# Perp (/docs/risex/contracts/contract-interface/perp)

## PerpsManager

The `PerpsManager` contract is the main entry point for perpetual futures trading. It handles order placement, cancellation,
margin mode, leverage, and position management.

### Place Order

**Description**

Places a trading order (market or limit) in the specified market.

```solidity
function placeOrder(
    IOrdersManager.PlaceOrderParams calldata params
) external returns (WideOrderId orderId);
```

**Parameters**

* `params`: PlaceOrderParams struct:
  * `marketId` (uint16): The market ID
  * `sizeSteps` (uint32): Order size in steps (multiply by market's `stepSize` to get actual size)
  * `priceTicks` (uint24): Price in ticks (multiply by market's `stepPrice` to get actual price)
  * `ttlUnits` (uint16): TTL in 5-minute units (for GoodTillTime orders)
  * `side` (OrderSide): Buy or Sell
  * `stpMode` (STPMode): Self-trade prevention mode (ExpireMaker, ExpireTaker, ExpireBoth)
  * `orderType` (OrderType): Market or Limit
  * `postOnly` (bool): If true, order will only rest on the book (reverts if it would match)
  * `reduceOnly` (bool): If true, order can only reduce an existing position
  * `timeInForce` (TimeInForce): GoodTillCancelled, GoodTillTime, FillOrKill, or ImmediateOrCancel
  * `headerVersion` (uint8): Header version for encoding compatibility
  * `builderId` (uint16): Builder code ID (0 if none)

**Returns**

* `WideOrderId`: 56-bit order ID encoding rest/ephemeral flag, side, userId, and slot/nonce

**Example**

```solidity
IOrdersManager.PlaceOrderParams memory params = IOrdersManager.PlaceOrderParams({
    marketId: 1, // BTC
    sizeSteps: 100, // 100 steps
    priceTicks: 500000, // price in ticks
    ttlUnits: 0, // no TTL
    side: IOrdersManager.OrderSide.Buy,
    stpMode: IOrdersManager.STPMode.ExpireMaker,
    orderType: IOrdersManager.OrderType.Limit,
    postOnly: false,
    reduceOnly: false,
    timeInForce: IOrdersManager.TimeInForce.GoodTillCancelled,
    headerVersion: 0,
    builderId: 0
});

WideOrderId orderId = perpsManager.placeOrder(params);
```

***

### Cancel Order

**Description**

Cancels a single resting limit order in the specified market.

```solidity
function cancelOrder(
    IOrdersManager.CancelOrderParams calldata params
) external;
```

**Parameters**

* `params`: CancelOrderParams struct:
  * `marketId` (uint16): The market ID
  * `orderId` (RestingOrderId): The 40-bit resting order ID to cancel

**Example**

```solidity
// placeOrder returns a WideOrderId (56-bit). To cancel, extract the RestingOrderId (40-bit)
// using WideOrderId.toRestingOrderId() — only resting (limit) orders can be cancelled.
RestingOrderId restingId = wideOrderId.toRestingOrderId();

IOrdersManager.CancelOrderParams memory params = IOrdersManager.CancelOrderParams({
    marketId: 1,
    orderId: restingId
});

perpsManager.cancelOrder(params);
```

***

### Cancel Orders (Batch)

**Description**

Cancels multiple resting orders in a single market in one transaction.

```solidity
function cancelOrders(
    uint16 marketId,
    RestingOrderId[] calldata orderIds
) external;
```

**Parameters**

* `marketId`: The market ID
* `orderIds`: Array of resting order IDs to cancel

**Example**

```solidity
RestingOrderId[] memory orderIds = new RestingOrderId[](2);
orderIds[0] = orderId1;
orderIds[1] = orderId2;

perpsManager.cancelOrders(1, orderIds);
```

***

### Update Margin Mode

**Description**

Updates the margin mode (Cross or Isolated) for an account in a specific market. Cannot change margin mode while
the account has open positions or orders in that market.

```solidity
function updateMarginMode(
    IPerpsAccount.UpdateMarginModeParams calldata params
) external;
```

**Parameters**

* `params`: UpdateMarginModeParams struct:
  * `marketId` (uint16): The market ID
  * `marginMode` (MarginMode): Cross or Isolated

**Example**

```solidity
IPerpsAccount.UpdateMarginModeParams memory params = IPerpsAccount.UpdateMarginModeParams({
    marketId: 1,
    marginMode: IPerpsAccount.MarginMode.Isolated
});

perpsManager.updateMarginMode(params);
```

***

### Update Leverage

**Description**

Updates the leverage for an account in a specific market. Leverage determines the maximum position size relative to
margin.

```solidity
function updateLeverage(
    IPerpsAccount.UpdateLeverageParams calldata params
) external;
```

**Parameters**

* `params`: UpdateLeverageParams struct:
  * `marketId` (uint16): The market ID
  * `leverage` (uint8): The new leverage multiplier (e.g., 10 for 10x, max determined by market config)

**Example**

```solidity
IPerpsAccount.UpdateLeverageParams memory params = IPerpsAccount.UpdateLeverageParams({
    marketId: 1,
    leverage: 20 // 20x leverage
});

perpsManager.updateLeverage(params);
```

***

### Update Isolated Position Margin Balance

**Description**

Adds or removes margin from an isolated position. Positive amount adds margin (transfers from cross balance),
negative amount removes margin (transfers back to cross balance).

```solidity
function updateIsolatedPositionMarginBalance(
    IPerpsIsolatedMargin.UpdateIsolatedPositionMarginBalanceParams calldata params
) external;
```

**Parameters**

* `params`: UpdateIsolatedPositionMarginBalanceParams struct:
  * `marketId` (uint16): The market ID
  * `amount` (int256): The delta amount to add (positive) or remove (negative), in USDC with 18 decimals

**Example**

```solidity
// Add 100 USDC to isolated position
IPerpsIsolatedMargin.UpdateIsolatedPositionMarginBalanceParams memory params =
    IPerpsIsolatedMargin.UpdateIsolatedPositionMarginBalanceParams({
        marketId: 1,
        amount: 100e18
    });

perpsManager.updateIsolatedPositionMarginBalance(params);

// Remove 50 USDC from isolated position
params.amount = -50e18;
perpsManager.updateIsolatedPositionMarginBalance(params);
```

***

### Migrate Account

**Description**

Migrates all positions, collateral, and open orders from the caller's account to a new account address.
The source account must be healthy (not liquidatable) and the target must have no existing state.

```solidity
function migrateAccount(address newAccount) external;
```

**Parameters**

* `newAccount`: The target account address to migrate to

**Example**

```solidity
perpsManager.migrateAccount(newAccountAddress);
```

***

## CollateralManager

The `CollateralManager` contract handles collateral deposits and withdrawals for perpetual trading.
It includes rate limiting and emergency withdrawal guards for security.

### Deposit

**Description**

Deposits collateral tokens into the specified account. The caller must have approved the CollateralManager contract
to spend the tokens.

```solidity
function deposit(address receiver, Currency token, uint256 amount) external;
```

**Parameters**

* `receiver`: The account to credit with the deposited collateral
* `token`: The token address (wrapped as `Currency` type)
* `amount`: The amount of tokens to deposit (in token's native decimals)

**Example**

```solidity
// Approve tokens first
IERC20(usdc).approve(address(collateralManager), amount);

// Deposit USDC
collateralManager.deposit(account, Currency.wrap(usdc), amount);
```

***

### Withdraw

**Description**

Withdraws collateral tokens from the caller's account to the specified address. The withdrawable amount is limited
by the account's free margin balance. Withdrawals may be rate-limited or queued during emergency conditions.

```solidity
function withdraw(address to, Currency token, uint256 amount) external;
```

**Parameters**

* `to`: The address to withdraw tokens to
* `token`: The token address (wrapped as `Currency` type)
* `amount`: The amount of tokens to withdraw (in token's native decimals)

**Example**

```solidity
// Get the withdrawable amount
uint256 withdrawable = collateralManager.getWithdrawableUSDC(account);

// Withdraw USDC to the recipient
collateralManager.withdraw(recipient, Currency.wrap(usdc), withdrawable);
```

***

### Permit Transfer From

**Description**

Withdraws collateral on behalf of an owner using a Permit2-style signed permit. The signature includes `msg.sender`
as the authorized spender. Uses sequential nonces for replay protection.

```solidity
function permitTransferFrom(
    ISignatureTransfer.PermitTransferFrom calldata permit,
    ISignatureTransfer.SignatureTransferDetails calldata transferDetails,
    address owner,
    bytes calldata signature
) external;
```

**Parameters**

* `permit`: Permit data containing token, amount, nonce, and deadline
* `transferDetails`: The withdrawal destination and requested amount
* `owner`: The account authorizing the withdrawal
* `signature`: EIP-712 signature from the owner

***

## View Functions

### Get Token Balance

**Description**

Returns the projected collateral balance for a specific token for an account. For USDC, this includes projected
realized PnL from deferred settlements and subtracts projected cross funding fees. It does not include unrealized
PnL from open positions.

*Available on: CollateralManager*

```solidity
function getTokenBalance(address account, Currency token) external view returns (int256);
```

**Example**

```solidity
int256 balance = collateralManager.getTokenBalance(account, Currency.wrap(usdc));
```

***

### Get Total Token Balance In USDC

**Description**

Returns the projected total token balance denominated in USDC for an account, summing all token balances using
oracle prices.

*Available on: CollateralManager*

```solidity
function getTotalTokenBalanceInUSDC(address account) external view returns (int256);
```

***

### Get Position

**Description**

Returns the position for an account in a market.

*Available on: PerpsManager*

```solidity
function getPosition(uint16 marketId, address account) external view returns (Position memory);
```

**Returns**

* `Position` struct:
  * `size` (int128): Position size (positive for long, negative for short)
  * `quoteAmount` (int128): Quote amount
  * `lastFundingPayment` (int128): Last funding payment snapshot
  * `leverage` (uint8): Current leverage multiplier
  * `marginMode` (MarginMode): Cross or Isolated
  * `isolatedUsdcBalance` (uint112): Isolated margin balance (if in isolated mode)

**Example**

```solidity
IPerpsAccount.Position memory position = perpsManager.getPosition(1, account);
```

***

### Get Leverage

**Description**

Returns the leverage for an account in a market.

*Available on: PerpsManager*

```solidity
function getLeverage(uint16 marketId, address account) external view returns (uint128);
```

**Returns**

* `uint128`: The effective leverage multiplier (e.g., 10 for 10x). Note: stored as `uint8` internally in the Position struct, but returned as `uint128` by this view function. When setting leverage via `updateLeverage`, pass a `uint8` value.

**Example**

```solidity
uint128 leverage = perpsManager.getLeverage(1, account);
```

***

### Get Market Config

**Description**

Returns the configuration for a market.

*Available on: PerpsManager*

```solidity
function getMarketConfig(uint16 marketId) external view returns (PerpsMarketConfig memory);
```

**Returns**

* `PerpsMarketConfig` struct:
  * `name` (string): Market name
  * `quote` (address): Quote token address
  * `unlocked` (bool): Whether the market is active for trading
  * `maxLeverage` (uint8): Maximum allowed leverage
  * `maintenanceMarginFactor` (uint80): Maintenance margin factor
  * `minOrderStep` (uint32): Minimum order size in steps
  * `maxOrderStep` (uint32): Maximum order size in steps
  * `oiLimitSteps` (uint32): Open interest limit in steps
  * `stepSize` (uint64): Size per step (multiply sizeSteps by this)
  * `stepPrice` (uint64): Price per tick (multiply priceTicks by this)
  * `matchPriceBandBps` (uint24): Match price band in basis points (0 = disabled)

**Example**

```solidity
IPerpsMarketConfig.PerpsMarketConfig memory config = perpsManager.getMarketConfig(1);
```

***

### Get Open Orders

**Description**

Returns a paginated list of open resting order IDs for an account in a market, excluding fully-consumed
deferred orders.

*Available on: PerpsManager*

```solidity
function getOpenOrders(
    uint16 marketId,
    address account,
    uint256 startIndex,
    uint256 limit
) external view returns (RestingOrderId[] memory);
```

**Example**

```solidity
RestingOrderId[] memory orderIds = perpsManager.getOpenOrders(1, account, 0, 10);
```

***

### Get Total Open Orders

**Description**

Returns the total number of open orders for an account in a market.

*Available on: PerpsManager*

```solidity
function getTotalOpenOrders(uint16 marketId, address account) external view returns (uint256);
```

***

### Get Active Markets

**Description**

Returns the active markets bitmap for an account (markets where the account has positions or orders).

*Available on: PerpsManager*

```solidity
function getActiveMarkets(address account) external view returns (uint256[] memory);
```

***

### Get Withdrawable USDC

**Description**

Returns the maximum withdrawable USDC amount for an account, considering margin requirements.

*Available on: CollateralManager*

```solidity
function getWithdrawableUSDC(address account) external view returns (uint256);
```

**Example**

```solidity
uint256 withdrawable = collateralManager.getWithdrawableUSDC(account);
```

***

### Get Account Equity

**Description**

Returns the total account equity in USDC, including all positions and collateral.

*Available on: CollateralManager*

```solidity
function getAccountEquity(address account) external view returns (int256);
```

**Example**

```solidity
int256 equity = collateralManager.getAccountEquity(account);
```

***

### Get Cross Margin Balance

**Description**

Returns the projected cross margin balance for an account. Requires the pre-computed total token balance in USDC
(from `CollateralManager.getTotalTokenBalanceInUSDC`).

*Available on: PerpsManager*

```solidity
function getCrossMarginBalance(
    int256 totalTokenBalanceInUSDC,
    address account
) external view returns (int256);
```

**Example**

```solidity
int256 tokenBalance = collateralManager.getTotalTokenBalanceInUSDC(account);
int256 crossMargin = perpsManager.getCrossMarginBalance(tokenBalance, account);
```

***

### Get Free Cross Margin Balance

**Description**

Returns the projected free (available for withdrawal or new orders) cross margin balance for an account.

*Available on: PerpsManager*

```solidity
function getFreeCrossMarginBalance(
    int256 totalTokenBalanceInUSDC,
    address account
) external view returns (uint256);
```

**Example**

```solidity
int256 tokenBalance = collateralManager.getTotalTokenBalanceInUSDC(account);
uint256 freeMargin = perpsManager.getFreeCrossMarginBalance(tokenBalance, account);
```

***

### Get Supported Collateral Tokens

**Description**

Returns the full list of supported collateral token addresses.

*Available on: CollateralManager*

```solidity
function getSupportedCollateralTokens() external view returns (address[] memory);
```

***

### Get Total Markets

**Description**

Returns the total number of perpetual markets.

*Available on: PerpsManager*

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

***

### Get Open Interest

**Description**

Returns the current open interest for a market.

*Available on: PerpsManager*

```solidity
function getOpenInterest(uint16 marketId) external view returns (uint256);
```
