Perp v2
Perp v2
  • About Perpetual Protocol
    • Social Links
    • Governance
    • v2 Era Ecosystem
    • PERP Token
  • Terms of Service
  • General
    • Wallets
    • Transfering Assets
    • Deposit & Withdrawal
    • Perpetual + Uniswap
    • FAQs
    • Guides
    • Legacy Reward Programs
    • Security
  • Hot Tub
  • Trading on Perp v2
    • How It Works
    • UI Overview
    • Perpetual Futures Basics
    • Trading Quick-start
    • Opening and Closing Positions
    • Account Value & More
    • Funding Payments
    • Order Types
    • Trading Fees and Gas Fees
    • Managing Risk
    • Multi-collateral
    • More docs
  • Providing Liquidity
    • Basics
    • Introduction to Maker UI
    • Add / Remove Liquidity
    • Estimated Fees and Rewards APR
    • More on LPing
    • Tools for LPs
  • Perp v2 Specs
  • Developer Docs
    • Developer FAQs
    • Source Code
    • Protocol Attributes
    • Contract guide
      • AccountBalance
      • BaseToken
      • ClearingHouse
      • CollateralManager
      • DelegateApproval
      • Exchange
      • InsuranceFund
      • MarketRegistry
      • OrderBook
      • QuoteToken
      • Vault
      • VirtualToken
    • Interface Contracts
      • IAccountBalance
      • IBaseToken
      • IClearingHouse
      • IClearingHouseConfig
      • IClearingHouseConfigEvent
      • ICollateralManager
      • IDelegateApproval
      • IERC20Metadata
      • IExchange
      • IIndexPrice
      • IInsuranceFund
      • IMarketRegistry
      • IOrderBook
      • IVault
      • IVirtualToken
    • Integration guide
    • Dev tools
Powered by GitBook
On this page
  • Functions​
  • ClearingHouseConfig
  • Functions​

Was this helpful?

  1. Developer Docs
  2. Contract guide

ClearingHouse

Last updated 1 year ago

Was this helpful?

InternalOpenPositionParams

  struct InternalOpenPositionParams(
    address trader
    address baseToken
    bool isBaseToQuote
    bool isExactInput
    bool isClose
    uint256 amount
    uint160 sqrtPriceLimitX96
  )

InternalCheckSlippageParams

  struct InternalCheckSlippageParams(
    bool isBaseToQuote
    bool isExactInput
    uint256 base
    uint256 quote
    uint256 oppositeAmountBound
  )

Functions

  function initialize(
  ) public

this function is public for testing

  function setDelegateApproval(
  ) external

remove to reduce bytecode size, might add back when we need it

  function addLiquidity(
    struct IClearingHouse.AddLiquidityParams params
  ) external returns (struct IClearingHouse.AddLiquidityResponse)

Maker can call addLiquidity to provide liquidity on Uniswap V3 pool

Tx will fail if adding base == 0 && quote == 0 / liquidity == 0

  • AddLiquidityParams.useTakerBalance is only accept false now

Name
Type
Description

params

struct IClearingHouse.AddLiquidityParams

AddLiquidityParams struct

Name
Type
Description

response

struct IClearingHouse.AddLiquidityResponse

AddLiquidityResponse struct

  function removeLiquidity(
    struct IClearingHouse.RemoveLiquidityParams params
  ) external returns (struct IClearingHouse.RemoveLiquidityResponse)

Maker can call removeLiquidity to remove liquidity

remove liquidity will transfer maker impermanent position to taker position, if liquidity of RemoveLiquidityParams struct is zero, the action will collect fee from pool to maker

Name
Type
Description

params

struct IClearingHouse.RemoveLiquidityParams

RemoveLiquidityParams struct

Name
Type
Description

response

struct IClearingHouse.RemoveLiquidityResponse

RemoveLiquidityResponse struct

  function settleAllFunding(
    address trader
  ) external

Settle all markets fundingPayment to owedRealized Pnl

Name
Type
Description

trader

address

The address of trader

  function openPosition(
    struct IClearingHouse.OpenPositionParams params
  ) external returns (uint256 base, uint256 quote)

Trader can call openPosition to long/short on baseToken market

  • OpenPositionParams.oppositeAmountBound

    • B2Q + exact input, want more output quote as possible, so we set a lower bound of output quote

    • B2Q + exact output, want less input base as possible, so we set a upper bound of input base

    • Q2B + exact input, want more output base as possible, so we set a lower bound of output base

    • Q2B + exact output, want less input quote as possible, so we set a upper bound of input quote

      when it's set to 0, it will disable slippage protection entirely regardless of exact input or output when it's over or under the bound, it will be reverted

  • OpenPositionParams.sqrtPriceLimitX96

    • B2Q: the price cannot be less than this value after the swap

    • Q2B: the price cannot be greater than this value after the swap

      it will fill the trade until it reaches the price limit but WON'T REVERT when it's set to 0, it will disable price limit; when it's 0 and exact output, the output amount is required to be identical to the param amount

