Perp
PerpsManager and CollateralManager contract interfaces for trading, position management, and account operations
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.
function placeOrder(
IOrdersManager.PlaceOrderParams calldata params
) external returns (WideOrderId orderId);Parameters
params: PlaceOrderParams struct:marketId(uint16): The market IDsizeSteps(uint32): Order size in steps (multiply by market'sstepSizeto get actual size)priceTicks(uint24): Price in ticks (multiply by market'sstepPriceto get actual price)ttlUnits(uint16): TTL in 5-minute units (for GoodTillTime orders)side(OrderSide): Buy or SellstpMode(STPMode): Self-trade prevention mode (ExpireMaker, ExpireTaker, ExpireBoth)orderType(OrderType): Market or LimitpostOnly(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 positiontimeInForce(TimeInForce): GoodTillCancelled, GoodTillTime, FillOrKill, or ImmediateOrCancelheaderVersion(uint8): Header version for encoding compatibilitybuilderId(uint16): Builder code ID (0 if none)
Returns
WideOrderId: 56-bit order ID encoding rest/ephemeral flag, side, userId, and slot/nonce
Example
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.
function cancelOrder(
IOrdersManager.CancelOrderParams calldata params
) external;Parameters
params: CancelOrderParams struct:marketId(uint16): The market IDorderId(RestingOrderId): The 40-bit resting order ID to cancel
Example
// 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.
function cancelOrders(
uint16 marketId,
RestingOrderId[] calldata orderIds
) external;Parameters
marketId: The market IDorderIds: Array of resting order IDs to cancel
Example
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.
function updateMarginMode(
IPerpsAccount.UpdateMarginModeParams calldata params
) external;Parameters
params: UpdateMarginModeParams struct:marketId(uint16): The market IDmarginMode(MarginMode): Cross or Isolated
Example
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.
function updateLeverage(
IPerpsAccount.UpdateLeverageParams calldata params
) external;Parameters
params: UpdateLeverageParams struct:marketId(uint16): The market IDleverage(uint8): The new leverage multiplier (e.g., 10 for 10x, max determined by market config)
Example
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).
function updateIsolatedPositionMarginBalance(
IPerpsIsolatedMargin.UpdateIsolatedPositionMarginBalanceParams calldata params
) external;Parameters
params: UpdateIsolatedPositionMarginBalanceParams struct:marketId(uint16): The market IDamount(int256): The delta amount to add (positive) or remove (negative), in USDC with 18 decimals
Example
// 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.
function migrateAccount(address newAccount) external;Parameters
newAccount: The target account address to migrate to
Example
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.
function deposit(address receiver, Currency token, uint256 amount) external;Parameters
receiver: The account to credit with the deposited collateraltoken: The token address (wrapped asCurrencytype)amount: The amount of tokens to deposit (in token's native decimals)
Example
// 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.
function withdraw(address to, Currency token, uint256 amount) external;Parameters
to: The address to withdraw tokens totoken: The token address (wrapped asCurrencytype)amount: The amount of tokens to withdraw (in token's native decimals)
Example
// 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.
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 deadlinetransferDetails: The withdrawal destination and requested amountowner: The account authorizing the withdrawalsignature: 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
function getTokenBalance(address account, Currency token) external view returns (int256);Example
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
function getTotalTokenBalanceInUSDC(address account) external view returns (int256);Get Position
Description
Returns the position for an account in a market.
Available on: PerpsManager
function getPosition(uint16 marketId, address account) external view returns (Position memory);Returns
Positionstruct:size(int128): Position size (positive for long, negative for short)quoteAmount(int128): Quote amountlastFundingPayment(int128): Last funding payment snapshotleverage(uint8): Current leverage multipliermarginMode(MarginMode): Cross or IsolatedisolatedUsdcBalance(uint112): Isolated margin balance (if in isolated mode)
Example
IPerpsAccount.Position memory position = perpsManager.getPosition(1, account);Get Leverage
Description
Returns the leverage for an account in a market.
Available on: PerpsManager
function getLeverage(uint16 marketId, address account) external view returns (uint128);Returns
uint128: The effective leverage multiplier (e.g., 10 for 10x). Note: stored asuint8internally in the Position struct, but returned asuint128by this view function. When setting leverage viaupdateLeverage, pass auint8value.
Example
uint128 leverage = perpsManager.getLeverage(1, account);Get Market Config
Description
Returns the configuration for a market.
Available on: PerpsManager
function getMarketConfig(uint16 marketId) external view returns (PerpsMarketConfig memory);Returns
PerpsMarketConfigstruct:name(string): Market namequote(address): Quote token addressunlocked(bool): Whether the market is active for tradingmaxLeverage(uint8): Maximum allowed leveragemaintenanceMarginFactor(uint80): Maintenance margin factorminOrderStep(uint32): Minimum order size in stepsmaxOrderStep(uint32): Maximum order size in stepsoiLimitSteps(uint32): Open interest limit in stepsstepSize(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
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
function getOpenOrders(
uint16 marketId,
address account,
uint256 startIndex,
uint256 limit
) external view returns (RestingOrderId[] memory);Example
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
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
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
function getWithdrawableUSDC(address account) external view returns (uint256);Example
uint256 withdrawable = collateralManager.getWithdrawableUSDC(account);Get Account Equity
Description
Returns the total account equity in USDC, including all positions and collateral.
Available on: CollateralManager
function getAccountEquity(address account) external view returns (int256);Example
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
function getCrossMarginBalance(
int256 totalTokenBalanceInUSDC,
address account
) external view returns (int256);Example
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
function getFreeCrossMarginBalance(
int256 totalTokenBalanceInUSDC,
address account
) external view returns (uint256);Example
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
function getSupportedCollateralTokens() external view returns (address[] memory);Get Total Markets
Description
Returns the total number of perpetual markets.
Available on: PerpsManager
function getTotalMarkets() external view returns (uint256);Get Open Interest
Description
Returns the current open interest for a market.
Available on: PerpsManager
function getOpenInterest(uint16 marketId) external view returns (uint256);