Solidity API

IAuctioneer

This interface defines the functions and events related to the auction and liquidation process in the clearing system. It is implemented by the Auctioneer facet of the ClearingDiamond contract, and hence all functionality is callable through the ClearingDiamond contract.

Deployed Addresses

Chain ID Address
65000000 0x5B5411F1548254d25360d71FE40cFc1cC983B2A2
65010004 0xB894bFf368Bf1EA89c18612670B7E072866a5264
65100004 0x393746A87CF3458EeA2b47BF035496429AbFBD66

Functions

AuctionConfig

Protocol set configuration options for liquidation auctions

struct AuctionConfig {
  uint64 restorationBuffer;
  uint256 liquidationDuration;
}

BidData

struct BidData {
  bytes32 productID;
  uint256 price;
  uint256 quantity;
  enum Side side;
}

AuctionData

struct AuctionData {
  uint256 startBlock;
  uint256 maeAtInitiation;
  uint256 mmuAtInitiation;
  int256 maeNow;
  uint256 mmuNow;
}

LiquidationStarted

Emitted when a liquidation auction is requested for a liquidatable margin account

event LiquidationStarted(address marginAccountID, address collateralToken)

Parameters

Name Type Description
marginAccountID address The address of the account being liquidated
collateralToken address The address of the collateral token used in the liquidation

Auctioned

Emitted when a liquidation auction is successfully bid on

event Auctioned(address liquidatingMarginAccountID, address liquidatorMarginAccountID, bytes32 productId, int256 quantity, uint256 price)

Parameters

Name Type Description
liquidatingMarginAccountID address The address of the account being liquidated
liquidatorMarginAccountID address The address of the liquidator placing the bid
productId bytes32 The product ID of the position being liquidated
quantity int256 The quantity of the position being bid on
price uint256 The price at which the bid was placed

LiquidationTerminated

Emitted when a liquidation auction is terminated

event LiquidationTerminated(address marginAccountID, address collateralToken)

This event is emitted when the liquidation auction is successfully terminated, either by the liquidator or by the margin account itself once above the restoration buffer.

Parameters

Name Type Description
marginAccountID address The address of the account being liquidated
collateralToken address The address of the collateral token used in the liquidation

requestLiquidation

Request a liquidation auction for a margin account that has a MMA = 0. The requestor will be rewarded with the associated auction bounty for initiating the liquidation

function requestLiquidation(address marginAccountID, address collateralToken) external

Parameters

Name Type Description
marginAccountID address The address of the account to be liquidated
collateralToken address The address of the collateral token used in the liquidation

bidAuction

Bid on an ongoing liquidation auction for a liquidatable margin account

function bidAuction(address marginAccountID, address collateralToken, struct IAuctioneer.BidData[] bids) external

Parameters

Name Type Description
marginAccountID address The address of the account being liquidated
collateralToken address The address of the collateral token used in the liquidation
bids struct IAuctioneer.BidData[] List of bids (see BidData)

terminateAuctions

Terminate an ongoing liquidation auction for a liquidatable margin account. The call is reverted if the liquidation cannot be terminated successfully.

function terminateAuctions(address marginAccountID, address collateral) external

This function can be called by the liquidator or by the margin account itself once above the restoration buffer.

Parameters

Name Type Description
marginAccountID address The address of the account being liquidated
collateral address The address of the collateral token used in the liquidation

isLiquidatable

function isLiquidatable(address marginAccountID, address collateralToken) external view returns (bool)

isLiquidating

function isLiquidating(address marginAccountID, address collateralToken) external view returns (bool)

canTerminateAuctions

Check if a liquidation auction can be terminated for a given account and collateral token

function canTerminateAuctions(address marginAccountID, address collateral) external view returns (bool)

Parameters

Name Type Description
marginAccountID address The address of the account being liquidated
collateral address The address of the collateral token used in the liquidation

Return Values

Name Type Description
[0] bool A boolean indicating whether the liquidation auction can be terminated

auctionConfig

function auctionConfig() external view returns (struct IAuctioneer.AuctionConfig)

auctionData

function auctionData(address marginAccountID, address collateral) external view returns (struct IAuctioneer.AuctionData)

maeCheckOnBid

Performs necessary checks on mae for the liquidator and the liquidating account

function maeCheckOnBid(address liquidatorMarginAccountID, address liquidatingMarginAccountID, address collateral, struct IAuctioneer.BidData[] bids) external view returns (bool maeCheckFailed, bool maeOverMmuRateExceeded)

Parameters

Name Type Description
liquidatorMarginAccountID address Margin Account ID of the liquidator
liquidatingMarginAccountID address Margin Account ID of the liquidating account
collateral address Address of the collateral token
bids struct IAuctioneer.BidData[] List of bids

Return Values

Name Type Description
maeCheckFailed bool True if mae check is failed on the liquidator account, false otherwise
maeOverMmuRateExceeded bool True if the rate of mae over mmu is not exceeded over the maximum allowed rate, false otherwise

validateAuctions

function validateAuctions(address marginAccountID, address collateralToken, struct IAuctioneer.BidData[] bids) external view returns (bool)

maxMaeOffered

function maxMaeOffered(address marginAccountID, address collateral, uint256 mmuDecreased) external view returns (uint256)

IBankruptcy

Deployed Addresses

Chain ID Address
65000000 0x5B5411F1548254d25360d71FE40cFc1cC983B2A2
65010004 0xB894bFf368Bf1EA89c18612670B7E072866a5264
65100004 0x393746A87CF3458EeA2b47BF035496429AbFBD66

Functions

LossMutualized

Emitted when a bankrupt account’s loss is mutualized

event LossMutualized(address bankruptAccount, address collateralToken, address caller, int256 lossAmount)

