bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 28쪽
ferred to the contract during the update is added to the order's execution fee.
### ExchangeRouter.updateOrder
```solidity
function updateOrder(
bytes32 key,
uint256 sizeDeltaUsd,
uint256 acceptablePrice,
uint256 triggerPrice,
uint256 minOutputAmount,
uint256 validFromTime,
bool autoCancel
)
```
Use this to change the parameters of a pending limit or trigger order. The order is also unfrozen if it was previously frozen due to an execution error.
**Parameters:**
| Parameter | Type | Description |
| ---------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key` | `bytes32` | Unique key of the order to update, returned by `createOrder`. |
| `sizeDeltaUsd` | `uint256` | New position size delta in USD. |
| `acceptablePrice`| `uint256` | New acceptable execution price in contract price format. For long increase orders, the order is cancelled if the execution price is greater than `acceptablePrice`. For short increase orders, the order is cancelled if the execution price is less than `acceptablePrice`. |
| `triggerPrice` | `uint256` | New trigger price for limit and stop-loss orders in contract price format. |
| `minOutputAmount`| `uint256` | New minimum output amount for swap orders or minimum USD value for decrease orders. |
| `validFromTime` | `uint256` | New timestamp from which the order becomes valid. Pass `0` for immediate validity. |
| `autoCancel` | `bool` | Whether to automatically cancel the order when the associated position closes. Only applies to `LimitDecrease` and `StopLossDecrease` orders. |
## Cancelling requests
You can cancel pending orders, deposits, withdrawals, and shifts that you created. When a request is cancelled, the deposited funds and any unused execution fee are returned to the creator. Cancelling a market order, deposit, withdrawal, or shift is subject to a delay period -- the request must have been pending for at least the configured `requestExpirationTime` before it can be cancelled. If you attempt to cancel too early, the transaction reverts with `RequestNotYetCancellable`. Limit, Stop Market, and TP/SL orders aren't subject to this delay.
On Arbitrum, Avalanche, and MegaETH, keepers also cancel expired requests automatically. If a Market Swap, Market Increase, or Market Decrease order, deposit, withdrawal, or shift is still pending about 60 seconds after it becomes cancellable, a keeper cancels it. Because `requestExpirationTime` is 300 seconds on these chains, this happens about six minutes or more after the request was created or last updated. GLV deposits and withdrawals are cancelled the same way (see [GlvRouter](./glv-router.md)). This timing is keeper behavior, not a protocol guarantee. Funds and the execution fee are returned the same way as for a cancellation you send yourself, and the keeper keeps no part of the execution fee.
Your integration can therefore receive a cancellation it didn't trigger. A keeper cancellation emits the same event as a cancellation you send yourself (`OrderCancelled`, `DepositCancelled`, `WithdrawalCancelled`, or `ShiftCancelled`, with reason `USER_INITIATED_CANCEL`), and your callback contract's cancellation callback runs as usual. The event doesn't show who sent the cancellation. To tell a keeper cancellation from your own, check the transaction: a keeper calls the handler contract (for example, `OrderHandler`) directly instead of going through `ExchangeRouter`. See [Order keepers](./architecture.md#order-keepers) for more on keeper behavior.
### ExchangeRouter.cancelOrder
```solidity
function cancelOrder(bytes32 key)
```
Cancels a pending order. Only the order's creator can cancel it.
**Parameters:**
| Parameter | Type | Description |
| --------- | --------- | ------------------------------------------------------------ |
| `key` | `bytes32` | Unique key of the order to cancel, returned by `createOrder`.|
### ExchangeRouter.cancelDeposit
```solidity
function cancelDeposit(bytes32 key)
```
Cancels a pending deposit. Only the deposit's creator can cancel it. The initial deposit tokens are returned to the creator's account.
**Parameters:**
| Parameter | Type | Description |
| --------- | --------- | ---------------------------------------------------------------- |
| `key` | `bytes32` | Unique key of the deposit to cancel, returned by `createDeposit`.|
### ExchangeRouter.cancelWithdrawal
```solidity
function cancelWithdrawal(bytes32 key)
```
Cancels a pending withdrawal. Only the withdrawal's creator can cancel it. The GM market tokens are returned to the creator's account.
**Parameters:**
| Parameter | Type | Description |
| --------- | --------- | ------------------------------------------------------------------------ |
| `key` | `bytes32` | Unique key of the withdrawal to cancel, returned by `createWithdrawal`. |
### ExchangeRouter.cancelShift
```solidity
function cancelShift(bytes32 key)
```
Cancels a pending shift. Only the shift's creator can cancel it. The source market's GM tokens are returned to the creator's account.
**Parameters:**
| Parameter | Type | Description |
| --------- | --------- | ------------------------------------------------------------------ |
| `key` | `bytes32` | Unique key of the shift to cancel, returned by `createShift`. |
## Setting a callback contract
You can set a persistent callback contract for a specific market. The protocol uses this saved callback contract for liquidations and auto-deleveraging (ADL), where no user-initiated order exists to specify a callback. This lets your contract receive notifications when your position is liquidated or reduced by ADL.
### ExchangeRouter.setSavedCallbackContract
```solidity
function setSavedCallbackContract(address market, address callbackContract)
```
Saves a callback contract for the caller's account in the given market. The protocol calls this contract during liquidation and ADL events for that account and market.
**Parameters:**
| Parameter | Type | Description |
| ------------------ | --------- | ---------------------------------------------------------------------------------- |
| `market` | `address` | Market address to associate the callback contract with. |
| `callbackContract` | `address` | Contract address to call on liquidation or ADL. Pass the zero address to remove it.|
## Claiming fees and rewards
These functions let you claim accumulated fees and rewards across multiple markets in a single transaction. The `markets` and `tokens` arrays must have the same length -- each index pairs a market with the token to claim.
### ExchangeRouter.claimFundingFees
```solidity
function claimFundingFees(
address[] memory markets,
address[] memory tokens,
address receiver
) returns (uint256[] memory)
```
Claims accumulated positive funding fees for the caller across the specified market-token pairs. Funding fees accrue when you hold a position on the less-crowded side of a market.
**Parameters:**
| Parameter | Type | Description |
| ---------- | ----------- | ----------------------------------------------------------------------------- |
| `markets` | `address[]` | Array of market addresses to claim funding fees from. |
| `tokens` | `address[]` | Array of token addresses, one per market, specifying which token to claim. |
| `receiver` | `address` | Address that receives the claimed funding fees. |
**Returns:** `uint256[]` -- the amount claimed for each market-token pair.
### ExchangeRouter.claimCollateral
```solidity
function claimCollateral(
address[] memory markets,
address[] memory tokens,
uint256[] memory timeKeys,
address receiver
) returns (uint256[] memory)
```
Claims collateral that was capped due to negative price impact. When a position's price impact is capped, the excess amount is stored and becomes claimable over time as the price impact factor recovers. Each claim is keyed by the timestamp when the capped amount was recorded.
**Parameters:**
| Parameter | Type | Description |
| ---------- | ----------- | ---------------------------------------------------------------------------------------- |
| `markets` | `address[]` | Array of market addresses to claim collateral from. |
| `tokens` | `address[]` | Array of token addresses, one per market, specifying which token to claim. |
| `timeKeys` | `uint256[]` | Array of timestamps identifying the specific capped collateral entries to claim. |
| `receiver` | `address` | Address that receives the claimed collateral. |
**Returns:** `uint256[]` -- the amount claimed for each entry.
### ExchangeRouter.claimAffiliateRewards
```solidity
function claimAffiliateRewards(
address[] memory markets,
address[] memory tokens,
address receiver
) returns (uint256[] memory)
```
Claims accumulated affiliate (referral) rewards for the caller across the specified market-token pairs. Rewards accrue when traders you referred generate trading fees.
**Parameters:**
| Parameter | Type | Description |
| ---------- | ----------- | -------------------------------------------------------------------------------- |
| `markets` | `address[]` | Array of market addresses to claim affiliate rewards from. |
| `tokens` | `address[]` | Array of token addresses, one per market, specifying which token to claim. |
| `receiver` | `address` | Address that receives the claimed affiliate rewards. |
**Returns:** `uint256[]` -- the amount claimed for each market-token pair.
## UI fee configuration
These functions let an integration configure its UI fee factor and claim accumulated UI fees.
### ExchangeRouter.setUiFeeFactor
```solidity
function setUiFeeFactor(uint256 uiFeeFactor)
```
Sets the UI fee factor for the caller's account. The factor is stored in the protocol configuration and is applied when users submit actions with your address as `uiFeeReceiver`.
**Parameters:**
| Parameter | Type | Description |
| -------------- | --------- | --------------------------------------------------------------------------- |
| `uiFeeFactor` | `uint256` | UI fee percentage in 30-decimal precision. The value must not exceed `MAX_UI_FEE_FACTOR`. |
### ExchangeRouter.claimUiFees
```solidity
function claimUiFees(
address[] memory markets,
address[] memory tokens,
address receiver
) returns (uint256[] memory)
```
Claims accumulated UI fees for the caller across the specified market-token pairs. The caller address (`msg.sender`) is treated as the `uiFeeReceiver` whose balance is being claimed.
**Parameters:**
| Parameter | Type | Description |
| ---------- | ----------- | ------------------------------------------------------------------------- |
| `markets` | `address[]` | Array of market addresses to claim UI fees from. |
| `tokens` | `address[]` | Array of token addresses, one per market, specifying which token to claim. |
| `receiver` | `address` | Address that receives the claimed UI fees. |
**Returns:** `uint256[]` -- the amount claimed for each market-token pair.
---
## Fees(Contracts)
This page documents fee types, execution fee calculation, and how to retrieve fee parameters from the DataStore.
## UI fee
UI fees are charged on top of the base protocol fee. The percentage is based on the `uiFeeFactor` configured for the `uiFeeReceiver` address you pass when creating an action. For more information, see [Running a frontend](../frontend-integration.md#running-a-frontend).
Configure the UI fee percentage for your address by calling `ExchangeRouter.setUiFeeFactor`. The `uiFeeFactor` is a percentage value over `10^30`. For example, if the `uiFeeFactor` is `2 * 10^25`, the percentage charged is `(2 * 10^25) / (10^30) = 0.00002 = 0.002%`. The call reverts with `InvalidUiFeeFactor` if the value exceeds the maximum.
The maximum `uiFeeFactor` is capped by `dataStore.getUint(Keys.MAX_UI_FEE_FACTOR)`.
The effective `uiFeeFactor` is snapshotted into each request when it is created. Changing the configured factor later does not change pending deposits, withdrawals, orders, shifts, GLV deposits, or GLV withdrawals.
You can pass the `uiFeeReceiver` value for the following actions:
- Deposits
- Withdrawals
- Swap orders
- Increase and decrease position orders (Market Increase, Limit Increase, Market Decrease, Limit Decrease, Stop-Loss, Take-Profit)
- GLV deposits
- GLV withdrawals
- Shifts
For deposits, withdrawals, and swaps, the fee is a percentage of the input amount. For increase and decrease position orders, the fee is a percentage of the position size change.
UI fees are credited when deposits, withdrawals, and orders execute. Call `ExchangeRouter.claimUiFees` to claim accumulated fees at any time. The caller's address (`msg.sender`) is used as the `uiFeeReceiver` for the claim.
## Execution fee
Creating a deposit, order, withdrawal, shift, GLV deposit, or GLV withdrawal request requires sending an `executionFee` as the transaction value.
During creation, the contracts verify that the provided `executionFee` is at least the minimum, calculated as:
```
tx.gasprice * GasUtils.adjustGasLimitForEstimate(dataStore, estimatedGasLimit, oraclePriceCount)
```
To calculate the `estimatedGasLimit`, use the appropriate function:
- For deposits: `GasUtils.estimateExecuteDepositGasLimit`
- For withdrawals: `GasUtils.estimateExecuteWithdrawalGasLimit`
- For orders: `GasUtils.estimateExecuteOrderGasLimit`
- For shifts: `GasUtils.estimateExecuteShiftGasLimit`
- For GLV deposits: `GasUtils.estimateExecuteGlvDepositGasLimit`
- For GLV withdrawals: `GasUtils.estimateExecuteGlvWithdrawalGasLimit`
Because `tx.gasprice` fluctuates based on network usage, add a buffer to reduce the risk of the creation transaction reverting. If the provided `executionFee` is below the minimum, the transaction reverts with `InsufficientExecutionFee`. Upon execution, any excess execution fee is refunded to the request's `account` address.
## Funding
For an overview of how funding fees work, see [adaptive funding](../../trading/fees.md#adaptive-funding).
Retrieve funding fee parameters from the [DataStore](./overview.md#reading-values) using these keys. All keys are per-market. The minimum and maximum funding-factor keys additionally include the paying side.
| Key | Description |
| --- | --- |
| `FUNDING_FACTOR` | Base funding factor per second |
| `FUNDING_EXPONENT_FACTOR` | Exponent applied to the open interest imbalance ratio |
| `FUNDING_INCREASE_FACTOR_PER_SECOND` | Rate at which the funding factor increases per second |
| `MIN_FUNDING_INCREASE_RATE_PER_SECOND` | Minimum amount by which adaptive funding increases per second while the imbalance is non-zero |
| `FUNDING_DECREASE_FACTOR_PER_SECOND` | Rate at which the funding factor decreases per second |
| `MIN_FUNDING_FACTOR_PER_SECOND` | Minimum funding factor per second, keyed separately for long-paying and short-paying states |
| `MAX_FUNDING_FACTOR_PER_SECOND` | Maximum funding factor per second, keyed separately for long-paying and short-paying states |
| `THRESHOLD_FOR_STABLE_FUNDING` | Imbalance threshold below which funding stays stable |
| `THRESHOLD_FOR_DECREASE_FUNDING` | Imbalance threshold below which the funding factor decreases |
## Borrowing
For an overview of how borrow fees work, see [borrow fees](../../trading/fees.md#borrow-fees).
Retrieve borrow fee parameters from the [DataStore](./overview.md#reading-values) using these keys. Each market uses one of the two models below.
### Global settings
These global DataStore keys affect borrowing calculations across all markets.
| Key | Description |
| --- | --- |
| `SKIP_BORROWING_FEE_FOR_SMALLER_SIDE` | If true, the side with smaller open interest pays zero borrow fees |
| `USE_OPEN_INTEREST_IN_TOKENS_FOR_BALANCE` | Controls how open interest balance is compared: when true, uses `openInterestInTokens` multiplied by the current index token price (notional value); when false, uses the `openInterest` USD values recorded at position entry |
### Kink model
| Key | Description |
| --- | --- |
| `OPTIMAL_USAGE_FACTOR` | Utilization threshold where the rate slope increases |
| `BASE_BORROWING_FACTOR` | Base rate factor below optimal utilization |
| `ABOVE_OPTIMAL_USAGE_BORROWING_FACTOR` | Rate factor applied above optimal utilization |
Some markets configure this model without an effective kink: `OPTIMAL_USAGE_FACTOR` is set to `100%`, while `BASE_BORROWING_FACTOR` and `ABOVE_OPTIMAL_USAGE_BORROWING_FACTOR` are set to the same annualized rate. This preserves a single borrowing-rate slope across the valid utilization range.
### Curve (power) model
| Key | Description |
| --- | --- |
| `BORROWING_FACTOR` | Per-market borrowing factor for longs and shorts |
| `BORROWING_EXPONENT_FACTOR` | Per-market exponent for longs and shorts |
## Position and swap fees
Retrieve position and swap fee parameters from the [DataStore](./overview.md#reading-values) using these keys. Fee factors are percentage values over `10^30`.
### Position fees
| Key | Description |
| --- | --- |
| `POSITION_FEE_FACTOR` | Percentage fee deducted on position increase and decrease, based on position size change |
| `POSITION_IMPACT_FACTOR` | Price impact factor for position actions |
| `MAX_POSITION_IMPACT_FACTOR` | Cap on negative price impact for positions |
| `MAX_POSITION_IMPACT_FACTOR_FOR_LIQUIDATIONS` | Cap on negative price impact applied during liquidations |
| `POSITION_IMPACT_EXPONENT_FACTOR` | Exponent for position price impact calculation |
| `POSITION_IMPACT_POOL_DISTRIBUTION_RATE` | Rate at which the position impact pool is distributed to the market pool |
| `PRO_DISCOUNT_FACTOR` | Fee discount factor applied to pro-tier traders |
### Swap fees
| Key | Description |
| --- | --- |
| `SWAP_FEE_FACTOR` | Percentage fee deducted on swaps, based on swap amount |
| `ATOMIC_SWAP_FEE_FACTOR` | Percentage fee deducted on atomic swaps using on-chain price feeds |
| `SWAP_IMPACT_FACTOR` | Price impact factor for swaps |
| `SWAP_IMPACT_EXPONENT_FACTOR` | Exponent for swap price impact calculation |
| `ATOMIC_SWAP_FEE_TYPE` | Type flag that determines the atomic swap fee behavior |
### Deposit and withdrawal fees
| Key | Description |
| --- | --- |
| `DEPOSIT_FEE_FACTOR` | Percentage fee deducted on deposits, based on deposit amount |
| `WITHDRAWAL_FEE_FACTOR` | Percentage fee deducted on withdrawals, based on withdrawal amount |
| `ATOMIC_WITHDRAWAL_FEE_FACTOR` | Percentage fee deducted on atomic withdrawals using on-chain price feeds |
### Liquidation fees
| Key | Description |
| --- | --- |
| `LIQUIDATION_FEE_FACTOR` | Percentage fee deducted when a position is liquidated |
### Fee receiver factors
These parameters control the share of collected fees allocated to the fee receiver. Each is a percentage value over `10^30`.
| Key | Description |
| --- | --- |
| `POSITION_FEE_RECEIVER_FACTOR` | Share of position fees allocated to the fee receiver |
| `SWAP_FEE_RECEIVER_FACTOR` | Share of swap fees allocated to the fee receiver |
| `BORROWING_FEE_RECEIVER_FACTOR` | Share of borrow fees allocated to the fee receiver |
| `LIQUIDATION_FEE_RECEIVER_FACTOR` | Share of liquidation fees allocated to the fee receiver |
## Relay fees
These parameters control the relay fee that the relay routers charge for gasless transactions submitted through GMX Relay. The key names keep their original `GELATO_` prefix, but the fee logic doesn't depend on Gelato.
| Key | Description |
| --- | --- |
| `GELATO_RELAY_FEE_MULTIPLIER_FACTOR` | Multiplier applied to the relay fee calculation |
| `GELATO_RELAY_FEE_BASE_AMOUNT` | Base fee amount for relay transactions |
| `MAX_RELAY_FEE_SWAP_USD` | Global maximum USD value of a relay-fee token swap |
| `MAX_RELAY_FEE_SWAP_USD_FOR_SUBACCOUNT` | Additional maximum USD value of a relay-fee token swap when the call is made by a subaccount |
The current production configuration sets `MAX_RELAY_FEE_SWAP_USD` to `100 USD`. The cap is enforced when `feeSwapPath` 프로젝트로 돌아가기