# GmxV2PositionManager

**Inherits:** Initializable, IHedgeManager, IOrderCallbackReceiver, IGasFeeCallbackReceiver

**Author:** Logarithm Labs

GmxV2PositionManager is a dedicated smart contract that interacts with the GMX protocol to maintain and adjust short positions in alignment with the strategy’s delta-neutral requirements. This manager operates as an auxiliary component to the main strategy, ensuring that the hedge remains effective by dynamically adjusting the size of the short position based on market movements.

*GmxV2PositionManager is an upgradeable smart contract, deployed through the beacon proxy pattern.*

### State Variables

#### MIN\_IDLE\_COLLATERAL\_USD

```solidity
uint256 constant MIN_IDLE_COLLATERAL_USD = 1e31;
```

#### GmxV2PositionManagerStorageLocation

```solidity
bytes32 private constant GmxV2PositionManagerStorageLocation =
    0xf08705b56fbd504746312a6db5deff16fc51a9c005f5e6a881519498d59a9600;
```

### Functions

#### \_getGmxV2PositionManagerStorage

```solidity
function _getGmxV2PositionManagerStorage() private pure returns (GmxV2PositionManagerStorage storage $);
```

#### onlyStrategy

```solidity
modifier onlyStrategy();
```

#### whenNotPending

```solidity
modifier whenNotPending();
```

#### initialize

```solidity
function initialize(address strategy_, address config_, address gmxGasStation_, address marketKey_)
    external
    initializer;
```

#### adjustPosition

Called to adjust the hedge position based on specified parameters.

```solidity
function adjustPosition(AdjustPositionPayload calldata params) external onlyStrategy whenNotPending;
```

**Parameters**

| Name     | Type                    | Description |
| -------- | ----------------------- | ----------- |
| `params` | `AdjustPositionPayload` |             |

#### keep

Called to maintain or adjust the hedge position as required by strategy logic.

*Realizes the claimable funding or increases collateral if there are idle assets*

```solidity
function keep() external onlyStrategy whenNotPending;
```

#### claimFunding

*Claims all the claimable funding fees. This is callable by anyone. Collateral funding amount is transferred to this position manager, otherwise transferred to strategy*

```solidity
function claimFunding() public;
```

#### claimCollateral

*Claims all the claimable collateral amount. Note: This amount is stored by account, token, timeKey and therefore the only way to figure it out is to use GMX events.*

```solidity
function claimCollateral(address token, uint256 timeKey) external;
```

**Parameters**

| Name      | Type      | Description                                                              |
| --------- | --------- | ------------------------------------------------------------------------ |
| `token`   | `address` | The token address derived from the gmx event: ClaimableCollateralUpdated |
| `timeKey` | `uint256` | The timeKey value derived from the gmx event: ClaimableCollateralUpdated |

#### afterOrderExecution

```solidity
function afterOrderExecution(bytes32 key, Order.Props calldata order, EventUtils.EventLogData calldata)
    external
    override;
```

#### afterOrderCancellation

```solidity
function afterOrderCancellation(bytes32 key, Order.Props calldata order, EventUtils.EventLogData calldata)
    external
    override;
```

#### afterOrderFrozen

```solidity
function afterOrderFrozen(bytes32, Order.Props memory, EventUtils.EventLogData memory) external pure override;
```

#### refundExecutionFee

```solidity
function refundExecutionFee(bytes32, EventUtils.EventLogData memory) external payable;
```

#### positionNetBalance

Gets the net collateral balance of the position, including pending adjustments.

```solidity
function positionNetBalance() public view returns (uint256);
```

**Returns**

| Name     | Type      | Description                                        |
| -------- | --------- | -------------------------------------------------- |
| `<none>` | `uint256` | The total collateral asset amount in the position. |

#### currentLeverage

Retrieves the current leverage of the position.

```solidity
function currentLeverage() public view returns (uint256);
```

**Returns**

| Name     | Type      | Description                      |
| -------- | --------- | -------------------------------- |
| `<none>` | `uint256` | The leverage ratio as a uint256. |

#### positionSizeInTokens

Returns the current size of the position in terms of index tokens.

```solidity
function positionSizeInTokens() public view returns (uint256);
```

**Returns**

| Name     | Type      | Description                               |
| -------- | --------- | ----------------------------------------- |
| `<none>` | `uint256` | The size of the position in index tokens. |

#### getExecutionFee

*Calculates the execution fee that is needed from gmx when increasing and decreasing.*

```solidity
function getExecutionFee() public view returns (uint256 feeIncrease, uint256 feeDecrease);
```

**Returns**

| Name          | Type      | Description                    |
| ------------- | --------- | ------------------------------ |
| `feeIncrease` | `uint256` | The execution fee for increase |
| `feeDecrease` | `uint256` | The execution fee for decrease |