Parameters

Name Type Description
bankruptAccount address The address of the bankrupt account
collateralToken address The address of the collateral token for which the account is bankrupt
caller address The address of the caller who triggered the loss mutualization
lossAmount int256 The amount of loss that was mutualized

PositionLossData

struct PositionLossData {
  bytes32 positionId;
  int256 bankruptAccountUPnL;
  int256 bankruptAccountQuantity;
  uint256 markPrice;
  uint256 pointValue;
  uint256 tickSize;
  struct IBankruptcy.LAAData[] laaData;
}

LAAData

struct LAAData {
  address owner;
  int256 quantity;
  uint256 lastTradedTimestamp;
  uint256 positionAge;
}

mutualizeLosses

triggers the loss mutualization process for a bankrupt account

function mutualizeLosses(address bankruptAccountId, address collateralToken, bytes32[] productIds, address[][] laas) external

Parameters

Name Type Description
bankruptAccountId address The address of the bankrupt account (must have mae < 0)
collateralToken address The address of the collateral token for which the account is bankrupt
productIds bytes32[] The list of product IDs for all products in the bankrupt account
laas address[][] The list of LAAs for each product in the bankrupt account (in the same order as productIds)

validateLAAs

calculates the loss mutualization data for a bankrupt account

function validateLAAs(contract IMarginAccount marginAccount, address bankruptAccount, bytes32 productId, address[] productOwners) external view returns (struct IBankruptcy.PositionLossData)

This function will revert if the productOwners does not contain all traders for the product in the last 30 seconds

Parameters

Name Type Description
marginAccount contract IMarginAccount The margin account contract in which the account is bankrupt
bankruptAccount address The address of the bankrupt account
productId bytes32 The product ID for which to calculate the loss mutualization data
productOwners address[] The list of product owners for the product for which to calculate the loss mutualization data

Return Values

Name Type Description
[0] struct IBankruptcy.PositionLossData PositionLossData containing the loss mutualization data for the bankrupt account

uniqueTraderCount

calculates the number of unique traders for a product in the last 30 seconds

function uniqueTraderCount(bytes32 productId) external view returns (uint256)

This amount of laas is the minimum necessary to call mutualizeLosses

Parameters

Name Type Description
productId bytes32 The product ID for which to calculate the unique trader count

Return Values

Name Type Description
[0] uint256 The number of unique traders for the product in the last 30 seconds

lastTradedTimestamp

returns the last timestamp at which a trader traded a product

function lastTradedTimestamp(bytes32 productId, address trader) external view returns (uint256)

Parameters

Name Type Description
productId bytes32 The product ID for which to get the last traded timestamp
trader address The address of the trader for which to get the last traded timestamp

Return Values

Name Type Description
[0] uint256 The last timestamp at which the trader traded the product

Side

enum Side {
  BID,
  ASK
}

IClearing

This interface defines the functions and data structures related to the clearing process in the trading system. The primary point of interaction with these clearing functions should be from Trading Protocols

Deployed Addresses

Chain ID Address
65000000 0x5B5411F1548254d25360d71FE40cFc1cC983B2A2
65010004 0xB894bFf368Bf1EA89c18612670B7E072866a5264
65100004 0x393746A87CF3458EeA2b47BF035496429AbFBD66

Functions

IntentData

Represents the data required for an intent

  • nonce - the unique nonce of the intent, used to prevent replay attacks
  • tradingProtocolID - the trading protocol ID that is executing the intent (must match the msg.sender)
  • productID - the product ID of the product being traded
  • limitPrice - the limit price for the trade
  • quantity - the maximum quantity to be traded
  • maxTradingFeeRate - the maximum trading fee rate that the account is willing to pay to the trading protocol
  • goodUntil - the time after which this intent expires
  • side* - the side of the trade (BID or ASK)
struct IntentData {
  uint256 nonce;
  address tradingProtocolID;
  bytes32 productID;
  uint256 limitPrice;
  uint256 quantity;
  uint256 maxTradingFeeRate;
  uint256 goodUntil;
  enum Side side;
}

Intent

Represents an intent to trade, which is signed by the margin account owner - marginAccountID - the margin account ID which has a funded margin account on the associated collateral asset - intentAccountID - the intent account ID which has signed the intent (must be approved by the margin account) - hash - the hash of the intent data - data - the intent data containing the details of the intended trade - signature - the signature of the intent, signed by the intent account ID

struct Intent {
  address marginAccountID;
  address intentAccountID;
  bytes32 hash;
  struct IClearing.IntentData data;
  bytes signature;
}

Trade

Represents a trade to be executed in the clearing system - productID - the product ID of the product being traded - protocolID - the trading protocol ID that is executing the trade (must match the msg.sender) - tradeID - an ID identifying the trade - price - the trade price - timestamp - the timestamp of the trade - accounts - the margin account IDs of the accounts involved in the trade - quantities - the quantities traded for each associated margin account - feeRates - the fee rates charged for each associated margin account - intents - the intent associated with the trade (must be signed by the appropriate margin accounts and in the same order as accounts)

struct Trade {
  bytes32 productID;
  address protocolID;
  uint256 tradeID;
  uint256 price;
  uint256 timestamp;
  address[] accounts;
  uint256[] quantities;
  int256[] feeRates;
  struct IClearing.Intent[] intents;
}

ClearingConfig

The configuration options for the clearing contract - clearingFeeRate - the clearing fee rate charged by the clearing contract, with precision 10^6

struct ClearingConfig {
  uint32 clearingFeeRate;
}

Config

The protocol-level configuration options for the clearing contract - auctionConfig - the auctioneer config - clearingConfig - the clearing contract config

