// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
import "../libraries/Types.sol";
interface IDealer {
/// @notice Deposit fund to get credit for
/// @param primaryAmount is the amount of primary asset you want to deposit.
/// @param secondaryAmount is the amount of secondary asset you want to deposit.
/// @param to is the account you want to deposit to.
function deposit(uint256 primaryAmount, uint256 secondaryAmount, address to) external;
/// @notice Submit withdrawal request, which can be executed after
/// the timelock. The main purpose of this function is to avoid the
/// failure of counterparty caused by withdrawal.
/// @param from The deducted account.
/// @param primaryAmount is the amount of primary asset you want to withdraw.
/// @param secondaryAmount is the amount of secondary asset you want to withdraw.
function requestWithdraw(address from, uint256 primaryAmount, uint256 secondaryAmount) external;
/// @notice Execute the withdrawal request.
/// @param from The deducted account.
/// @param to is the address receiving assets.
/// @param isInternal Only internal credit transfers will be made,
/// and ERC20 transfers will not happen.
/// @param param call "to" with param if not null.
function executeWithdraw(address from, address to, bool isInternal, bytes memory param) external;
/// @notice Withdraw without waiting.
/// @param from The deducted account.
/// @param to is the address receiving assets.
/// @param primaryAmount is the amount of primary asset you want to withdraw.
/// @param secondaryAmount is the amount of secondary asset you want to
/// @param isInternal Only internal credit transfers will be made,
/// and ERC20 transfers will not happen.
/// @param param call "to" with param if not null.
function fastWithdraw(
address from,
address to,
uint256 primaryAmount,
uint256 secondaryAmount,
bool isInternal,
bytes memory param
)
external;
/// @notice Help perpetual contract parse tradeData and return
/// the balance changes of each trader.
/// @dev only perpetual contract can call this function
/// @param orderSender is the one who submit tradeData.
/// @param tradeData contains orders, signatures and match info.
function approveTrade(
address orderSender,
bytes calldata tradeData
)
external
returns (address[] memory traderList, int256[] memory paperChangeList, int256[] memory creditChangeList);
/// @notice Check if the trader's margin is enough (>= maintenance margin).
/// If so, the trader is "safe".
/// The trader's positions under all markets will be liquidated if he is
/// not safe.
function isSafe(address trader) external view returns (bool);
/// @notice Check if a list of traders are safe.
/// @dev This function is more gas effective than isSafe, by caching
/// mark prices.
function isAllSafe(address[] calldata traderList) external view returns (bool);
/// @notice Get funding rate of a perpetual market.
/// Funding rate is a 1e18 based decimal.
function getFundingRate(address perp) external view returns (int256);
/// @notice Update multiple funding rate at once.
/// Can only be called by funding rate keeper.
function updateFundingRate(address[] calldata perpList, int256[] calldata rateList) external;
/// @notice Calculate the paper and credit change of liquidator and
/// liquidated trader.
/// @dev Only perpetual contract can call this function.
/// liqtor is short for liquidator, liqed is short for liquidated trader.
/// @param executor is the one who will excute liquidation.
/// @param liquidator is the one who will take over positions.
/// @param liquidatedTrader is the one who is being liquidated.
/// @param requestPaperAmount is the size that the liquidator wants to take.
/// Positive if the position is long, negative if the position is short.
function requestLiquidation(
address executor,
address liquidator,
address liquidatedTrader,
int256 requestPaperAmount
)
external
returns (int256 liqtorPaperChange, int256 liqtorCreditChange, int256 liqedPaperChange, int256 liqedCreditChange);
/// @notice Transfer all bad debt to insurance account,
/// including primary and secondary balances.
function handleBadDebt(address liquidatedTrader) external;
/// @notice Register the trader's position into dealer.
/// @dev Only perpetual contract can call this function when
/// someone's position is opened.
function openPosition(address trader) external;
/// @notice Accrual realized pnl and remove the trader's position from dealer.
/// @dev Only perpetual contract can call this function when
/// someone's position is closed.
function realizePnl(address trader, int256 pnl) external;
/// @notice Register operator.
/// The operator can sign order on your behalf.
function setOperator(address operator, bool isValid) external;
/// @param perp the address of perpetual contract market
function getRiskParams(address perp) external view returns (Types.RiskParams memory params);
/// @notice Return all registered perpetual contract market.
function getAllRegisteredPerps() external view returns (address[] memory);
/// @notice Return mark price of a perpetual market.
/// price is a 1e18 based decimal.
function getMarkPrice(address perp) external view returns (uint256);
/// @notice Get all open positions of the trader.
function getPositions(address trader) external view returns (address[] memory);
/// @notice Return the credit details of the trader.
/// You cannot use credit as net value or net margin of a trader.
/// The net value of positions would also be included.
function getCreditOf(address trader)
external
view
returns (
int256 primaryCredit,
uint256 secondaryCredit,
uint256 pendingPrimaryWithdraw,
uint256 pendingSecondaryWithdraw,
uint256 executionTimestamp
);
/// @notice Get the risk profile data of a trader.
/// @return netValue net value of trader including credit amount
/// @return exposure open position value of the trader across all markets
/// @return initialMargin Funds required to open a position.
/// @return maintenanceMargin Funds needed to keep a position open.
function getTraderRisk(address trader)
external
view
returns (int256 netValue, uint256 exposure, uint256 initialMargin, uint256 maintenanceMargin);
/// @notice Get liquidation price of a position
/// @dev This function is for directional use. The margin of error is typically
/// within 10 wei.
/// @return liquidationPrice equals 0 if there is no liquidation price.
function getLiquidationPrice(address trader, address perp) external view returns (uint256 liquidationPrice);
/// @notice a view version of requestLiquidation, liquidators can use
/// this function to check how much you have to pay in advance.
function getLiquidationCost(
address perp,
address liquidatedTrader,
int256 requestPaperAmount
)
external
view
returns (int256 liqtorPaperChange, int256 liqtorCreditChange);
/// @notice Get filled paper amount of an order to avoid double matching.
/// @return filledAmount includes paper amount
function getOrderFilledAmount(bytes32 orderHash) external view returns (uint256 filledAmount);
/// @notice check if order sender is valid
function isOrderSenderValid(address orderSender) external view returns (bool);
/// @notice check if fastWithdrawl is valid
function isFastWithdrawalValid(address fastWithdrawOperator) external view returns (bool);
/// @notice check if operator is valid
function isOperatorValid(address client, address operator) external view returns (bool);
/// @notice check if spender can operate from
function isCreditAllowed(
address from,
address spender
)
external
view
returns (uint256 primaryCreditAllowed, uint256 secondaryCreditAllowed);
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
interface IPerpetual {
/// @notice Return the paper amount and credit amount of a certain trader.
/// @return paper is positive when the trader holds a long position and
/// negative when the trader holds a short position.
/// @return credit is not related to position direction or entry price,
/// only used to calculate risk ratio and net value.
function balanceOf(address trader) external view returns (int256 paper, int256 credit);
/// @notice Match and settle orders.
/// @dev tradeData will be forwarded to the Dealer contract and waiting
/// for matching result. Then the Perpetual contract will execute the result.
function trade(bytes calldata tradeData) external;
/// @notice Liquidate a position with customized paper amount and price protection.
/// @dev Because the liquidation is open to public, there is no guarantee that
/// your request will be executed.
/// It will not be executed or partially executed if:
/// 1) someone else submitted a liquidation request before you, or
/// 2) the trader deposited enough margin in time, or
/// 3) the mark price moved beyond your price protection.
/// Your liquidation will be limited to the position size. For example, if the
/// position remains 10ETH and you're requesting a 15ETH liquidation. Only 10ETH
/// will be executed. And the other 5ETH request will be cancelled.
/// @param liquidator is the trader who liquidate others.
/// @param liquidatedTrader is the trader you want to liquidate.
/// @param requestPaper is the size of position you want to take .
/// requestPaper is positive when you want to liquidate a long position, negative when short.
/// @param expectCredit is the amount of credit you want to pay (when liquidating a short position)
/// or receive (when liquidating a long position)
/// @return liqtorPaperChange is the final executed change of liquidator's paper amount
/// @return liqtorCreditChange is the final executed change of liquidator's credit amount
function liquidate(
address liquidator,
address liquidatedTrader,
int256 requestPaper,
int256 expectCredit
)
external
returns (int256 liqtorPaperChange, int256 liqtorCreditChange);
/// @notice Get funding rate of this perpetual market.
/// Funding rate is a 1e18 based decimal.
function getFundingRate() external view returns (int256);
/// @notice Update funding rate, owner only function.
function updateFundingRate(int256 newFundingRate) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "./interfaces/IDealer.sol";
import "./interfaces/IPerpetual.sol";
import "./libraries/SignedDecimalMath.sol";
contract Perpetual is Ownable, IPerpetual {
using SignedDecimalMath for int256;
// ========== storage ==========
/*
We use int128 to store paper and reduced credit,
so that we could store balance in a single slot.
This trick can help us saving gas.
int128 can support size of 1.7E38, which is enough
for most transactions. But other than storing paper
and reduced credit values, we use int256 to achieve
higher accuracy of calculation.
Normally, paper amount will be a 1e18 based decimal.
*/
struct balance {
int128 paper;
int128 reducedCredit;
}
mapping(address => balance) balanceMap;
int256 fundingRate;
// ========== events ==========
event BalanceChange(address indexed trader, int256 paperChange, int256 creditChange);
event UpdateFundingRate(int256 oldFundingRate, int256 newFundingRate);
// ========== constructor ==========
constructor(address _owner) Ownable() {
transferOwnership(_owner);
}
// ========== balance related ==========
/*
We store "reducedCredit" instead of credit itself.
So that after funding rate is updated, the credit values will be
updated without any extra storage write.
credit = (paper * fundingRate) + reducedCredit
FundingRate here is a little different from what it means at CEX.
FundingRate is a cumulative value. Its absolute value doesn't mean
anything and only the changes (due to funding updates) matter.
e.g. If the fundingRate increases by 5 at a certain update,
then you will receive 5 credit for every paper you long.
And you will be charged 5 credit for every paper you short.
*/
/// @inheritdoc IPerpetual
function balanceOf(address trader) external view returns (int256 paper, int256 credit) {
paper = int256(balanceMap[trader].paper);
credit = paper.decimalMul(fundingRate) + int256(balanceMap[trader].reducedCredit);
}
function updateFundingRate(int256 newFundingRate) external onlyOwner {
int256 oldFundingRate = fundingRate;
fundingRate = newFundingRate;
emit UpdateFundingRate(oldFundingRate, newFundingRate);
}
function getFundingRate() external view returns (int256) {
return fundingRate;
}
// ========== trade ==========
/// @inheritdoc IPerpetual
function trade(bytes calldata tradeData) external {
(address[] memory traderList, int256[] memory paperChangeList, int256[] memory creditChangeList) =
IDealer(owner()).approveTrade(msg.sender, tradeData);
for (uint256 i = 0; i < traderList.length;) {
_settle(traderList[i], paperChangeList[i], creditChangeList[i]);
unchecked {
++i;
}
}
require(IDealer(owner()).isAllSafe(traderList), "TRADER_NOT_SAFE");
}
// ========== liquidation ==========
/// @inheritdoc IPerpetual
function liquidate(
address liquidator,
address liquidatedTrader,
int256 requestPaper,
int256 expectCredit
)
external
returns (int256 liqtorPaperChange, int256 liqtorCreditChange)
{
// liqed => liquidated trader, who faces the risk of liquidation.
// liqtor => liquidator, who takes over the trader's position.
int256 liqedPaperChange;
int256 liqedCreditChange;
(liqtorPaperChange, liqtorCreditChange, liqedPaperChange, liqedCreditChange) =
IDealer(owner()).requestLiquidation(msg.sender, liquidator, liquidatedTrader, requestPaper);
// expected price = expectCredit/requestPaper * -1
// execute price = liqtorCreditChange/liqtorPaperChange * -1
if (liqtorPaperChange < 0) {
// open short, execute price >= expected price
// liqtorCreditChange/liqtorPaperChange * -1 >= expectCredit/requestPaper * -1
// liqtorCreditChange/liqtorPaperChange <= expectCredit/requestPaper
// liqtorCreditChange*requestPaper <= expectCredit*liqtorPaperChange
require(
liqtorCreditChange * requestPaper <= expectCredit * liqtorPaperChange, "LIQUIDATION_PRICE_PROTECTION"
);
} else {
// open long, execute price <= expected price
// liqtorCreditChange/liqtorPaperChange * -1 <= expectCredit/requestPaper * -1
// liqtorCreditChange/liqtorPaperChange >= expectCredit/requestPaper
// liqtorCreditChange*requestPaper >= expectCredit*liqtorPaperChange
require(
liqtorCreditChange * requestPaper >= expectCredit * liqtorPaperChange, "LIQUIDATION_PRICE_PROTECTION"
);
}
_settle(liquidatedTrader, liqedPaperChange, liqedCreditChange);
_settle(liquidator, liqtorPaperChange, liqtorCreditChange);
require(IDealer(owner()).isSafe(liquidator), "LIQUIDATOR_NOT_SAFE");
if (balanceMap[liquidatedTrader].paper == 0) {
IDealer(owner()).handleBadDebt(liquidatedTrader);
}
}
// ========== settlement ==========
/*
Remember the fomula?
credit = (paper * fundingRate) + reducedCredit
So we have...
reducedCredit = credit - (paper * fundingRate)
When you update the balance, you need to first calculate the credit,
and then calculate and store the reducedCredit.
*/
function _settle(address trader, int256 paperChange, int256 creditChange) internal {
bool isNewPosition = balanceMap[trader].paper == 0;
int256 rate = fundingRate; // gas saving
int256 credit =
int256(balanceMap[trader].paper).decimalMul(rate) + int256(balanceMap[trader].reducedCredit) + creditChange;
int128 newPaper = balanceMap[trader].paper + SafeCast.toInt128(paperChange);
int128 newReducedCredit = SafeCast.toInt128(credit - int256(newPaper).decimalMul(rate));
balanceMap[trader].paper = newPaper;
balanceMap[trader].reducedCredit = newReducedCredit;
emit BalanceChange(trader, paperChange, creditChange);
if (isNewPosition) {
IDealer(owner()).openPosition(trader);
}
if (newPaper == 0) {
// realize PNL
IDealer(owner()).realizePnl(trader, balanceMap[trader].reducedCredit);
balanceMap[trader].reducedCredit = 0;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toUint248(uint256 value) internal pure returns (uint248) {
require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toUint240(uint256 value) internal pure returns (uint240) {
require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toUint232(uint256 value) internal pure returns (uint232) {
require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.2._
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toUint216(uint256 value) internal pure returns (uint216) {
require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toUint208(uint256 value) internal pure returns (uint208) {
require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toUint200(uint256 value) internal pure returns (uint200) {
require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toUint192(uint256 value) internal pure returns (uint192) {
require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toUint184(uint256 value) internal pure returns (uint184) {
require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toUint176(uint256 value) internal pure returns (uint176) {
require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toUint168(uint256 value) internal pure returns (uint168) {
require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toUint160(uint256 value) internal pure returns (uint160) {
require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toUint152(uint256 value) internal pure returns (uint152) {
require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toUint144(uint256 value) internal pure returns (uint144) {
require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toUint136(uint256 value) internal pure returns (uint136) {
require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v2.5._
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toUint120(uint256 value) internal pure returns (uint120) {
require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toUint112(uint256 value) internal pure returns (uint112) {
require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toUint104(uint256 value) internal pure returns (uint104) {
require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.2._
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toUint88(uint256 value) internal pure returns (uint88) {
require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toUint80(uint256 value) internal pure returns (uint80) {
require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toUint72(uint256 value) internal pure returns (uint72) {
require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v2.5._
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toUint56(uint256 value) internal pure returns (uint56) {
require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toUint48(uint256 value) internal pure returns (uint48) {
require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v2.5._
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toUint24(uint256 value) internal pure returns (uint24) {
require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v2.5._
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v2.5._
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*
* _Available since v3.0._
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.7._
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.7._
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*
* _Available since v3.0._
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
/// @notice Decimal math for int256. Round down.
library SignedDecimalMath {
int256 constant SignedONE = 10 ** 18;
uint256 constant ONE = 1e18;
function decimalMul(int256 a, int256 b) internal pure returns (int256) {
return (a * b) / SignedONE;
}
function decimalDiv(int256 a, int256 b) internal pure returns (int256) {
return (a * SignedONE) / b;
}
function abs(int256 a) internal pure returns (uint256) {
return a < 0 ? uint256(a * -1) : uint256(a);
}
function decimalMul(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * b) / ONE;
}
function decimalDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * ONE) / b;
}
function decimalRemainder(uint256 a, uint256 b) internal pure returns (bool) {
if ((a * ONE) % b == 0) {
return true;
} else {
return false;
}
}
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
library Types {
uint256 public constant SECONDS_PER_YEAR = 365 days;
uint256 public constant ONE = 1e18;
/// @notice data structure of dealer
struct State {
// primary asset, ERC20
address primaryAsset;
// secondary asset, ERC20
address secondaryAsset;
// credit, gained by deposit assets
mapping(address => int256) primaryCredit;
mapping(address => uint256) secondaryCredit;
// allow fund operators to withdraw
mapping(address => mapping(address => uint256)) primaryCreditAllowed;
mapping(address => mapping(address => uint256)) secondaryCreditAllowed;
// withdrawal request time lock
uint256 withdrawTimeLock;
// pending primary asset withdrawal amount
mapping(address => uint256) pendingPrimaryWithdraw;
// pending secondary asset withdrawal amount
mapping(address => uint256) pendingSecondaryWithdraw;
// withdrawal request executable timestamp
mapping(address => uint256) withdrawExecutionTimestamp;
// perpetual contract risk parameters
mapping(address => Types.RiskParams) perpRiskParams;
// perpetual contract registry, for view
address[] registeredPerp;
// all open positions of a trader
mapping(address => address[]) openPositions;
// For offchain pnl calculation, serial number +1 whenever
// position is fully closed.
// trader => perpetual contract address => current serial Num
mapping(address => mapping(address => uint256)) positionSerialNum;
// filled amount of orders
mapping(bytes32 => uint256) orderFilledPaperAmount;
// valid order sender registry
mapping(address => bool) validOrderSender;
// addresses that can make fast withdrawal
mapping(address => bool) fastWithdrawalWhitelist;
bool fastWithdrawDisabled;
// operator registry
// client => operator => isValid
mapping(address => mapping(address => bool)) operatorRegistry;
// insurance account
address insurance;
// funding rate keeper, normally an EOA account
address fundingRateKeeper;
uint256 maxPositionAmount;
mapping(address => bool) isWithdrawalWhitelist;
}
struct Order {
// address of perpetual market
address perp;
/*
Signer is trader, the identity of behavior,
whose balance will be changed.
Normally it should be an EOA account and the
order is valid only if the signer signed it.
If the signer is a smart contract, it has two ways
to sign the order. The first way is to authorize
another EOA address to sign for it through setOperator.
The other way is to implement IERC1271 for self-verification.
*/
address signer;
// positive(negative) if you want to open long(short) position
int128 paperAmount;
// negative(positive) if you want to open long(short) position
int128 creditAmount;
/*
╔═══════════════════╤═════════╗
║ info component │ type ║
╟───────────────────┼─────────╢
║ makerFeeRate │ int64 ║
║ takerFeeRate │ int64 ║
║ expiration │ uint64 ║
║ nonce │ uint64 ║
╚═══════════════════╧═════════╝
*/
bytes32 info;
}
// EIP712 component
bytes32 public constant ORDER_TYPEHASH =
keccak256("Order(address perp,address signer,int128 paperAmount,int128 creditAmount,bytes32 info)");
/// @notice risk params of a perpetual market
struct RiskParams {
/*
When users withdraw funds, their margin must be equal or
greater than the exposure * initialMarginRatio.
*/
uint256 initialMarginRatio;
/*
Liquidation will happen when
netValue < exposure * liquidationThreshold
The lower liquidationThreshold, the higher leverage.
This value is also known as "maintenance margin ratio".
1E18 based decimal.
*/
uint256 liquidationThreshold;
/*
The discount rate for the liquidation.
markPrice * (1 - liquidationPriceOff) when liquidate long position
markPrice * (1 + liquidationPriceOff) when liquidate short position
1e18 based decimal.
*/
uint256 liquidationPriceOff;
// The insurance fee rate charged from liquidation.
// 1E18 based decimal.
uint256 insuranceFeeRate;
// price source of mark price
address markPriceSource;
// perpetual market name
string name;
// if the market is activited
bool isRegistered;
}
/// @notice Match result obtained by parsing and validating tradeData.
/// Contains arrays of balance change.
struct MatchResult {
address[] traderList;
int256[] paperChangeList;
int256[] creditChangeList;
int256 orderSenderFee;
}
struct ReserveInfo {
// the initial mortgage rate of collateral
// 1e18 based decimal
uint256 initialMortgageRate;
// max total deposit collateral amount
uint256 maxTotalDepositAmount;
// max deposit collateral amount per account
uint256 maxDepositAmountPerAccount;
// the collateral max deposit value, protect from oracle
uint256 maxColBorrowPerAccount;
// oracle address
address oracle;
// total deposit amount
uint256 totalDepositAmount;
// liquidation mortgage rate
// 1e18 based decimal
uint256 liquidationMortgageRate;
/*
The discount rate for the liquidation.
price * (1 - liquidationPriceOff)
1e18 based decimal.
*/
uint256 liquidationPriceOff;
// insurance fee rate
// 1e18
uint256 insuranceFeeRate;
/*
if the mortgage collateral delisted.
if isFinalLiquidation = true which means user can not deposit collateral and borrow USDO
*/
bool isFinalLiquidation;
// if allow user deposit collateral
bool isDepositAllowed;
// if allow user borrow USDO
bool isBorrowAllowed;
}
/// @notice user param
struct UserInfo {
// deposit collateral ==> deposit amount
mapping(address => uint256) depositBalance;
mapping(address => bool) hasCollateral;
// t0 borrow USDO amount
uint256 t0BorrowBalance;
// user deposit collateral list
address[] collateralList;
}
struct LiquidateData {
uint256 actualCollateral;
uint256 insuranceFee;
uint256 actualLiquidatedT0;
uint256 actualLiquidated;
uint256 liquidatedRemainUSDC;
}
}
{
"compilationTarget": {
"src/Perpetual.sol": "Perpetual"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": [
":@openzeppelin/=lib/openzeppelin-contracts/",
":@pythnetwork/pyth-sdk-solidity/=node_modules/@pythnetwork/pyth-sdk-solidity/",
":ds-test/=lib/forge-std/lib/ds-test/src/",
":erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
":forge-std/=lib/forge-std/src/",
":gmx-synthetics/=lib/gmx-synthetics/contracts/",
":openzeppelin-contracts/=lib/openzeppelin-contracts/",
":openzeppelin/=lib/openzeppelin-contracts/contracts/",
":v3-core/=lib/v3-core/contracts/",
":v3-periphery/=lib/v3-periphery/contracts/"
]
}
[{"inputs":[{"internalType":"address","name":"_owner","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"trader","type":"address"},{"indexed":false,"internalType":"int256","name":"paperChange","type":"int256"},{"indexed":false,"internalType":"int256","name":"creditChange","type":"int256"}],"name":"BalanceChange","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"int256","name":"oldFundingRate","type":"int256"},{"indexed":false,"internalType":"int256","name":"newFundingRate","type":"int256"}],"name":"UpdateFundingRate","type":"event"},{"inputs":[{"internalType":"address","name":"trader","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"int256","name":"paper","type":"int256"},{"internalType":"int256","name":"credit","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getFundingRate","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"liquidator","type":"address"},{"internalType":"address","name":"liquidatedTrader","type":"address"},{"internalType":"int256","name":"requestPaper","type":"int256"},{"internalType":"int256","name":"expectCredit","type":"int256"}],"name":"liquidate","outputs":[{"internalType":"int256","name":"liqtorPaperChange","type":"int256"},{"internalType":"int256","name":"liqtorCreditChange","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"tradeData","type":"bytes"}],"name":"trade","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"int256","name":"newFundingRate","type":"int256"}],"name":"updateFundingRate","outputs":[],"stateMutability":"nonpayable","type":"function"}]