GMX 백서

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

toRelayRouter` for same-chain delegated order execution and `MultichainSubaccountRouter` for cross-chain delegated order execution. At the contract level, the main account can authorize or remove a subaccount, set an expiry timestamp for delegated actions, cap how many delegated actions may be performed, and bind a subaccount to an integration id. The delegated subaccount can then create regular or TWAP orders, update orders, and cancel orders through the delegated trading surface. For delegated TWAP creation, call `SubaccountGelatoRelayRouter.createTwapOrder(...)` with the signed subaccount approval, `twapCount`, and `interval`. Each created TWAP part counts as one `SUBACCOUNT_ORDER_ACTION`, so the remaining action allowance must cover the full `twapCount`. ## Permission model The GMX subaccount model is scoped to delegated trading, not broad account delegation. Delegated access is designed for order management — it is narrower than giving a third party full account ownership, and it does not turn the delegated signer into a general-purpose owner of the account. ### Boundaries | Area | Behavior | | --- | --- | | Order outputs | Constrained to the main account | | Collateral and WNT | The delegated flow can spend the main account's collateral and WNT within the supported order flow | | Deposits, withdrawals, shifts, claims | Not delegated — these use their own routers and flows | For a summary of integration caveats, also review [Known issues](./known-issues.md). ## Roles in a delegated trading flow Most integrations end up with three roles: ### 1. Main account owner The owner wallet is the trust anchor for the trading account. It decides which delegated signer is allowed to trade, sets expiry and action-count limits, revokes delegated access, and optionally binds the subaccount to an `integrationId`. ### 2. Delegated trader or subaccount signer This signer executes delegated trading actions within the limits the owner authorized. Depending on your design, it may be a key generated and stored locally in the user's browser for one-click trading, a key generated and managed by your backend or trading service, or a wallet controlled directly by a trader operating under your system's authorization flow. ### 3. Backend or relayer Your backend may orchestrate owner-authorization flows, store or broker delegated session metadata, relay gasless order flow through `SubaccountGelatoRelayRouter`, and monitor expiry, action count, order lifecycle, and risk state. ## Common integration patterns GMX supports multiple delegated trading patterns. The right one depends on your custody and trust model. ### Browser-local one-click signer This is the closest match to the GMX interface's one-click trading flow described in [Trading overview](../../trading/overview.md#express-trading-and-one-click-trading). The delegated signer is created client-side, the key stays in the browser or local device storage, the owner authorizes delegated access with expiry and action limits, and the UI uses the delegated signer for order flow. This is the lowest-backend-custody model, but it shifts key-security risk to the browser environment. ### Backend-managed delegated signer This pattern is useful when your product already operates managed trading infrastructure. Your backend provisions and manages the delegated signer, the owner authorizes that signer as a subaccount, and your backend handles session lifecycle, revocation, and monitoring. This gives you more operational control, but the delegated signer becomes part of your key-management perimeter — treat it as a hot operational key with strict lifecycle controls. ### Relay-first owner approval flow This pattern is useful when you want owner-controlled authorization, delegated trading without repeated wallet popups, and gasless or sponsored execution. The owner signs the subaccount approval payload, the delegated signer signs the trade payload, and your relayer or backend submits through `SubaccountGelatoRelayRouter`. This is the most natural path when you want tight control over expiry, nonce handling, and replay protection while still delivering a low-friction user experience. ## Recommended end-to-end flow The most common delegated trading sequence looks like this: ### Step 1 — Choose the delegated signer model Decide whether the delegated signer will be browser-local, backend-managed, or externally controlled by the delegated trader. ### Step 2 — Create or identify the delegated signer This signer becomes the subaccount address that the main account owner authorizes. ### Step 3 — Owner authorizes delegated trading The owner enables delegated trading by setting the subaccount address, the delegated action type, expiry, maximum allowed action count, and an optional integration id. ### Step 4 — Store delegated session metadata Your application should track: | State | Notes | | --- | --- | | Subaccount address | The delegated signer's address | | Authorization status | Whether the subaccount is currently active | | Expiry | When delegated access expires | | Remaining action budget | How many actions remain before re-authorization | | Nonce state | Required if you are using relay-based approvals | | Integration id | If you use one | ### Step 5 — Execute delegated orders Use `SubaccountGelatoRelayRouter` for same-chain delegated order execution or `MultichainSubaccountRouter` for cross-chain delegated order execution. ### Step 6 — Monitor and refresh Your system should detect expiry approaching, action count approaching the cap, nonce invalidation, and revoked delegated access. ### Step 7 — Re-authorize or revoke When the delegated session is no longer valid, the owner can refresh authorization with a new expiry or action budget, or remove the subaccount entirely. ## Router selection Use `SubaccountGelatoRelayRouter` for same-chain delegated trading. This is the primary delegated order path used by the current GMX interface — it supports gasless delegated order creation, updates, cancellation, and subaccount removal, with owner-signed approval payloads and delegated trade payloads in one relay flow. Use `MultichainSubaccountRouter` for cross-chain delegated trading flows. A legacy `SubaccountRouter` contract remains deployed on all networks but is no longer used for order operations. The GMX interface only calls it for wallet-based subaccount removal outside the express flow. ## SDK, API, and contract responsibilities SDK v2 provides a managed one-click trading flow that generates the delegated signer, tracks its authorization state, and attaches the required approval when preparing and submitting Express Trading orders. It also supports independently generated subaccount signers through the explicit `subaccountAddress` and `subaccountApproval` fields. External signers must sign the prepared typed data directly because the high-level signing helper only has access to keys generated by that SDK instance. See [SDK v2 order examples](../../sdk/v2/examples.md#use-an-externally-managed-subaccount) for the complete prepare, sign, and submit flow. The SDK does not choose the custody or session architecture for your integration. In practice, delegated trading integrations still compose three layers: | Layer | Role | Notes | | --- | --- | --- | | Contracts | Source of truth for delegated authorization, order execution, and expiry/action-count/integration-id enforcement | Always the canonical state | | SDK | Typed read helpers, order-building convenience, and wallet-client integration | Useful in delegated flows, but you own the overall authorization and session architecture | | API | Near-live positions and orders over HTTP, lighter-weight read integration, and separation between read polling and write submission | See [API integration guide](../integration-guide.md) for freshness and consistency expectations | ## Monitoring architecture If delegated trading is part of a risk-managed product, design the monitoring layer intentionally rather than treating every read surface as interchangeable. | Surface | Best for | Latency | Examples | | --- | --- | --- | --- | | `Reader`, `DataStore`, `Multicall3` | Tight on-chain state loops | Lowest — same-block | Subaccount expiry, action-count consumption, delegated access status, position state for risk controls | | API and SDK reads | Application state and account views | Near-live | Dashboards, trader-facing views, normal order monitoring, eventual-consistency workflows after writes | | GraphQL and indexed surfaces | History and analytics | Higher | Investigations, reporting, trade history | :::tip Treat API and SDK reads as near-live, not as a strict same-block risk engine. Do not rely only on indexed or historical surfaces for latency-sensitive delegated trading controls. ::: See [Overview](./overview.md) for the read contracts and [Reader](./reader.md) for position and order helpers. ## Security guidance Delegated trading is a security-sensitive integration. Keep these constraints in mind: ### Limit scope aggressively Always use the protocol's built-in controls — expiry, maximum allowed action count, and optional integration id. Do not treat delegated access as open-ended if your use case does not require it. ### Be explicit about key custody If you use a browser-local signer, the browser becomes part of the trust boundary — compromised local storage or injected scripts can compromise the delegated signer. If you use a backend-managed signer, your backend becomes part of the custody boundary, and you should treat the delegated signer as a hot key with planned revocation, rotation, and auditability. ### Avoid unnecessary private-key transport If your integration can avoid transporting raw delegated private keys between backend and browser, that is generally the safer design. Prefer architectures where the delegated signer is generated client-side, or the backend signs on behalf of the delegated session without exposing raw key material to the browser. ### Separate read architecture from write architecture Do not tie delegated trade submission and risk monitoring to the same fragile polling path. In production integrations, treat authorization and write flow, state polling, and risk enforcement as separate responsibilities, even if they are implemented by the same service. ## What GMX provides vs what your integration must provide | GMX provides | Your integration provides | | --- | --- | | Delegated trading primitives | Signer custody design | | Gasless relay primitives | User authorization UX | | Owner-controlled expiry and action limits | Session lifecycle management | | Read contracts and APIs for account state | Monitoring and risk architecture | | Protocol-level enforcement, not custody | Key-security controls appropriate for your trust model | ## Next steps - [Advanced entry points](./advanced-entrypoints.md) for the raw delegated trading surfaces - [Reader](./reader.md) for position and order reads - [Overview](./overview.md) for read contracts and multicall guidance - [Trading overview](../../trading/overview.md#express-trading-and-one-click-trading) for the user-facing one-click trading model - [SDK v1 integration guide](../../sdk/v1/integration-guide.md) for SDK operational notes - [API integration guide](../integration-guide.md) for freshness, consistency, and read-surface guidance --- ## Event monitoring All protocol events are emitted through a single `EventEmitter` contract. Every event carries an `eventName` field, so you can monitor any protocol action by filtering on the `EventEmitter` address plus the `eventName` value — without needing to track individual logic contract addresses, which may be upgraded over time. The `EventEmitter` address for each network is listed on [Contract addresses](./addresses.md). For the full generated deployment inventory, see the [gmx-synthetics docs folder](https://github.com/gmx-io/gmx-synthetics/tree/updates/docs). ## Event types The `EventEmitter` contract defines three structured event signatures that differ by the number of indexed `bytes32` topics: | Event | Indexed topics | Use case | | --- | --- | --- | | `EventLog` | `eventNameHash` only | General events with no additional indexed lookup | | `EventLog1` | `eventNameHash`, `topic1` | Events indexed by one key (for example, an action key) | | `EventLog2` | `eventNameHash`, `topic1`, `topic2` | Events indexed by two keys (for example, market address and account) | All three variants include `msgSender`, `eventName` (as a plain string), `eventNameHash` (indexed for filtering), and `eventData` (a structured `EventUtils.EventLogData` payload containing typed arrays of addresses, uints, ints, bools, bytes32 values, bytes, and strings). The `EventEmitter` also exposes raw log functions (`emitDataLog1` through `emitDataLog4`) that emit unstructured logs using assembly. These are used for general-purpose data emission and don't follow the `EventLog` schema. Which variant a specific protocol event uses depends on how the emitting contract calls the `EventEmitter`. Check the relevant contract source to determine the correct variant before setting up a filter. ## Example: monitoring Timelock actions with OpenZeppelin Defender The following steps configure an alert that fires whenever an action is signalled on the `TimelockConfig` contract. Timelock signal events use `EventLog1` with `eventName == "SignalPendingAction"` and the action key as `topic1`. 1. In [OpenZeppelin Defender](https://defender.openzeppelin.com), select the "Monitor" (Sentinel) option. 2. Click "Create Monitor." 3. Enter a name for the monitor. 4. Select the target network. 5. Enter the `EventEmitter` address for that network in the "Addresses" field. 6. Under "Contract conditions," select "Events" > "EventLog1." 7. In the filter field below "EventLog1," enter `eventName == "SignalPendingAction"`. 8. Click "Next" and configure a notification channel. With this configuration, you receive a notification each time an action is signalled on the Timelock. --- ## ExchangeRouter The `ExchangeRouter` contract exposes the main protocol functions for creating orders, deposits, and withdrawals. For an overview of the contract architecture and execution model, see [Architecture](./architecture.md). ## Creating an order To create a swap, increase-position, or decrease-position order, you must first transfer the required tokens to the `OrderVault`, then call `ExchangeRouter.createOrder` in the same transaction. :::warning The token transfer and the `ExchangeRouter.createOrder` call must occur in a single transaction. If they are separated, other users may withdraw the transferred tokens before your order is created. ::: See the [ExchangeRouter tests](https://github.com/gmx-io/gmx-synthetics/blob/updates/test/router/ExchangeRouter.ts) for a complete example. ### ExchangeRouter.createOrder ```solidity function createOrder(IBaseOrderUtils.CreateOrderParams calldata params) returns (bytes32) ``` Use this to create swap, increase, or decrease orders through the router. For increase and swap orders, transfer the execution fee and any input collateral to the `OrderVault` in the same transaction, usually via `multicall`. **Example (TypeScript / ethers):** ```typescript await usdc.approve(router.address, collateralAmount); await exchangeRouter.multicall( [ exchangeRouter.interface.encodeFunctionData("sendWnt", [orderVault.address, executionFee]), exchangeRouter.interface.encodeFunctionData("sendTokens", [usdc.address, orderVault.address, collateralAmount]), exchangeRouter.interface.encodeFunctionData("createOrder", [ { addresses: { receiver: trader.address, cancellationReceiver: trader.address, callbackContract: ethers.constants.AddressZero, uiFeeReceiver: ethers.constants.AddressZero, market: marketToken, initialCollateralToken: usdc.address, swapPath: [], }, numbers: { sizeDeltaUsd, initialCollateralDeltaAmount: collateralAmount, triggerPrice: 0, acceptablePrice, executionFee, callbackGasLimit: 0, minOutputAmount: 0, validFromTime: 0, }, orderType: OrderType.MarketIncrease, decreasePositionSwapType: DecreasePositionSwapType.NoSwap, isLong: true, shouldUnwrapNativeToken: false, autoCancel: false, referralCode: ethers.constants.HashZero, dataList: [], }, ]), ], { value: executionFee } ); ``` **Parameters:** | Parameter | Type | Description | | --------- | ----------------------------------- | ------------------------------------- | | `params` | `IBaseOrderUtils.CreateOrderParams` | Struct containing order configuration | ### ExchangeRouter.createTwapOrder ```solidity function createTwapOrder( IBaseOrderUtils.CreateOrderParams calldata params, uint256 twapCount, uint256 interval ) returns (bytes32[] memory orderKeys) ``` Use this to split one order configuration into a time-weighted series. `twapCount` must be at least `2`, and `interval` must be greater than `0`. The first order uses `params.numbers.validFromTime`; each following order adds `interval` to the previous start time. Use a compatible non-market order type. `MarketSwap`, `MarketIncrease`, and `MarketDecrease` are invalid because market orders can't have a non-zero `validFromTime`; with multiple parts and a positive interval, later parts necessarily have a scheduled start time. The GMX interface uses `LimitSwap`, `LimitIncrease`, or `LimitDecrease` for TWAP parts. Transfer the aggregate collateral and execution fee to the `OrderVault` before this call in the same transaction. The contract allocates the received WNT execution fee evenly across the orders. For swap and increase orders, it also divides the received collateral evenly across them. If WNT is also the initial collateral token, the aggregate WNT transfer must first cover `params.numbers.executionFee * twapCount`; the remaining WNT is split as collateral. The function returns the order key for every part in creation order. **Parameters:** | Parameter | Type | Description | | ----------- | ----------------------------------- | ------------------------------------------------ | | `params` | `IBaseOrderUtils.CreateOrderParams` | Shared order configuration for every TWAP part | | `twapCount` | `uint256` | Number of orders to create; must be at least `2` | | `interval` | `uint256` | Seconds between consecutive `validFromTime` values | ### CreateOrderParams The order struct is split into address fields, numeric fields, and a small set of enums and flags. | Field | Description | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `addresses` | Group of address fields listed in [CreateOrderParamsAddresses](#createorderparamsaddresses). | | `numbers` | Group of numeric fields listed in [CreateOrderParamsNumbers](#createorderparamsnumbers). | | `orderType` | Order type enum listed in [OrderType](#ordertype). | | `decreasePositionSwapType` | Swap behavior for decrease orders listed in [DecreasePositionSwapType](#decreasepositionswaptype). | | `isLong` | `true` for a long position, `false` for a short position. | | `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. | | `autoCancel` | For `LimitDecrease` and `StopLossDecrease` orders, whether the order is cancelled automatically when the position closes. Ignored for all other order types. | | `referralCode` | Referral code to set for the trader alongside order creation. If the trader already has a referral code set, this parameter has no effect. | | `dataList` | Array of additional `bytes32` data. Pass an empty array if no extra data is needed. | ### CreateOrderParamsAddresses | Field | Description | | ------------------------ | -----------------------------
프로젝트로 돌아가기