struct Config {
  struct IAuctioneer.AuctionConfig auctionConfig;
  struct IClearing.ClearingConfig clearingConfig;
}

TradeExecuted

Emitted when a trade is executed

event TradeExecuted(bytes32 productID, address protocolID, address marginAccount, uint256 price, uint256 quantity)

Parameters

Name Type Description
productID bytes32 the product ID of the executed trade
protocolID address the trading protocol ID that executed the trade
marginAccount address the margin account contract address used for the product
price uint256 the price at which the trade was executed
quantity uint256 the quantity of the trade executed (sum of all quantities on each side of the trade)

execute

performs trade validation checks and executes a trade

function execute(struct IClearing.Trade trade, bool fallbackOnFailure) external

this function can only be called by the trading protocol listed in the trade object

Parameters

Name Type Description
trade struct IClearing.Trade the trade to be executed
fallbackOnFailure bool if true, the trading protocol’s margin account will be substituted for any margin account in the trade that fails the MAE check

setConfig

sets the clearing config

function setConfig(struct IClearing.Config config) external

this function can only be called by the contract owner

Parameters

Name Type Description
config struct IClearing.Config the clearing config to be set

finalizeInitialization

finalizes initialization of the clearing contract

function finalizeInitialization(address marginAccountRegistry) external

Parameters

Name Type Description
marginAccountRegistry address the address of the margin account registry

setTreasury

sets the treasury address

function setTreasury(address treasury) external

this function can only be called by the contract owner

Parameters

Name Type Description
treasury address the address of the treasury

estimateFees

returns the estimated fees for a given trade

function estimateFees(bytes32 productID, uint256 price, uint256 quantity, int256 tradingFeeRate) external view returns (uint256, int256)

Parameters

Name Type Description
productID bytes32 the product ID
price uint256 the price of the trade
quantity uint256 the quantity of the trade
tradingFeeRate int256 the trading fee rate charged by the trading protocol

Return Values

Name Type Description
[0] uint256 fees the clearing fee charged by the clearing protocol and trading fee charged by the trading protocol
[1] int256

clearingFeeRate

returns the clearing fee rate with precision 10^6

function clearingFeeRate() external view returns (uint256)

Return Values

Name Type Description
[0] uint256 the clearing fee rate

MAX_TRADING_FEE_RATE

returns the maximum trading fee rate with precision 10^6

function MAX_TRADING_FEE_RATE() external pure returns (uint256)

Return Values

Name Type Description
[0] uint256 the maximum trading fee rate

getProductRegistry

returns the product registry address

function getProductRegistry() external view returns (contract IProductRegistry)

Return Values

Name Type Description
[0] contract IProductRegistry the product registry address

getMarginAccountRegistry

returns the margin account registry address

function getMarginAccountRegistry() external view returns (contract IMarginAccountRegistry)

Return Values

Name Type Description
[0] contract IMarginAccountRegistry the margin account registry address

getTreasury

returns the treasury address

function getTreasury() external view returns (address)

Return Values

Name Type Description
[0] address the treasury address

config

returns the clearing config

function config() external view returns (struct IClearing.Config)

Return Values

Name Type Description
[0] struct IClearing.Config the clearing config

IClearingDiamond

This interface represents the complete functionality of the ClearingDiamond contract. It includes inheritance from multiple facets that handle different aspects of the clearing process.

Deployed Addresses

Chain ID Address
65000000 0x5B5411F1548254d25360d71FE40cFc1cC983B2A2
65010004 0xB894bFf368Bf1EA89c18612670B7E072866a5264
65100004 0x393746A87CF3458EeA2b47BF035496429AbFBD66

Functions

Inherited (IAdminControlled)

IFinalSettlement

Deployed Addresses

Chain ID Address
65000000 0x5B5411F1548254d25360d71FE40cFc1cC983B2A2
65010004 0xB894bFf368Bf1EA89c18612670B7E072866a5264
65100004 0x393746A87CF3458EeA2b47BF035496429AbFBD66

Functions

FSPFinalized

event FSPFinalized(bytes32 productID, uint256 fsp)

FinalSettlementCloseout

event FinalSettlementCloseout(bytes32 productID, uint256 accountLength, address closedBy)

initiateFinalSettlement

initiates a final settlement process on a product

function initiateFinalSettlement(bytes32 productID, address[] accounts) external

Parameters

Name Type Description
productID bytes32 the product to be settled
accounts address[] the accounts to be settled, the positions must be offsetting

finalizeFsp

finalizes the final settlement price on a product if it earliest FSP time has passed

function finalizeFsp(bytes32 productID) external returns (uint256)

Parameters

Name Type Description
productID bytes32 the product to be finalized

Return Values

Name Type Description
[0] uint256 the final settlement price (FSP) of the product

CLOSEOUT_FEE_RATE

returns the constant protocol fee rate that closed positions will be charged

function CLOSEOUT_FEE_RATE() external pure returns (uint256)

Return Values

Name Type Description
[0] uint256 the protocol closeout fee rate with 10^6 precision

CLOSEOUT_REWARD_RATE

returns the constant protocol reward rate that closers will be credited

function CLOSEOUT_REWARD_RATE() external pure returns (uint256)

Return Values

Name Type Description
[0] uint256 the protocol closeout reward rate with 10^6 precision

getFsp

returns the final settlement price (FSP) for a given product ID

function getFsp(bytes32 productId) external view returns (uint256 fsp, bool finalized)

Parameters

Name Type Description
productId bytes32 the product ID to get the FSP for

Return Values

Name Type Description
fsp uint256 the final settlement price
finalized bool whether the FSP has been finalized

IMarginAccount

Functions

PositionData