#### getClaimableFundingAmounts

*The current claimable funding amounts that are not accrued*

```solidity
function getClaimableFundingAmounts()
    external
    view
    returns (uint256 claimableLongTokenAmount, uint256 claimableShortTokenAmount);
```

#### getAccruedClaimableFundingAmounts

*The accrued claimable token amounts.*

```solidity
function getAccruedClaimableFundingAmounts()
    external
    view
    returns (uint256 claimableLongTokenAmount, uint256 claimableShortTokenAmount);
```

#### cumulativeFundingAndBorrowingFeesUsd

*The total cumulated funding fee and borrowing fee in usd including next fees.*

```solidity
function cumulativeFundingAndBorrowingFeesUsd()
    external
    view
    returns (uint256 fundingFeeUsd, uint256 borrowingFeeUsd);
```

#### needKeep

Checks whether the `keep` function needs to be called to maintain the position.

*Checks if the claimable funding amount is over than max share or if idle collateral is bigger than minimum requirement so that the position can be settled to add it to position’s collateral.*

```solidity
function needKeep() external view returns (bool);
```

**Returns**

| Name     | Type   | Description                                        |
| -------- | ------ | -------------------------------------------------- |
| `<none>` | `bool` | A boolean indicating if `keep` should be executed. |

#### \_createOrder

*Creates increase/decrease GMX order*

```solidity
function _createOrder(InternalCreateOrderParams memory params) private returns (bytes32);
```

#### \_processIncreasePosition

*Used in GMX callback functions.*

```solidity
function _processIncreasePosition(uint256 initialCollateralDeltaAmount, uint256 sizeInTokens) private;
```

#### \_processDecreasePosition

*Used in GMX callback functions.*

```solidity
function _processDecreasePosition(uint256 sizeInTokens) private;
```

#### \_recordPositionSize

*Stores new size and return delta size in tokens*

```solidity
function _recordPositionSize(uint256 sizeInTokens) private returns (uint256);
```

#### \_processPendingPositionFee

*Processes the pending position fees.*

```solidity
function _processPendingPositionFee(bool isIncrease, bool isExecuted) private;
```

#### \_getGmxParams

*Derives a set of gmx params that are need to call gmx smart contracts.*

```solidity
function _getGmxParams(IGmxConfig _config) private view returns (GmxV2Lib.GmxParams memory);
```

#### \_onlyStrategy

```solidity
function _onlyStrategy() private view;
```

#### \_whenNotPending

```solidity
function _whenNotPending() private view;
```

#### \_isPending

*True when a GMX order has been submitted, but not executed.*

```solidity
function _isPending() private view returns (bool);
```

#### \_validateOrderHandler

*Validates if the caller is OrderHandler of gmx*

```solidity
function _validateOrderHandler(bytes32 orderKey, bool isIncrease) private view;
```

#### \_setPendingOrderKey

```solidity
function _setPendingOrderKey(bytes32 orderKey, bool isIncrease) private;
```

#### config

The address of gmx config smart contract.

```solidity
function config() public view returns (IGmxConfig);
```

#### collateralToken

Returns the address of the collateral token used in the position.

```solidity
function collateralToken() public view returns (address);
```

**Returns**

| Name     | Type      | Description                          |
| -------- | --------- | ------------------------------------ |
| `<none>` | `address` | The address of the collateral token. |

#### strategy

The address of strategy.

```solidity
function strategy() public view returns (address);
```

#### gmxGasStation

The address of the gmx gas station smart contract.

```solidity
function gmxGasStation() public view returns (address);
```

#### marketToken

The address of gmx market token where position is opened at.

```solidity
function marketToken() public view returns (address);
```

#### indexToken

Returns the address of the index token used in the position.

```solidity
function indexToken() public view returns (address);
```

**Returns**

| Name     | Type      | Description                     |
| -------- | --------- | ------------------------------- |
| `<none>` | `address` | The address of the index token. |

#### longToken

The address of long token of the opened market.

```solidity
function longToken() public view returns (address);
```

#### shortToken

The address of short token of the opened market.

```solidity
function shortToken() public view returns (address);
```

#### isLong

The direction of position.

```solidity
function isLong() public view returns (bool);
```

#### maxClaimableFundingShare

The max share of claimable funding before it get claimed through keeping.

```solidity
function maxClaimableFundingShare() public view returns (uint256);
```

#### pendingIncreaseOrderKey

The gmx increase order key that is in pending.

```solidity
function pendingIncreaseOrderKey() public view returns (bytes32);
```

#### pendingDecreaseOrderKey

The gmx decrease order key that is in pending.

```solidity
function pendingDecreaseOrderKey() public view returns (bytes32);
```

#### increaseCollateralMinMax