Name
Type
Description

params

struct IClearingHouse.OpenPositionParams

OpenPositionParams struct

Name
Type
Description

base

uint256

The amount of baseToken the taker got or spent

quote

uint256

The amount of quoteToken the taker got or spent

  function openPositionFor(
    address trader,
    struct IClearingHouse.OpenPositionParams params
  ) external returns (uint256 base, uint256 quote, uint256 fee)
Name
Type
Description

trader

address

The address of trader

params

struct IClearingHouse.OpenPositionParams

OpenPositionParams struct is the same as openPosition()

Name
Type
Description

base

uint256

The amount of baseToken the taker got or spent

quote

uint256

The amount of quoteToken the taker got or spent

fee

uint256

The trading fee

  function closePosition(
    struct IClearingHouse.ClosePositionParams params
  ) external returns (uint256 base, uint256 quote)

Close trader's position

Name
Type
Description

params

struct IClearingHouse.ClosePositionParams

ClosePositionParams struct

Name
Type
Description

base

uint256

The amount of baseToken the taker got or spent

quote

uint256

The amount of quoteToken the taker got or spent

  function liquidate(
    address trader,
    address baseToken,
    int256 positionSize
  ) external

If trader is underwater, any one can call liquidate to liquidate this trader

If trader has open orders, need to call cancelAllExcessOrders first If positionSize is greater than maxLiquidatePositionSize, liquidate maxLiquidatePositionSize by default If margin ratio >= 0.5 mmRatio, maxLiquidateRatio = MIN((1, 0.5 totalAbsPositionValue / absPositionValue) If margin ratio < 0.5 mmRatio, maxLiquidateRatio = 1 maxLiquidatePositionSize = positionSize maxLiquidateRatio

Name
Type
Description

trader

address

The address of trader

baseToken

address

The address of baseToken

positionSize

int256

the position size to be liquidated by liquidator

  function liquidate(
    address trader,
    address baseToken,
     positionSize
  ) external

If trader is underwater, any one can call liquidate to liquidate this trader

If trader has open orders, need to call cancelAllExcessOrders first If positionSize is greater than maxLiquidatePositionSize, liquidate maxLiquidatePositionSize by default If margin ratio >= 0.5 mmRatio, maxLiquidateRatio = MIN((1, 0.5 totalAbsPositionValue / absPositionValue) If margin ratio < 0.5 mmRatio, maxLiquidateRatio = 1 maxLiquidatePositionSize = positionSize maxLiquidateRatio

Name
Type
Description

trader

address

The address of trader

baseToken

address

The address of baseToken

positionSize

the position size to be liquidated by liquidator

  function cancelExcessOrders(
    address maker,
    address baseToken,
    bytes32[] orderIds
  ) external

Cancel excess order of a maker

Order id can get from OrderBook.getOpenOrderIds

Name
Type
Description

maker

address

The address of Maker

baseToken

address

The address of baseToken

orderIds

bytes32[]

The id of the order

  function cancelAllExcessOrders(
    address maker,
    address baseToken
  ) external

Cancel all excess orders of a maker if the maker is underwater

This function won't fail if the maker has no order but fails when maker is not underwater

Name
Type
Description

maker

address

The address of maker

baseToken

address

The address of baseToken

  function quitMarket(
    address trader,
    address baseToken
  ) external returns (uint256 base, uint256 quote)

Close all positions and remove all liquidities of a trader in the closed market

Name
Type
Description

trader

address

The address of trader

baseToken

address

The address of baseToken

Name
Type
Description

base

uint256

The amount of base token that is closed

quote

uint256

The amount of quote token that is closed

  function uniswapV3MintCallback(
    uint256 amount0Owed,
    uint256 amount1Owed,
    bytes data
  ) external

Called to msg.sender after minting liquidity to a position from IUniswapV3Pool#mint.

namings here follow Uniswap's convention

Name
Type
Description

amount0Owed

uint256

The amount of token0 due to the pool for the minted liquidity

amount1Owed

uint256

The amount of token1 due to the pool for the minted liquidity

data

bytes

Any data passed through by the caller via the IUniswapV3PoolActions#mint call

  function uniswapV3SwapCallback(
    int256 amount0Delta,
    int256 amount1Delta,
    bytes data
  ) external

Called to msg.sender after executing a swap via IUniswapV3Pool#swap.

namings here follow Uniswap's convention

Name
Type
Description

amount0Delta

int256

The amount of token0 that was sent (negative) or must be received (positive) by the pool by

the end of the swap. If positive, the callback must send that amount of token0 to the pool. |amount1Delta | int256 | The amount of token1 that was sent (negative) or must be received (positive) by the pool by the end of the swap. If positive, the callback must send that amount of token1 to the pool. |data | bytes | Any data passed through by the caller via the IUniswapV3PoolActions#swap call

  function getQuoteToken(
  ) external returns (address)

Get QuoteToken address

Name
Type
Description

quoteToken

address

The quote token address

  function getUniswapV3Factory(
  ) external returns (address)

Get UniswapV3Factory address

Name
Type
Description

factory

address

UniswapV3Factory address

  function getClearingHouseConfig(
  ) external returns (address)

Get ClearingHouseConfig address

Name
Type
Description

clearingHouseConfig

address

ClearingHouseConfig address

  function getVault(
  ) external returns (address)

Get Vault address

Name
Type
Description

vault

address

Vault address

  function getExchange(
  ) external returns (address)

Get Exchange address

Name
Type
Description

exchange

address

Exchange address

  function getOrderBook(
  ) external returns (address)

Get OrderBook address

Name
Type
Description

orderBook

address

OrderBook address

  function getAccountBalance(
  ) external returns (address)

Get AccountBalance address

Name
Type
Description

accountBalance

address

AccountBalance address

  function getInsuranceFund(
  ) external returns (address)

Get InsuranceFund address

Name
Type
Description

insuranceFund

address

InsuranceFund address

  function getDelegateApproval(
  ) external returns (address)

Get DelegateApproval address

Name
Type
Description

delegateApproval

address

DelegateApproval address

  function getAccountValue(
    address trader
  ) public returns (int256)

Get account value of trader

accountValue = totalCollateralValue + totalUnrealizedPnl, in 18 decimals

Name
Type
Description

trader

address

The address of trader

Name
Type
Description

accountValue

int256

The account value of trader

ClearingHouseConfig

  function initialize(
  ) external
  function setLiquidationPenaltyRatio(
  ) external
  function setPartialCloseRatio(
  ) external
  function setTwapInterval(
  ) external
  function setMaxMarketsPerAccount(
  ) external
  function setSettlementTokenBalanceCap(
  ) external
  function setMaxFundingRate(
  ) external
  function setMarkPriceMarketTwapInterval(
  ) external
  function setMarkPricePremiumInterval(
  ) external
  function getMaxMarketsPerAccount(
  ) external returns (uint8)
Name
Type
Description

maxMarketsPerAccount

uint8

Max value of total markets per account

  function getImRatio(
  ) external returns (uint24)
Name
Type
Description

imRatio

uint24

Initial margin ratio

  function getMmRatio(
  ) external returns (uint24)
Name
Type
Description

mmRatio

uint24

Maintenance margin requirement ratio

  function getLiquidationPenaltyRatio(
  ) external returns (uint24)
Name
Type
Description

liquidationPenaltyRatio

uint24

Liquidation penalty ratio

  function getPartialCloseRatio(
  ) external returns (uint24)
Name
Type
Description

partialCloseRatio

uint24

Partial close ratio

  function getTwapInterval(
  ) external returns (uint32)
Name
Type
Description

twapInterval

uint32

TwapInterval for funding and prices (market & index) calculations

  function getSettlementTokenBalanceCap(
  ) external returns (uint256)
Name
Type
Description

settlementTokenBalanceCap

uint256

Max value of settlement token balance

  function getMaxFundingRate(
  ) external returns (uint24)
Name
Type
Description

maxFundingRate

uint24

Max value of funding rate

  function getMarkPriceConfig(
  ) external returns (uint32, uint32)
Name
Type
Description

marketTwapInterval

uint32

MarketTwapInterval is the interval of market twap used for mark price calculations

premiumInterval

uint32

PremiumInterval is the interval of premium used for mark price calculations

initialize

setDelegateApproval

addLiquidity

Parameters:

Return Values:

removeLiquidity

Parameters:

Return Values:

settleAllFunding

Parameters:

openPosition

Parameters:

Return Values:

openPositionFor

Parameters:

Return Values:

closePosition

Parameters:

Return Values:

liquidate

Parameters:

liquidate

Parameters:

cancelExcessOrders

Parameters:

cancelAllExcessOrders

Parameters:

quitMarket

Parameters:

Return Values:

uniswapV3MintCallback

Parameters:

uniswapV3SwapCallback

Parameters:

getQuoteToken

Return Values:

getUniswapV3Factory

Return Values:

getClearingHouseConfig

Return Values:

getVault

Return Values:

getExchange

Return Values:

getOrderBook

Return Values:

getAccountBalance

Return Values:

getInsuranceFund

Return Values:

getDelegateApproval

Return Values:

getAccountValue

Parameters:

Return Values:

Functions

initialize

setLiquidationPenaltyRatio

setPartialCloseRatio

setTwapInterval

setMaxMarketsPerAccount

setSettlementTokenBalanceCap

setMaxFundingRate

setMarkPriceMarketTwapInterval

setMarkPricePremiumInterval

getMaxMarketsPerAccount

Return Values:

getImRatio

Return Values:

getMmRatio

Return Values:

getLiquidationPenaltyRatio

Return Values:

getPartialCloseRatio

Return Values:

getTwapInterval

Return Values:

getSettlementTokenBalanceCap

Return Values:

getMaxFundingRate

Return Values:

getMarkPriceConfig

Return Values:

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​