the data associated with a specific position in the margin account - positionId - the product ID of the product for which the position is held - quantity - the total quantity of the position held - costBasis - the cost basis of the position, representing the average weighted price at which the position was acquired - maintenanceMargin - the amount of margin reserved by this position - pnl - the unrealized profit and loss of the position, calculated using the difference between the current market price and the cost basis

struct PositionData {
  bytes32 positionId;
  int256 quantity;
  int256 costBasis;
  uint256 maintenanceMargin;
  int256 pnl;
}

Settlement

Data associated with a single trade to settle - positionId - the ID of the product in which the trade will settle - quantity - quantity to be traded - price - price at which the trade will settle

struct Settlement {
  bytes32 positionId;
  int256 quantity;
  uint256 price;
}

PositionUpdated

emitted when a position is created/updated

event PositionUpdated(address marginAccountID, bytes32 positionId, int256 totalQuantity, int256 costBasis, uint256 price, int256 quantity)

Parameters

Name Type Description
marginAccountID address The address of the margin account
positionId bytes32 The position id
totalQuantity int256 The total quantity of the position after the update
costBasis int256 The cost basis of the position after the update
price uint256 The price at which the position was updated
quantity int256 The quantity added to the position (negative if position was reduced)

FeeCollected

emitted when a fee is collected from a margin account

event FeeCollected(address marginAccountID, int256 capitalAmount)

Parameters

Name Type Description
marginAccountID address The address of the margin account
capitalAmount int256 The amount of capital collected

FeeDispersed

emitted when fees are dispersed to recipients

event FeeDispersed(address recipient, uint256 capitalAmount)

Parameters

Name Type Description
recipient address The addresses of the recipients
capitalAmount uint256 The amounts of capital dispersed to each recipient

Deposit

emitted when collateral is deposited into the margin account

event Deposit(address user, uint256 amount)

Parameters

Name Type Description
user address The address of the user depositing collateral
amount uint256 The amount of collateral deposited

Withdraw

emitted when collateral is withdrawn from the margin account

event Withdraw(address user, uint256 amount)

Parameters

Name Type Description
user address The address of the user withdrawing collateral
amount uint256 The amount of collateral withdrawn

IntentAuthorized

emitted when an intent account is authorized to act on behalf of the margin account

event IntentAuthorized(address marginAccountID, address intentAccount)

Parameters

Name Type Description
marginAccountID address The address of the margin account
intentAccount address The address of the intent account authorized

IntentRevoked

emitted when an intent account is revoked from acting on behalf of the margin account

event IntentRevoked(address marginAccountID, address intentAccount)

Parameters

Name Type Description
marginAccountID address The address of the margin account
intentAccount address The address of the intent account revoked

settle

settles a trade for a given position

function settle(address marginAccountID, address intentAccount, struct IMarginAccount.Settlement settlement) external returns (bool)

This function can only be called by the clearing house

Parameters

Name Type Description
marginAccountID address The address of the margin account
intentAccount address The address of the intent account
settlement struct IMarginAccount.Settlement The trade to settle (see Settlement)

Return Values

Name Type Description
[0] bool bool True if the trade was settled successfully

collectFee

collects a fee from the margin account

function collectFee(address marginAccount, int256 capitalAmount) external

This function can only be called by the clearing house Collected fees need to equal dispersed fees for a transaction not to revert

Parameters

Name Type Description
marginAccount address The address of the margin account
capitalAmount int256 The amount of capital to collect

disperseFees

disperses fees to the recipients

function disperseFees(address[] recipients, uint256[] capitalAmounts) external

This function can only be called by the clearing house The total amount of fees dispersed must equal the total amount of fees collected

Parameters

Name Type Description
recipients address[] The addresses of the recipients
capitalAmounts uint256[] The amounts of capital to disperse to each recipient

batchSettle

Settles trades for given list of settlements.

function batchSettle(address marginAccountID, struct IMarginAccount.Settlement[] settlements) external returns (bool)

This function can only be called by the clearing house

Parameters

Name Type Description
marginAccountID address The address of the margin account
settlements struct IMarginAccount.Settlement[] List of trades to be settled

Return Values

Name Type Description
[0] bool bool True if the trade was settled successfully

deposit

deposits collateral into the margin account

function deposit(uint256 amount) external

the collateral asset must be approved for transfer

Parameters

Name Type Description
amount uint256 The amount of collateral to deposit

withdraw

withdraws collateral from the margin account

function withdraw(uint256 amount) external

the user must have sufficient collateral in their margin account

Parameters

Name Type Description
amount uint256 The amount of collateral to withdraw

authorize

authorizes an intent account to act on behalf of the margin account

function authorize(address intentAccount) external

this function can only be called by the margin account owner

Parameters

Name Type Description
intentAccount address The address of the intent account to authorize

revokeAuthorization

Revokes authorization of an intent account to act on behalf of the margin account

function revokeAuthorization(address intentAccount) external

this function can only be called by the margin account owner

Parameters

Name Type Description
intentAccount address The address of the intent account

collateralAsset

returns the address of the ERC20 collateral asset for the margin account contract

function collateralAsset() external view returns (address)

Return Values

Name Type Description
[0] address The address of the ERC20 collateral asset

authorized

returns the address of the clearing house contract

function authorized(address marginAccountID, address intentAccount) external view returns (bool)

Return Values

Name Type Description
[0] bool the address of the clearing house

capital

returns the amount of capital in the margin account

function capital(address marginAccountID) external view returns (int256)

Parameters

Name Type Description
marginAccountID address The address of the margin account

Return Values

Name Type Description
[0] int256 the amount of capital in the margin account

mae

returns the amount of collateral in the margin account

function mae(address marginAccountID) external view returns (int256)

Parameters

Name Type Description
marginAccountID address The address of the margin account

Return Values

Name Type Description
[0] int256 the amount of collateral in the margin account

