# Frontend Integration

> The GMX protocol consists of smart contracts deployed on blockchains.

# Frontend Integration

The GMX protocol consists of smart contracts deployed on blockchains.

Users can interact directly with the smart contracts using blockchain explorers such as [Arbiscan](https://arbiscan.io/) and [SnowTrace](https://snowtrace.io/).

The [GMX frontend repository](https://github.com/gmx-io/gmx-interface) provides code to simplify contract interaction and to view protocol information and can be deployed by any community member.

A deployed instance of the GMX frontend is available at [https://app.gmx.io/](https://app.gmx.io/).

A backup instance of the GMX frontend is available at [https://gmxalt.io/](https://gmxalt.io/).

## Testnet frontend

A testnet GMX frontend is available at [https://test.gmx-interface.pages.dev/](https://test.gmx-interface.pages.dev/). Use it to test against testnet networks (Arbitrum Sepolia and Avalanche Fuji) and to access debug mode tooling.

## Running a frontend

Integrators can either deploy the [GMX frontend repository](https://github.com/gmx-io/gmx-interface) or build their own frontend, aggregator, or backend-driven trading flow.

The supported technical earning options are UI fees and referrals. UI fees pay a configured receiver on supported transactions. Referrals let a registered referral-code owner earn affiliate rewards on position fees when the referral code is applied to a trader.

One-Click Trading is not an earning option by itself. It is a delegated trading UX pattern that lets users approve a limited subaccount signer for faster order flow.

If your frontend reads orders from the GMX API, each order response includes `uiFeeFactor`. This is the 30-decimal factor snapshotted when the order was created, so use it for historical order attribution instead of looking up the receiver's current factor. Orders created before the snapshot field was introduced return `uiFeeFactor: null`; treat that as unavailable historical data, not as zero. The same rule applies to orders nested under a position response when you request `includeRelatedOrders: true`.

### If you use the GMX Interface repository

To run the GMX frontend locally, follow the instructions in the [GMX frontend repository](https://github.com/gmx-io/gmx-interface). You can also deploy it using a static hosting service such as Vercel, Netlify, or Cloudflare Pages.

#### UI fee receiver

To configure the UI fee receiver, add `VITE_APP_UI_FEE_RECEIVER` to your `.env` file. Set it to the wallet address that receives [UI fees](./contracts/fees.md#ui-fee).

```bash
VITE_APP_UI_FEE_RECEIVER=0xYourReceiverAddressHere
```

The current interface sets `uiFeeReceiver` for orders and for GM and GLV deposits, withdrawals, and shifts. The receiver account must configure its UI fee factor with `ExchangeRouter.setUiFeeFactor`. A configured receiver can claim accrued UI fees through `ExchangeRouter.claimUiFees`.

#### Referral codes

To apply a referral code from your frontend, link users to the interface with a `ref` query parameter.

```text
https://your-interface.example/#/?ref=YourReferralCode
```

The interface stores the encoded referral code in browser local storage as `GMX-referralCode`. When a user creates an order, the interface can pass the stored code to the contracts only if the trader does not already have an on-chain referral code, the local code has a registered owner, and the code is valid where `ReferralCodeValidator` is active. Existing pre-validator codes remain valid; new follower-chain codes may need to wait for leader-chain validation to propagate.

#### One-Click Trading storage

The GMX interface generates a random subaccount private key in the browser, encrypts that private key with the main account address, and stores One-Click Trading configuration in browser local storage under keys scoped by `chainId` and account. The key doesn't come from a wallet signature: the main wallet signs a `SubaccountApproval` for its address.

The browser stores the One-Click Trading configuration under `[chainId, account, "one-click-trading-config"]` and the subaccount approval under `[chainId, account, "subaccount-approval"]`.

#### Custom RPC URLs

To override the default RPC endpoints for Arbitrum, Avalanche, or MegaETH, add the corresponding variable to your `.env` file. Each variable takes a JSON array of RPC URLs, which the interface uses as fallback endpoints. Replace the placeholder URLs with endpoints from your RPC provider.

```dotenv
VITE_APP_ARBITRUM_RPC_URLS=["https://your-arbitrum-rpc-provider.example/rpc"]
VITE_APP_AVALANCHE_RPC_URLS=["https://your-avalanche-rpc-provider.example/rpc"]
VITE_APP_MEGAETH_RPC_URLS=["https://your-megaeth-rpc-provider.example/rpc"]
```

### If you use your own frontend or aggregator

Custom integrations should not rely on GMX Interface environment variables or local storage keys. Build these flows directly in your own order creation, storage, and claiming logic.

#### UI fees

1. Choose the wallet address that should receive UI fees.
2. From that receiver address, call `ExchangeRouter.setUiFeeFactor(uiFeeFactor)`. The factor is a 30-decimal percentage and must not exceed `MAX_UI_FEE_FACTOR`.
3. When you create supported actions, pass that address as `uiFeeReceiver` in the action parameters. Supported actions include deposits, withdrawals, swap orders, increase and decrease position orders, GLV deposits and withdrawals, and shifts.
4. Claim accrued UI fees by calling `ExchangeRouter.claimUiFees(markets, tokens, receiver)` from the UI fee receiver address.

See [Fees](./contracts/fees.md#ui-fee) and [ExchangeRouter UI fee configuration](./contracts/exchange-router.md#ui-fee-configuration) for the contract details.

#### Referrals

1. Register and own the referral code on each network where you want to earn affiliate rewards. For new validator-gated codes, prefer registration on Arbitrum, which is the leader chain for referral-code validation.
2. If you create orders through SDK v2 or the hosted GMX API order prepare flow, pass the code as `referralCode` in the prepare request. The API accepts either the human-readable registered code or an already encoded `bytes32` value. Human-readable codes can contain letters, digits, and underscores, and can be up to 20 characters long.
3. If you create orders through direct contract calls, encode the referral code as `bytes32` before passing it to order creation.
4. Before applying a code for a trader, read `ReferralStorage.traderReferralCodes(trader)` and `ReferralStorage.codeOwners(referralCode)`. On-chain reads use the `bytes32`-encoded referral code. Where `ReferralCodeValidator` is active, also check `ReferralCodeValidator.isValid(referralCode)`.
5. If the trader has no on-chain referral code, `codeOwners(referralCode)` is not the zero address, and the code is valid where validator checks apply, pass the code when creating the trader's order.
6. Claim accrued affiliate rewards by calling `ExchangeRouter.claimAffiliateRewards(markets, tokens, receiver)` from the referral-code owner address.

A referral code is valid for affiliate rewards only if it has a registered owner and, for new validator-gated codes, `ReferralCodeValidator.isValid(referralCode)` returns true. Existing pre-validator codes remain valid. In practice, the code is set on the first successful order transaction that includes a valid registered code for a trader with no existing referral code. After a trader has an on-chain referral code, later order transactions cannot replace it through the normal order referral assignment path. That path skips zero referral codes and does not overwrite an existing trader referral code.

Changing an existing trader referral code is normally a separate user action that requires the user to sign a referral-code change transaction or relay message. Integrations should not bundle or disguise a referral-code change as part of any other action. GMX-maintained protocol services may still assign GMX-owned codes for organic volume discounts or referral graduation, such as `EARNED_TRADER_DISCOUNT_5`, `EARNED_TRADER_DISCOUNT_10`, `DIRECT_GMX_DISCOUNT_5`, and `DIRECT_GMX_DISCOUNT_10`; custom integrations should treat those as protocol-managed codes and should not try to overwrite them through normal order creation.

Registered referral-code owners earn affiliate rewards on position fees only. Position fees are the fees charged on leveraged position size when a trader opens, closes, increases, or partially decreases a position; they do not include swap fees, deposit or withdrawal fees, borrowing fees, or funding fees. See [Referrals](../referrals.md) for the user-facing referral flow and tier details.

#### One-Click Trading and delegated signing

If your integration exposes One-Click Trading or another delegated trading flow, you must provide your own storage and session management.

1. Choose the delegated signer model: browser-local signer, backend-managed signer, or an externally controlled delegated wallet.
2. Create or identify the delegated signer address.
3. Have the main account authorize the delegated signer with expiry, maximum action count, delegated action type, and any integration id your flow uses.
4. Store delegated session metadata in your own origin or backend. Track at least the subaccount address, authorization status, expiry, remaining action count, nonce state for relay flows, and revocation state.
5. Submit delegated orders through the supported delegated trading routers, such as `SubaccountGelatoRelayRouter` for same-chain delegated order flow or `MultichainSubaccountRouter` for cross-chain delegated order flow.
6. Monitor expiry, action-count usage, nonce invalidation, order lifecycle, and revocation. Refresh or revoke delegated access when the session is no longer valid.

Because browser storage is origin-scoped, a custom frontend or aggregator cannot reuse One-Click Trading state stored by the GMX Interface deployment. If your integration manages the delegated signer on a backend for bots, agents, or managed trading services, your backend becomes responsible for hot-key custody, session lifecycle, revocation, and monitoring. See [Delegated trading integration](./contracts/delegated-trading.md) for the subaccount and relay model.