Returns the minimum and maximum collateral limits for increasing the position.

```solidity
function increaseCollateralMinMax() external pure returns (uint256 min, uint256 max);
```

**Returns**

| Name  | Type      | Description                                       |
| ----- | --------- | ------------------------------------------------- |
| `min` | `uint256` | The minimum allowable collateral increase amount. |
| `max` | `uint256` | The maximum allowable collateral increase amount. |

#### increaseSizeMinMax

Returns the minimum and maximum limits for increasing the position size.

```solidity
function increaseSizeMinMax() external pure returns (uint256 min, uint256 max);
```

**Returns**

| Name  | Type      | Description                                      |
| ----- | --------- | ------------------------------------------------ |
| `min` | `uint256` | The minimum allowable increase in position size. |
| `max` | `uint256` | The maximum allowable increase in position size. |

#### decreaseCollateralMinMax

Returns the minimum and maximum collateral limits for decreasing the position.

```solidity
function decreaseCollateralMinMax() external pure returns (uint256 min, uint256 max);
```

**Returns**

| Name  | Type      | Description                                       |
| ----- | --------- | ------------------------------------------------- |
| `min` | `uint256` | The minimum allowable collateral decrease amount. |
| `max` | `uint256` | The maximum allowable collateral decrease amount. |

#### decreaseSizeMinMax

Returns the minimum and maximum limits for decreasing the position size.

```solidity
function decreaseSizeMinMax() external pure returns (uint256 min, uint256 max);
```

**Returns**

| Name  | Type      | Description                                      |
| ----- | --------- | ------------------------------------------------ |
| `min` | `uint256` | The minimum allowable decrease in position size. |
| `max` | `uint256` | The maximum allowable decrease in position size. |

#### limitDecreaseCollateral

Retrieves the minimum decrease in collateral required for cost-efficient execution.

*Helps in optimizing gas usage and cost efficiency.*

```solidity
function limitDecreaseCollateral() external view returns (uint256);
```

**Returns**

| Name     | Type      | Description                                                                         |
| -------- | --------- | ----------------------------------------------------------------------------------- |
| `<none>` | `uint256` | The minimum decrease collateral amount that qualifies for cost-effective execution. |

#### cumulativePositionFeeUsd

The total cumulated position fee in usd.

```solidity
function cumulativePositionFeeUsd() external view returns (uint256);
```

#### cumulativeClaimedFundingUsd

The total claimed funding fee in usd.

```solidity
function cumulativeClaimedFundingUsd() external view returns (uint256);
```

### Events

#### FundingClaimed

*Emitted when the claimable funding fee gets claimed.*

```solidity
event FundingClaimed(address indexed token, uint256 indexed amount);
```

#### CollateralClaimed

*Emitted when the claimable collateral gets claimed.*

```solidity
event CollateralClaimed(address indexed token, uint256 indexed amount);
```

#### PositionAdjustmentRequested

*Emitted when a position adjustment is requested by strategy.*

```solidity
event PositionAdjustmentRequested(uint256 sizeDeltaInTokens, uint256 collateralDeltaAmount, bool isIncrease);
```

### Structs

#### InternalCreateOrderParams

*Used to create GMX order internally.*

```solidity
struct InternalCreateOrderParams {
    bool isLong;
    bool isIncrease;
    address exchangeRouter;
    address orderVault;
    address collateralToken;
    uint256 collateralDeltaAmount;
    uint256 sizeDeltaUsd;
    uint256 callbackGasLimit;
    bytes32 referralCode;
}
```

#### GmxV2PositionManagerStorage

```solidity
struct GmxV2PositionManagerStorage {
    address oracle;
    address gmxGasStation;
    address config;
    address strategy;
    address marketToken;
    address indexToken;
    address longToken;
    address shortToken;
    address collateralToken;
    bool isLong;
    Status status;
    bytes32 pendingIncreaseOrderKey;
    bytes32 pendingDecreaseOrderKey;
    uint256 pendingCollateralAmount;
    uint256 sizeInTokensBefore;
    uint256 decreasingCollateralDeltaAmount;
    uint256 pendingPositionFeeUsdForIncrease;
    uint256 pendingPositionFeeUsdForDecrease;
    uint256 cumulativePositionFeeUsd;
    uint256 positionFundingFeeAmountPerSize;
    uint256 cumulativeClaimedFundingUsd;
    uint256 cumulativeFundingFeeUsd;
    uint256 positionBorrowingFactor;
    uint256 cumulativeBorrowingFeeUsd;
}
```

### Enums

#### Status

*Describes the state of position manager.*

```solidity
enum Status {
    IDLE,
    INCREASE,
    DECREASE_ONE_STEP,
    DECREASE_TWO_STEP,
    SETTLE
}
```