mmu

returns the maintenance margin used in the margin account

function mmu(address marginAccountID) external view returns (uint256)

Parameters

Name Type Description
marginAccountID address The address of the margin account

Return Values

Name Type Description
[0] uint256 the maintenance margin used

mma

returns the maintenance margin available in the margin account

function mma(address marginAccountID) external view returns (uint256)

Parameters

Name Type Description
marginAccountID address The address of the margin account

Return Values

Name Type Description
[0] uint256 the maintenance margin available

pnl

returns the unrealized profit and loss of the margin account

function pnl(address marginAccountID) external view returns (int256)

Parameters

Name Type Description
marginAccountID address The address of the margin account

Return Values

Name Type Description
[0] int256 the unrealized profit and loss

positionAge

returns weighted position age of a particular position on a margin account

function positionAge(address marginAccountID, bytes32 positionId) external view returns (uint256)

Parameters

Name Type Description
marginAccountID address The address of the margin account
positionId bytes32 The id of the position

Return Values

Name Type Description
[0] uint256 the weighted position age of the position

positionQuantity

returns the total quantity of a position in the margin account

function positionQuantity(address marginAccountID, bytes32 positionId) external view returns (int256)

Parameters

Name Type Description
marginAccountID address The address of the margin account
positionId bytes32 The id of the position

Return Values

Name Type Description
[0] int256 the total quantity of the position

withdrawable

returns the amount of collateral that can be withdrawn from the margin account

function withdrawable(address marginAccountID) external view returns (uint256)

Parameters

Name Type Description
marginAccountID address The address of the margin account

Return Values

Name Type Description
[0] uint256 the amount of collateral that can be withdrawn

positionCount

returns the number of positions held by the margin account

function positionCount(address marginAccountID) external view returns (uint256)

Parameters

Name Type Description
marginAccountID address The address of the margin account owner

Return Values

Name Type Description
[0] uint256 the number of positions held by the margin account

positions

returns the ids of all positions held by the margin account

function positions(address marginAccountID) external view returns (bytes32[])

Parameters

Name Type Description
marginAccountID address The address of the margin account

Return Values

Name Type Description
[0] bytes32[] an array of position ids

positionData

returns the position data for a given position id

function positionData(address marginAccountID, bytes32 positionId) external view returns (struct IMarginAccount.PositionData)

Parameters

Name Type Description
marginAccountID address The address of the margin account
positionId bytes32 The position id

Return Values

Name Type Description
[0] struct IMarginAccount.PositionData the position data

maeCheck

checks if the margin account has enough equity to settle a trade

function maeCheck(address marginAccountID, struct IMarginAccount.Settlement settlement, uint256 markPriceIfSettled) external view returns (bool checkPassed, int256 maeAfter, uint256 mmuAfter)

Parameters

Name Type Description
marginAccountID address The address of the margin account
settlement struct IMarginAccount.Settlement The trade to settle
markPriceIfSettled uint256 The mark price if the trade is settled

Return Values

Name Type Description
checkPassed bool True if the margin account has enough equity to settle the trade
maeAfter int256 MAE of the account if the trade is settled
mmuAfter uint256 MMU of the account if the trade is settled

batchMaeCheck

Checks if the margin account has enough equity to settle a list of trades. The position ids in the list settlements must be distinct to get proper result.

function batchMaeCheck(address marginAccountID, struct IMarginAccount.Settlement[] settlements, uint256[] markPriceIfSettled) external view returns (bool checkPassed, int256 maeAfter, uint256 mmuAfter)

Parameters

Name Type Description
marginAccountID address The address of the margin account
settlements struct IMarginAccount.Settlement[] List of trades to be settled
markPriceIfSettled uint256[] Mark prices if the trades are settled successfully

Return Values

Name Type Description
checkPassed bool True if the margin account has enough equity to settle the trades
maeAfter int256 MAE of the account if the trades are settled
mmuAfter uint256 MMU of the account if the trades are settled

maeAndMmuAfterBatchTrade

Calculates the MAE and the MMU after settling a list of trades. The position ids in the list settlements must be distinct to get proper result.

function maeAndMmuAfterBatchTrade(address marginAccountID, struct IMarginAccount.Settlement[] settlements, uint256[] markPriceIfSettled) external view returns (int256 mae, uint256 mmu)

Parameters

Name Type Description
marginAccountID address The address of the margin account
settlements struct IMarginAccount.Settlement[] List of trades to be settled
markPriceIfSettled uint256[] Mark prices if the trades are settled successfully

Return Values

Name Type Description
mae int256 MAE if the trades are settled
mmu uint256 MMU if the trades are settled

positionPnL

Calculates the PnL of a position in the margin account

function positionPnL(address marginAccount, bytes32 positionId) external view returns (int256)

Parameters

Name Type Description
marginAccount address The address of the margin account
positionId bytes32 The id of the position

Return Values

Name Type Description
[0] int256 the PnL of the position (in collateral asset)

estimateLiquidationPriceForPosition

Calculates the price at which the account would become liquidatable

function estimateLiquidationPriceForPosition(address marginAccountID, bytes32 positionId) external view returns (uint256)

The liquidation price is the price at which the position’s PnL would be equal to the maintenance margin, assuming all other positions remain at their current mark prices.

Parameters

Name Type Description
marginAccountID address The address of the margin account
positionId bytes32 The id of the position (productID)

Return Values

Name Type Description
[0] uint256 the liquidation price of the position (in collateral asset)

estimateLiquidationPrice

Calculates the price at which an account would be liquidatable if the trade is executed

function estimateLiquidationPrice(address marginAccountID, bytes32 productID, uint256 tradePrice, int256 tradeQuantity) external view returns (uint256)

Parameters

Name Type Description
marginAccountID address The address of the margin account
productID bytes32 The id of the product
tradePrice uint256 The price at which the trade would be executed
tradeQuantity int256 The quantity of the trade

Return Values

Name Type Description
[0] uint256 the liquidation price of the position (in collateral asset)

IMarginAccountRegistry

Deployed Addresses

Chain ID Address
65000000 0x99f4FA9Cdce7AD227eB84907936a8FeF2095D846
65010004 0xDA71FdE0E7cfFf445e848EAdB3B2255B68Ed6ef6
65100004 0x216a1fa7c98d7f7304bC4D7d0F856d063f2ecBA5

Functions

MarginAccountCreated

event MarginAccountCreated(address collateralAsset, address marginAccount)

getMarginAccount

returns the margin account contract for a given collateral asset

function getMarginAccount(address collateralAsset) external view returns (contract IMarginAccount)

this function should revert if the margin account does not exist

Parameters

Name Type Description
collateralAsset address the collateral asset

Return Values

Name Type Description
[0] contract IMarginAccount the margin account contract

initializeMarginAccount

deploys and initializes a margin account contract for the given asset

function initializeMarginAccount(address collateralAsset) external returns (contract IMarginAccount)

Parameters

Name Type Description
collateralAsset address the collateral asset

Return Values

Name Type Description
[0] contract IMarginAccount the margin account contract

IOracleProvider

Deployed Addresses

Chain ID Address
65000000 0xF2A2A27da33D30B4BF38D7e186E7B0b1e964e55c
65010004 0x626da921088a5A00C75C208Decbb60E816488481
65100004 0xF3FA1f6fe52604EFf85B438B01B8b984AA200651

Functions

resolve

returns the final settlement price of a given product

function resolve(bytes32 productId, bytes oracleCalldata) external view returns (int256)

this function should revert if the product has not reached final settlement

Parameters

Name Type Description
productId bytes32 the product id from the ProductRegistry
oracleCalldata bytes additional data required by the oracle to resolve the price

Return Values

Name Type Description
[0] int256 the final settlement price of the product

ProductState

enum ProductState {
  NOT_EXIST,
  PENDING,
  LIVE,
  TRADEOUT,
  FINAL_SETTLEMENT,
  EXPIRED
}

IProductRegistry

Deployed Addresses

Chain ID Address
65000000 0x86B3829471929B115367DA0958f56A6AB844b08e
65010004 0x9b92EAC112c996a513e515Cf8c3BDd83619F730D
65100004 0x05A7f949caE3235f239313339a7f9661F8C7415d

Functions

ProductMetadata

the metadata associated with a product - builder - the address of the product creator - symbol - the symbol for this product - description - the description of the product

struct ProductMetadata {
  address builder;
  string symbol;
  string description;
}

OracleSpecification

the oracle specification for a product - oracleAddress - the address of the oracle contract - fsvDecimals - the precision of the price quotation from oracleAddress.resolve - fspAlpha - the alpha value for the oracle, used in price calculations fsp = alpha * oraclePrice + beta - fspBeta - the beta value for the oracle, used in price calculations fsp = alpha * oraclePrice + beta - fsvCalldata - the calldata to be used for final settlement price (FSP) calculation

the oracleAddress must implement the IOracleProvider interface

struct OracleSpecification {
  address oracleAddress;
  uint8 fsvDecimals;
  int256 fspAlpha;
  int256 fspBeta;
  bytes fsvCalldata;
}

Product

the product struct that contains all the information about a product registered with the clearing system - metadata - the metadata associated with the product - oracleSpec - the oracle specification for the product - priceQuotation - the symbol of the price quotation - collateralAsset - the address of the ERC20 collateral asset - startTime - the start time of the product - earliestFSPSubmissionTime - the earliest time to submit the final settlement price - unitValue - the point value of the product - initialMarginRequirement - the initial margin requirement for the product - maintenanceMarginRequirement - the maintenance margin requirement for the product - auctionBounty - the bounty for the auctioneer - tradeoutInterval - the interval for tradeout - tickSize - the maximum precision of the price quotation - extendedMetadata - CID of product extended metadata using the IPLD dag-json codec

struct Product {
  struct IProductRegistry.ProductMetadata metadata;
  struct IProductRegistry.OracleSpecification oracleSpec;
  string priceQuotation;
  address collateralAsset;
  uint256 startTime;
  uint256 earliestFSPSubmissionTime;
  uint256 unitValue;
  uint16 initialMarginRequirement;
  uint16 maintenanceMarginRequirement;
  uint64 auctionBounty;
  uint32 tradeoutInterval;
  uint8 tickSize;
  string extendedMetadata;
}

ProductRegistered

Event emitted when a new product is registered

event ProductRegistered(address builder, bytes32 productId)

Parameters

Name Type Description
builder address the address of the product builder
productId bytes32 the product ID of the registered product

products

returns the product struct for a given product ID

function products(bytes32 productId) external view returns (struct IProductRegistry.Product)

Parameters

Name Type Description
productId bytes32 the product id

Return Values

Name Type Description
[0] struct IProductRegistry.Product the product struct

state

returns the product state for a given product ID

function state(bytes32 productId) external view returns (enum ProductState)

Parameters

Name Type Description
productId bytes32 the product id

Return Values

Name Type Description
[0] enum ProductState the product state (NOT_EXIST, PENDING, LIVE, TRADEOUT, FINAL_SETTLEMENT, EXPIRED)

collateralAsset

the address of the ERC20 collateral asset

function collateralAsset(bytes32 productId) external view returns (address)

Parameters

Name Type Description
productId bytes32 the product id

Return Values

Name Type Description
[0] address the product state

pointValue

the point value of the product

function pointValue(bytes32 productId) external view returns (uint256)

Parameters

Name Type Description
productId bytes32 the product id

Return Values

Name Type Description
[0] uint256 the point value of the product

earliestFSPSubmissionTime

the earliest time to submit FSP

function earliestFSPSubmissionTime(bytes32 productId) external view returns (uint256)

Parameters

Name Type Description
productId bytes32 the product id

Return Values

Name Type Description
[0] uint256 the earliest time to submit FSP

imr

the initial margin requirement for the product

function imr(bytes32 productId) external view returns (uint256)

Parameters

Name Type Description
productId bytes32 the product id

Return Values

Name Type Description
[0] uint256 the initial margin requirement

mmr

mmr the maintenance margin requirement for the product

function mmr(bytes32 productId) external view returns (uint256)

Parameters

Name Type Description
productId bytes32 the product id

Return Values

Name Type Description
[0] uint256 the maintenance margin requirement

tickSize

tickSize the maximum precision of the price quotation

function tickSize(bytes32 productId) external view returns (uint256)

Parameters

Name Type Description
productId bytes32 the product id

Return Values

Name Type Description
[0] uint256 the number of decimal places in the price quotation

id

returns the product ID for a given product

function id(struct IProductRegistry.Product product) external pure returns (bytes32)

Parameters

Name Type Description
product struct IProductRegistry.Product the product to be registered

Return Values

Name Type Description
[0] bytes32 the product ID

auctionBounty

returns the auction bounty

function auctionBounty(bytes32 productId) external view returns (uint256)

Parameters

Name Type Description
productId bytes32 the product id

Return Values

Name Type Description
[0] uint256 the auction bounty for the product

oracleSpecification

returns the oracle specification for a given product

function oracleSpecification(bytes32 productId) external view returns (struct IProductRegistry.OracleSpecification)

Parameters

Name Type Description
productId bytes32 the product id

Return Values

Name Type Description
[0] struct IProductRegistry.OracleSpecification the OracleSpecification for the product

register

register a new product

function register(struct IProductRegistry.Product product) external

this function can only be called by the product builder and must pass the product validity checks

Parameters

Name Type Description
product struct IProductRegistry.Product the product to be registered

ISystemViewer

This interface represents a set of read-only functions to view the state of the system.

Deployed Addresses

Chain ID Address
65000000 0xfF2DFcC44a95cce96E03EfC33C65c8Be671Bae5B
65010004 0xcB3F71Db710544283a1FfB38FE1bEC554d0634A5

Functions

UserMarginAccountData

Contains information about a user’s margin account - collateralAsset - the collateral asset of the margin account - marginAccountId - the account - mae - the margin account equity of the account (in collateral asset units) - mmu - the maintenance margin requirement of the account (in collateral asset units) - positions - the positions held in the margin account

struct UserMarginAccountData {
  address collateralAsset;
  address marginAccountId;
  int256 mae;
  uint256 mmu;
  struct IMarginAccount.PositionData[] positions;
}

maeChecksByCollateralAsset

Performs margin account equity (MAE) checks for multiple accounts associated with a specific collateral asset, after applying a series of settlements.

function maeChecksByCollateralAsset(address collateralAsset, address[] accounts, struct IMarginAccount.Settlement[] settlements) external view returns (bool[] results, int256[] maeAfter, uint256[] mmuAfter)

Parameters

Name Type Description
collateralAsset address The address of the collateral asset.
accounts address[] An array of account addresses.
settlements struct IMarginAccount.Settlement[] An array of Settlement structs representing the settlements to be applied to each account.

Return Values

Name Type Description
results bool[] An array of boolean values indicating whether each account passes the MAE check after settlements.
maeAfter int256[] An array of MAE values for each account after applying the settlements.
mmuAfter uint256[] An array of maintenance margin requirement (MMU) values for each account after applying the settlements.

maeByCollateralAsset

Fetches the Margin Account Equity (MAE) for multiple accounts associated with a specific collateral asset.

function maeByCollateralAsset(address collateralAsset, address[] accounts) external view returns (int256[] results)

Parameters

Name Type Description
collateralAsset address The address of the collateral asset.
accounts address[] An array of account addresses.

Return Values

Name Type Description
results int256[] An array of MAE values corresponding to each account.

maeByCollateralAssets

Fetches the Margin Account Equity (MAE) for multiple accounts across multiple collateral assets.

function maeByCollateralAssets(address[] collateralAssets, address[] accounts) external view returns (int256[] results)

Parameters

Name Type Description
collateralAssets address[] An array of collateral asset addresses.
accounts address[] An array of account addresses.

Return Values

Name Type Description
results int256[] An array of MAE values corresponding to each account and collateral asset pair.

positionsByCollateralAsset

Fetches positions for multiple accounts associated with a specific collateral asset.

function positionsByCollateralAsset(address collateralAsset, address[] accounts) external view returns (struct IMarginAccount.PositionData[][] results)

Parameters

Name Type Description
collateralAsset address The address of the collateral asset.
accounts address[] An array of account addresses.

Return Values

Name Type Description
results struct IMarginAccount.PositionData[][] A 2D array where each sub-array contains the positions for the corresponding account.

positionsByCollateralAssets

Fetches positions for multiple accounts across multiple collateral assets.

function positionsByCollateralAssets(address[] collateralAssets, address[] accounts) external view returns (struct IMarginAccount.PositionData[][] results)

Parameters

Name Type Description
collateralAssets address[] An array of collateral asset addresses.
accounts address[] An array of account addresses.

Return Values

Name Type Description
results struct IMarginAccount.PositionData[][] A 2D array where each sub-array contains the positions for the corresponding account and collateral asset.

valuations

Fetches the current mark price of multiple products from the Valuation contract.

function valuations(bytes32[] productIds) external view returns (uint256[] prices)

Parameters

Name Type Description
productIds bytes32[] An array of product IDs to fetch valuations for.

Return Values

Name Type Description
prices uint256[] An array of current mark prices for each product ID.

productDetails

Fetches detailed information about multiple products from the Product Registry.

function productDetails(bytes32[] productIds) external view returns (struct IProductRegistry.Product[] details)

Parameters

Name Type Description
productIds bytes32[] An array of product IDs to fetch details for.

Return Values

Name Type Description
details struct IProductRegistry.Product[] An array of Product structs

productStates

Fetches the current states of multiple products from the Product Registry.

function productStates(bytes32[] productIds) external view returns (enum ProductState[] states)

Parameters

Name Type Description
productIds bytes32[] An array of product IDs to fetch states for.

Return Values

Name Type Description
states enum ProductState[] An array of ProductState enums representing the current state of each product.

userMarginDataByCollateralAsset

Fetches margin account data for multiple users associated with a specific collateral asset.

function userMarginDataByCollateralAsset(address collateralAsset, address[] accounts) external view returns (struct ISystemViewer.UserMarginAccountData[] data)

Parameters

Name Type Description
collateralAsset address The address of the collateral asset.
accounts address[] An array of user account addresses to fetch margin data for.

Return Values

Name Type Description
data struct ISystemViewer.UserMarginAccountData[] An array of UserMarginAccountData structs containing margin account details for each user.

userMarginDataByCollateralAssets

Fetches margin account data for multiple users across multiple collateral assets.

function userMarginDataByCollateralAssets(address[] collateralAssets, address[] accounts) external view returns (struct ISystemViewer.UserMarginAccountData[] data)

Parameters

Name Type Description
collateralAssets address[] An array of collateral asset addresses.
accounts address[] An array of user account addresses to fetch margin data for.

Return Values

Name Type Description
data struct ISystemViewer.UserMarginAccountData[] An array of UserMarginAccountData structs containing margin account details for each user.

ITrackInterest

Deployed Addresses

Chain ID Address
65000000 0x5B5411F1548254d25360d71FE40cFc1cC983B2A2
65010004 0xB894bFf368Bf1EA89c18612670B7E072866a5264
65100004 0x393746A87CF3458EeA2b47BF035496429AbFBD66

Functions

openInterest

returns the current open interest on the product

function openInterest(bytes32 productId) external view returns (uint256)

Parameters

Name Type Description
productId bytes32 the product

Return Values

Name Type Description
[0] uint256 the open interest of the product

ITradingProtocol

Deployed Addresses

Chain ID Address
65000000 0x107668375a05f0782368C5954F8126ab0B477B8B
65010004 0x1758BCf0a0AfD98691F6C38DAB4e9ad0E3BDAA7a
65100004 0x504b1d5B2364F85002889B741ae7D434B0ac0C77

Functions

SequenceExecuted

emitted after executing a sequence of trades

event SequenceExecuted(bool[] results, bytes[] errors)

Parameters

Name Type Description
results bool[] whether each trade was successfully executed or not
errors bytes[] errors that occured during execution

execute

execute a trade with the clearing protocol

function execute(struct IClearing.Trade trade, bool fallbackOnFailure) external

this function is restricted to valid trade submitters

Parameters

Name Type Description
trade struct IClearing.Trade the trade to execute
fallbackOnFailure bool if true, the trading protocol’s margin account will be substituted if MAE checks fail

executeSequence

executes a sequence of trades with the clearing protocol

function executeSequence(struct IClearing.Trade[] trades, bool fallbackOnFailure) external

this function is restricted to valid trade submitters

Parameters

Name Type Description
trades struct IClearing.Trade[] the array of trades to execute
fallbackOnFailure bool if true, the trading protocol’s margin account will be substituted for any margin account in the trade that fails the MAE check

addTradeSubmitter

adds a whitelisted trade submitter

function addTradeSubmitter(address submitter) external

this function is restricted to the owner of the trading protocol

Parameters

Name Type Description
submitter address the address of the trade submitter

removeTradeSubmitter

removes a whitelisted trade submitter

function removeTradeSubmitter(address submitter) external

this function is restricted to the owner of the trading protocol

Parameters

Name Type Description
submitter address the address of the trade submitter

deposit

deposit’s in the margin account

function deposit(address marginAccountContract, uint256 amount) external

this function is restricted to the owner of the trading protocol

Parameters

Name Type Description
marginAccountContract address the address of the margin account contract
amount uint256 the amount to deposit

withdraw

withdraws from the margin account

function withdraw(address marginAccountContract, uint256 amount) external

this function is restricted to the owner of the trading protocol

Parameters

Name Type Description
marginAccountContract address the address of the margin account contract
amount uint256 the amount to withdraw

IValuation

Deployed Addresses

Chain ID Address
65000000 0x5B5411F1548254d25360d71FE40cFc1cC983B2A2
65010004 0xB894bFf368Bf1EA89c18612670B7E072866a5264
65100004 0x393746A87CF3458EeA2b47BF035496429AbFBD66

Functions

valuation

returns a product’s current mark price

function valuation(bytes32 productId) external view returns (uint256)

Parameters

Name Type Description
productId bytes32 the product

Return Values

Name Type Description
[0] uint256 the mark price of the product

valuationAfterTrade

returns what a product’s mark price will be after a trade

function valuationAfterTrade(bytes32 productId, uint256 price, uint256 quantity) external view returns (uint256)

Parameters

Name Type Description
productId bytes32 the product
price uint256 the price of the trade
quantity uint256 the quantity of the trade

Return Values

Name Type Description
[0] uint256 the mark price of the product after the trade