// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
// 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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32")
mstore(0x1c, hash)
message := keccak256(0x00, 0x3c)
}
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, "\x19\x01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
data := keccak256(ptr, 0x42)
}
}
/**
* @dev Returns an Ethereum Signed Data with intended validator, created from a
* `validator` and `data` according to the version 0 of EIP-191.
*
* See {recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x00", validator, data));
}
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./Types.sol";
library EIP712 {
function _buildDomainSeparator(
string memory name,
string memory version,
address verifyingContract
)
internal
view
returns (bytes32)
{
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
return keccak256(abi.encode(typeHash, hashedName, hashedVersion, block.chainid, verifyingContract));
}
function _hashTypedDataV4(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return ECDSA.toTypedDataHash(domainSeparator, structHash);
}
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
/// @notice Error messages
library Errors {
string constant PERP_MISMATCH = "JOJO_PERP_MISMATCH";
string constant PERP_NOT_REGISTERED = "JOJO_PERP_NOT_REGISTERED";
string constant PERP_ALREADY_REGISTERED = "JOJO_PERP_ALREADY_REGISTERED";
string constant INVALID_RISK_PARAM = "JOJO_INVALID_RISK_PARAM";
string constant INVALID_ORDER_SENDER = "JOJO_INVALID_ORDER_SENDER";
string constant INVALID_ORDER_SIGNATURE = "JOJO_INVALID_ORDER_SIGNATURE";
string constant INVALID_TRADER_NUMBER = "JOJO_AT_LEAST_TWO_TRADERS";
string constant INVALID_FUNDING_RATE_KEEPER = "JOJO_INVALID_FUNDING_RATE_KEEPER";
string constant INVALID_LIQUIDATION_EXECUTOR = "JOJO_INVALID_LIQUIDATION_EXECUTOR";
string constant ORDER_FILLED_OVERFLOW = "JOJO_ORDER_FILLED_OVERFLOW";
string constant ORDER_PRICE_NOT_MATCH = "JOJO_ORDER_PRICE_NOT_MATCH";
string constant ORDER_PRICE_NEGATIVE = "JOJO_ORDER_PRICE_NEGATIVE";
string constant ORDER_SENDER_NOT_SAFE = "JOJO_ORDER_SENDER_NOT_SAFE";
string constant ORDER_EXPIRED = "JOJO_ORDER_EXPIRED";
string constant ORDER_WRONG_SORTING = "JOJO_ORDER_WRONG_SORTING";
string constant ORDER_SELF_MATCH = "JOJO_ORDER_SELF_MATCH";
string constant ACCOUNT_NOT_SAFE = "JOJO_ACCOUNT_NOT_SAFE";
string constant ACCOUNT_IS_SAFE = "JOJO_ACCOUNT_IS_SAFE";
string constant TAKER_TRADE_AMOUNT_WRONG = "JOJO_TAKER_TRADE_AMOUNT_WRONG";
string constant TRADER_HAS_NO_POSITION = "JOJO_TRADER_HAS_NO_POSITION";
string constant WITHDRAW_PENDING = "JOJO_WITHDRAW_PENDING";
string constant WITHDRAW_INVALID = "JOJO_WITHDRAW_INVALID";
string constant FAST_WITHDRAW_NOT_ALLOWED = "JOJO_FAST_WITHDRAW_NOT_ALLOWED";
string constant LIQUIDATION_REQUEST_AMOUNT_WRONG = "JOJO_LIQUIDATION_REQUEST_AMOUNT_WRONG";
string constant SELF_LIQUIDATION_NOT_ALLOWED = "JOJO_SELF_LIQUIDATION_NOT_ALLOWED";
string constant SECONDARY_ASSET_ALREADY_EXIST = "JOJO_SECONDARY_ASSET_ALREADY_EXIST";
string constant SECONDARY_ASSET_DECIMAL_WRONG = "JOJO_SECONDARY_ASSET_DECIMAL_WRONG";
string constant ARRAY_LENGTH_NOT_SAME = "JOJO_ARRAY_LENGTH_NOT_SAME";
string constant POSITION_AMOUNT_REACH_UPPER_LIMIT = "JOJO_POSITION_AMOUNT_REACH_UPPER_LIMIT";
string constant RESERVE_NOT_ALLOW_DEPOSIT = "RESERVE_NOT_ALLOW_DEPOSIT";
string constant DEPOSIT_AMOUNT_IS_ZERO = "DEPOSIT_AMOUNT_IS_ZERO";
string constant REPAY_AMOUNT_IS_ZERO = "REPAY_AMOUNT_IS_ZERO";
string constant WITHDRAW_AMOUNT_IS_ZERO = "WITHDRAW_AMOUNT_IS_ZERO";
string constant LIQUIDATE_AMOUNT_IS_ZERO = "LIQUIDATE_AMOUNT_IS_ZERO";
string constant AFTER_BORROW_ACCOUNT_IS_NOT_SAFE = "AFTER_BORROW_ACCOUNT_IS_NOT_SAFE";
string constant AFTER_WITHDRAW_ACCOUNT_IS_NOT_SAFE = "AFTER_WITHDRAW_ACCOUNT_IS_NOT_SAFE";
string constant AFTER_FLASHLOAN_ACCOUNT_IS_NOT_SAFE = "AFTER_FLASHLOAN_ACCOUNT_IS_NOT_SAFE";
string constant EXCEED_THE_MAX_DEPOSIT_AMOUNT_PER_ACCOUNT = "EXCEED_THE_MAX_DEPOSIT_AMOUNT_PER_ACCOUNT";
string constant EXCEED_THE_MAX_DEPOSIT_AMOUNT_TOTAL = "EXCEED_THE_MAX_DEPOSIT_AMOUNT_TOTAL";
string constant EXCEED_THE_MAX_BORROW_AMOUNT_PER_ACCOUNT = "EXCEED_THE_MAX_BORROW_AMOUNT_PER_ACCOUNT";
string constant EXCEED_THE_MAX_BORROW_AMOUNT_TOTAL = "EXCEED_THE_MAX_BORROW_AMOUNT_TOTAL";
string constant WITHDRAW_AMOUNT_IS_TOO_BIG = "WITHDRAW_AMOUNT_IS_TOO_BIG";
string constant CAN_NOT_OPERATE_ACCOUNT = "CAN_NOT_OPERATE_ACCOUNT";
string constant LIQUIDATION_PRICE_PROTECTION = "LIQUIDATION_PRICE_PROTECTION";
string constant NOT_ALLOWED_TO_EXCHANGE = "NOT_ALLOWED_TO_EXCHANGE";
string constant NO_MORE_RESERVE_ALLOWED = "NO_MORE_RESERVE_ALLOWED";
string constant RESERVE_PARAM_ERROR = "RESERVE_PARAM_ERROR";
string constant REPAY_AMOUNT_NOT_ENOUGH = "REPAY_AMOUNT_NOT_ENOUGH";
string constant INSURANCE_AMOUNT_NOT_ENOUGH = "INSURANCE_AMOUNT_NOT_ENOUGH";
string constant LIQUIDATED_AMOUNT_NOT_ENOUGH = "LIQUIDATED_AMOUNT_NOT_ENOUGH";
string constant LIQUIDATOR_NOT_IN_THE_WHITELIST = "LIQUIDATOR_NOT_IN_THE_WHITELIST";
string constant RESERVE_PARAM_WRONG = "RESERVE_PARAM_WRONG";
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "../interfaces/internal/IPriceSource.sol";
import "../interfaces/IPerpetual.sol";
import "../libraries/Errors.sol";
import "../libraries/SignedDecimalMath.sol";
import "./Liquidation.sol";
import "./Operation.sol";
import "./Types.sol";
library Funding {
using SafeERC20 for IERC20;
// ========== events ==========
event Deposit(address indexed to, address indexed payer, uint256 primaryAmount, uint256 secondaryAmount);
event Withdraw(address indexed to, address indexed payer, uint256 primaryAmount, uint256 secondaryAmount);
event RequestWithdraw(
address indexed payer, uint256 primaryAmount, uint256 secondaryAmount, uint256 executionTimestamp
);
event TransferIn(address trader, uint256 primaryAmount, uint256 secondaryAmount);
event TransferOut(address trader, uint256 primaryAmount, uint256 secondaryAmount);
// ========== deposit ==========
function deposit(Types.State storage state, uint256 primaryAmount, uint256 secondaryAmount, address to) external {
if (primaryAmount > 0) {
IERC20(state.primaryAsset).safeTransferFrom(msg.sender, address(this), primaryAmount);
state.primaryCredit[to] += SafeCast.toInt256(primaryAmount);
}
if (secondaryAmount > 0) {
IERC20(state.secondaryAsset).safeTransferFrom(msg.sender, address(this), secondaryAmount);
state.secondaryCredit[to] += secondaryAmount;
}
emit Deposit(to, msg.sender, primaryAmount, secondaryAmount);
}
// ========== withdraw ==========
function isWithdrawValid(
Types.State storage state,
address spender,
address from,
uint256 primaryAmount,
uint256 secondaryAmount
)
internal
view
returns (bool)
{
if (spender != from) {
return (
state.primaryCreditAllowed[from][spender] >= primaryAmount
&& state.secondaryCreditAllowed[from][spender] >= secondaryAmount
) && (state.primaryCreditAllowed[from][spender] != 0 || state.secondaryCreditAllowed[from][spender] != 0);
}
return true;
}
function requestWithdraw(
Types.State storage state,
address from,
uint256 primaryAmount,
uint256 secondaryAmount
)
external
{
require(isWithdrawValid(state, msg.sender, from, primaryAmount, secondaryAmount), Errors.WITHDRAW_INVALID);
state.pendingPrimaryWithdraw[from] = primaryAmount;
state.pendingSecondaryWithdraw[from] = secondaryAmount;
state.withdrawExecutionTimestamp[from] = block.timestamp + state.withdrawTimeLock;
emit RequestWithdraw(from, primaryAmount, secondaryAmount, state.withdrawExecutionTimestamp[from]);
}
function executeWithdraw(
Types.State storage state,
address from,
address to,
bool isInternal,
bytes memory param
)
external
{
require(state.withdrawExecutionTimestamp[from] <= block.timestamp, Errors.WITHDRAW_PENDING);
uint256 primaryAmount = state.pendingPrimaryWithdraw[from];
uint256 secondaryAmount = state.pendingSecondaryWithdraw[from];
require(isWithdrawValid(state, msg.sender, from, primaryAmount, secondaryAmount), Errors.WITHDRAW_INVALID);
state.pendingPrimaryWithdraw[from] = 0;
state.pendingSecondaryWithdraw[from] = 0;
// No need to change withdrawExecutionTimestamp, because we set pending
// withdraw amount to 0.
_withdraw(state, msg.sender, from, to, primaryAmount, secondaryAmount, isInternal, param);
}
function fastWithdraw(
Types.State storage state,
address from,
address to,
uint256 primaryAmount,
uint256 secondaryAmount,
bool isInternal,
bytes memory param
)
external
{
require(
!state.fastWithdrawDisabled || state.fastWithdrawalWhitelist[msg.sender], Errors.FAST_WITHDRAW_NOT_ALLOWED
);
require(isWithdrawValid(state, msg.sender, from, primaryAmount, secondaryAmount), Errors.WITHDRAW_INVALID);
_withdraw(state, msg.sender, from, to, primaryAmount, secondaryAmount, isInternal, param);
}
function _withdraw(
Types.State storage state,
address spender,
address from,
address to,
uint256 primaryAmount,
uint256 secondaryAmount,
bool isInternal,
bytes memory param
)
private
{
if (spender != from) {
state.primaryCreditAllowed[from][spender] -= primaryAmount;
state.secondaryCreditAllowed[from][spender] -= secondaryAmount;
emit Operation.FundOperatorAllowedChange(
from, spender, state.primaryCreditAllowed[from][spender], state.secondaryCreditAllowed[from][spender]
);
}
if (primaryAmount > 0) {
state.primaryCredit[from] -= SafeCast.toInt256(primaryAmount);
if (isInternal) {
state.primaryCredit[to] += SafeCast.toInt256(primaryAmount);
} else {
IERC20(state.primaryAsset).safeTransfer(to, primaryAmount);
}
}
if (secondaryAmount > 0) {
state.secondaryCredit[from] -= secondaryAmount;
if (isInternal) {
state.secondaryCredit[to] += secondaryAmount;
} else {
IERC20(state.secondaryAsset).safeTransfer(to, secondaryAmount);
}
}
if (primaryAmount > 0) {
// if trader withdraw primary asset, we should check if solid safe
require(Liquidation._isSolidIMSafe(state, from), Errors.ACCOUNT_NOT_SAFE);
} else {
// if trader didn't withdraw primary asset, normal safe check is enough
require(Liquidation._isIMSafe(state, from), Errors.ACCOUNT_NOT_SAFE);
}
if (isInternal) {
emit TransferIn(to, primaryAmount, secondaryAmount);
emit TransferOut(from, primaryAmount, secondaryAmount);
} else {
emit Withdraw(to, from, primaryAmount, secondaryAmount);
}
if (param.length != 0) {
require(Address.isContract(to), "target is not a contract");
require(state.isWithdrawalWhitelist[to], "target is not in whiteList");
(bool success,) = to.call(param);
if (success == false) {
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
}
}
}
/*
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 IDecimalERC20 {
function decimals() external returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
/*
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;
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
interface IPriceSource {
/// @notice Return mark price. Revert if data not available.
/// @return price is a 1e18 based decimal.
function getMarkPrice() external view returns (uint256 price);
/// @notice Return asset price. Revert if data not available.
/// @return price is a 1e18 based decimal.
function getAssetPrice() external view returns (uint256);
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
import "./JOJOExternal.sol";
import "./JOJOOperation.sol";
import "./JOJOView.sol";
/// @notice Top entrance. For implementation of specific functions:
/// view functions -> JOJOView
/// external calls -> JOJOExternal
/// owner-only methods -> JOJOOperation
/// data structure -> JOJOStorage
contract JOJODealer is JOJOExternal, JOJOOperation, JOJOView {
constructor(address _primaryAsset) JOJOStorage() {
state.primaryAsset = _primaryAsset;
}
function version() external pure returns (string memory) {
return "JOJODealer V1.1";
}
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/interfaces/IERC1271.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./interfaces/IDealer.sol";
import "./libraries/Errors.sol";
import "./libraries/Funding.sol";
import "./libraries/Liquidation.sol";
import "./libraries/Operation.sol";
import "./libraries/Position.sol";
import "./libraries/SignedDecimalMath.sol";
import "./libraries/Trading.sol";
import "./JOJOStorage.sol";
abstract contract JOJOExternal is JOJOStorage, IDealer {
using SignedDecimalMath for int256;
using SafeERC20 for IERC20;
// ========== fund related ==========
/// @inheritdoc IDealer
function deposit(uint256 primaryAmount, uint256 secondaryAmount, address to) external nonReentrant {
Funding.deposit(state, primaryAmount, secondaryAmount, to);
}
/// @inheritdoc IDealer
function requestWithdraw(address from, uint256 primaryAmount, uint256 secondaryAmount) external nonReentrant {
Funding.requestWithdraw(state, from, primaryAmount, secondaryAmount);
}
/// @inheritdoc IDealer
function executeWithdraw(address from, address to, bool isInternal, bytes memory param) external nonReentrant {
Funding.executeWithdraw(state, from, to, isInternal, param);
}
/// @inheritdoc IDealer
function fastWithdraw(
address from,
address to,
uint256 primaryAmount,
uint256 secondaryAmount,
bool isInternal,
bytes memory param
)
external
nonReentrant
{
Funding.fastWithdraw(state, from, to, primaryAmount, secondaryAmount, isInternal, param);
}
/// @inheritdoc IDealer
function setOperator(address operator, bool isValid) external {
Operation.setOperator(state, msg.sender, operator, isValid);
}
function approveFundOperator(address operator, uint256 primaryAmount, uint256 secondaryAmount) external {
Operation.approveFundOperator(state, msg.sender, operator, primaryAmount, secondaryAmount);
}
/// @inheritdoc IDealer
function handleBadDebt(address liquidatedTrader) external {
Liquidation.handleBadDebt(state, liquidatedTrader);
}
// ========== registered perpetual only ==========
/// @inheritdoc IDealer
function requestLiquidation(
address executor,
address liquidator,
address liquidatedTrader,
int256 requestPaperAmount
)
external
onlyRegisteredPerp
returns (int256 liqtorPaperChange, int256 liqtorCreditChange, int256 liqedPaperChange, int256 liqedCreditChange)
{
return Liquidation.requestLiquidation(
state, msg.sender, executor, liquidator, liquidatedTrader, requestPaperAmount
);
}
/// @inheritdoc IDealer
function openPosition(address trader) external onlyRegisteredPerp {
Position._openPosition(state, trader);
}
/// @inheritdoc IDealer
function realizePnl(address trader, int256 pnl) external onlyRegisteredPerp {
Position._realizePnl(state, trader, pnl);
}
/// @inheritdoc IDealer
function approveTrade(
address orderSender,
bytes calldata tradeData
)
external
onlyRegisteredPerp
returns (
address[] memory, // traderList
int256[] memory, // paperChangeList
int256[] memory // creditChangeList
)
{
require(state.validOrderSender[orderSender], Errors.INVALID_ORDER_SENDER);
/*
parse tradeData
Pass in all orders and their signatures that need to be matched.
Also, pass in the amount you want to fill each order.
*/
(Types.Order[] memory orderList, bytes[] memory signatureList, uint256[] memory matchPaperAmount) =
abi.decode(tradeData, (Types.Order[], bytes[], uint256[]));
bytes32[] memory orderHashList = new bytes32[](orderList.length);
// validate all orders
for (uint256 i = 0; i < orderList.length;) {
Types.Order memory order = orderList[i];
bytes32 orderHash = EIP712._hashTypedDataV4(domainSeparator, Trading._structHash(order));
orderHashList[i] = orderHash;
// validate signature
(address recoverSigner,) = ECDSA.tryRecover(orderHash, signatureList[i]);
if (recoverSigner != order.signer && !state.operatorRegistry[order.signer][recoverSigner]) {
if (Address.isContract(order.signer)) {
require(
IERC1271(order.signer).isValidSignature(orderHash, signatureList[i]) == 0x1626ba7e,
Errors.INVALID_ORDER_SIGNATURE
);
} else {
revert(Errors.INVALID_ORDER_SIGNATURE);
}
}
// requirements
require(Trading._info2Expiration(order.info) >= block.timestamp, Errors.ORDER_EXPIRED);
require(
(order.paperAmount < 0 && order.creditAmount > 0) || (order.paperAmount > 0 && order.creditAmount < 0),
Errors.ORDER_PRICE_NEGATIVE
);
require(order.perp == msg.sender, Errors.PERP_MISMATCH);
require(i == 0 || order.signer != orderList[0].signer, Errors.ORDER_SELF_MATCH);
state.orderFilledPaperAmount[orderHash] += matchPaperAmount[i];
require(
state.orderFilledPaperAmount[orderHash] <= int256(orderList[i].paperAmount).abs(),
Errors.ORDER_FILLED_OVERFLOW
);
unchecked {
++i;
}
}
Types.MatchResult memory result = Trading._matchOrders(state, orderHashList, orderList, matchPaperAmount);
// charge fee
state.primaryCredit[orderSender] += result.orderSenderFee;
// if orderSender pay fees to traders, check if orderSender is safe
if (result.orderSenderFee < 0) {
require(Liquidation._isSolidIMSafe(state, orderSender), Errors.ORDER_SENDER_NOT_SAFE);
}
return (result.traderList, result.paperChangeList, result.creditChangeList);
}
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IDealer.sol";
import "./libraries/Errors.sol";
import "./libraries/Operation.sol";
import "./libraries/Types.sol";
import "./JOJOStorage.sol";
/// @notice Owner-only functions
abstract contract JOJOOperation is JOJOStorage, IDealer {
using SafeERC20 for IERC20;
// ========== params updates ==========
/// @inheritdoc IDealer
function updateFundingRate(
address[] calldata perpList,
int256[] calldata rateList
)
external
onlyFundingRateKeeper
{
Operation.updateFundingRate(perpList, rateList);
}
/// @notice Set risk parameters for a perpetual market.
/// @param param market will be ready to trade if param.isRegistered value is true.
/// This market will not be opened if param.isRegistered value is false.
function setPerpRiskParams(address perp, Types.RiskParams calldata param) external onlyOwner {
Operation.setPerpRiskParams(state, perp, param);
}
function setFundingRateKeeper(address newKeeper) external onlyOwner {
Operation.setFundingRateKeeper(state, newKeeper);
}
function setInsurance(address newInsurance) external onlyOwner {
Operation.setInsurance(state, newInsurance);
}
function setMaxPositionAmount(uint256 newMaxPositionAmount) external onlyOwner {
Operation.setMaxPositionAmount(state, newMaxPositionAmount);
}
function setWithdrawTimeLock(uint256 newWithdrawTimeLock) external onlyOwner {
Operation.setWithdrawTimeLock(state, newWithdrawTimeLock);
}
function setOrderSender(address orderSender, bool isValid) external onlyOwner {
Operation.setOrderSender(state, orderSender, isValid);
}
function setFastWithdrawalWhitelist(address target, bool isValid) external onlyOwner {
Operation.setFastWithdrawalWhitelist(state, target, isValid);
}
function setWithdrawlWhitelist(address target, bool isValid) external onlyOwner {
Operation.setWithdrawalWhitelist(state, target, isValid);
}
function disableFastWithdraw(bool disabled) external onlyOwner {
Operation.disableFastWithdraw(state, disabled);
}
/// @notice Secondary asset can only be set once.
/// Secondary asset must have the same decimal with primary asset.
function setSecondaryAsset(address _secondaryAsset) external onlyOwner {
Operation.setSecondaryAsset(state, _secondaryAsset);
}
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./libraries/EIP712.sol";
import "./libraries/Errors.sol";
import "./libraries/Types.sol";
/// @notice All storage variables of JOJODealer
abstract contract JOJOStorage is Ownable, ReentrancyGuard {
Types.State public state;
bytes32 public immutable domainSeparator;
constructor() Ownable() {
domainSeparator = EIP712._buildDomainSeparator("JOJO", "1", address(this));
}
modifier onlyFundingRateKeeper() {
require(msg.sender == state.fundingRateKeeper, Errors.INVALID_FUNDING_RATE_KEEPER);
_;
}
modifier onlyRegisteredPerp() {
require(state.perpRiskParams[msg.sender].isRegistered, Errors.PERP_NOT_REGISTERED);
_;
}
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "./interfaces/IDealer.sol";
import "./libraries/Errors.sol";
import "./libraries/Liquidation.sol";
import "./libraries/Trading.sol";
import "./JOJOStorage.sol";
abstract contract JOJOView is JOJOStorage, IDealer {
// ========== simple read state ==========
/// @inheritdoc IDealer
function getRiskParams(address perp) external view returns (Types.RiskParams memory params) {
params = state.perpRiskParams[perp];
}
/// @inheritdoc IDealer
function getAllRegisteredPerps() external view returns (address[] memory) {
return state.registeredPerp;
}
/// @inheritdoc IDealer
function getMarkPrice(address perp) external view returns (uint256) {
return Liquidation.getMarkPrice(state, perp);
}
/// @inheritdoc IDealer
function getPositions(address trader) external view returns (address[] memory) {
return state.openPositions[trader];
}
/// @inheritdoc IDealer
function getCreditOf(address trader)
external
view
returns (
int256 primaryCredit,
uint256 secondaryCredit,
uint256 pendingPrimaryWithdraw,
uint256 pendingSecondaryWithdraw,
uint256 executionTimestamp
)
{
primaryCredit = state.primaryCredit[trader];
secondaryCredit = state.secondaryCredit[trader];
pendingPrimaryWithdraw = state.pendingPrimaryWithdraw[trader];
pendingSecondaryWithdraw = state.pendingSecondaryWithdraw[trader];
executionTimestamp = state.withdrawExecutionTimestamp[trader];
}
/// @inheritdoc IDealer
function isOrderSenderValid(address orderSender) external view returns (bool) {
return state.validOrderSender[orderSender];
}
/// @inheritdoc IDealer
function isFastWithdrawalValid(address fastWithdrawOperator) external view returns (bool) {
return state.fastWithdrawalWhitelist[fastWithdrawOperator];
}
/// @inheritdoc IDealer
function isCreditAllowed(
address from,
address spender
)
external
view
returns (uint256 primaryCreditAllowed, uint256 secondaryCreditAllowed)
{
return (state.primaryCreditAllowed[from][spender], state.secondaryCreditAllowed[from][spender]);
}
/// @inheritdoc IDealer
function isOperatorValid(address client, address operator) external view returns (bool) {
return state.operatorRegistry[client][operator];
}
// ========== liquidation related ==========
/// @inheritdoc IDealer
function isSafe(address trader) external view returns (bool safe) {
return Liquidation._isMMSafe(state, trader);
}
function isIMSafe(address trader) external view returns (bool safe) {
return Liquidation._isIMSafe(state, trader);
}
/// @inheritdoc IDealer
function isAllSafe(address[] calldata traderList) external view returns (bool safe) {
return Liquidation._isAllMMSafe(state, traderList);
}
/// @inheritdoc IDealer
function getFundingRate(address perp) external view returns (int256) {
return IPerpetual(perp).getFundingRate();
}
/// @inheritdoc IDealer
function getTraderRisk(address trader)
external
view
returns (int256 netValue, uint256 exposure, uint256 initialMargin, uint256 maintenanceMargin)
{
(netValue, exposure, initialMargin, maintenanceMargin) = Liquidation.getTotalExposure(state, trader);
}
/// @inheritdoc IDealer
function getLiquidationPrice(address trader, address perp) external view returns (uint256 liquidationPrice) {
return Liquidation.getLiquidationPrice(state, trader, perp);
}
/// @inheritdoc IDealer
function getLiquidationCost(
address perp,
address liquidatedTrader,
int256 requestPaperAmount
)
external
view
returns (int256 liqtorPaperChange, int256 liqtorCreditChange)
{
(liqtorPaperChange, liqtorCreditChange,) =
Liquidation.getLiquidateCreditAmount(state, perp, liquidatedTrader, requestPaperAmount);
}
// ========== order related ==========
/// @inheritdoc IDealer
function getOrderFilledAmount(bytes32 orderHash) external view returns (uint256 filledAmount) {
filledAmount = state.orderFilledPaperAmount[orderHash];
}
// ========== encode data helper ==========
function getSetOperatorCallData(address operator, bool isValid) external pure returns (bytes memory) {
return abi.encodeWithSignature("setOperator(address,bool)", operator, isValid);
}
function getRequestWithdrawCallData(
address from,
uint256 primaryAmount,
uint256 secondaryAmount
)
external
pure
returns (bytes memory)
{
return abi.encodeWithSignature("requestWithdraw(address,uint256,uint256)", from, primaryAmount, secondaryAmount);
}
function getExecuteWithdrawCallData(
address from,
address to,
bool isInternal,
bytes memory param
)
external
pure
returns (bytes memory)
{
return abi.encodeWithSignature("executeWithdraw(address,address,bool,bytes)", from, to, isInternal, param);
}
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "../interfaces/internal/IPriceSource.sol";
import "../interfaces/IPerpetual.sol";
import "../libraries/SignedDecimalMath.sol";
import "../libraries/Errors.sol";
import "./Types.sol";
import "./Position.sol";
library Liquidation {
using SignedDecimalMath for int256;
// ========== events ==========
event BeingLiquidated(
address indexed perp,
address indexed liquidatedTrader,
int256 paperChange,
int256 creditChange,
uint256 positionSerialNum
);
event JoinLiquidation(
address indexed perp,
address indexed liquidator,
address indexed liquidatedTrader,
int256 paperChange,
int256 creditChange,
uint256 positionSerialNum
);
// emit when charge insurance fee from liquidated trader
event ChargeInsurance(address indexed perp, address indexed liquidatedTrader, uint256 fee);
event HandleBadDebt(address indexed liquidatedTrader, int256 primaryCredit, uint256 secondaryCredit);
// ========== trader safety check ==========
function getTotalExposure(
Types.State storage state,
address trader
)
public
view
returns (int256 netValue, uint256 exposure, uint256 initialMargin, uint256 maintenanceMargin)
{
int256 netPositionValue;
// sum net value and exposure among all markets
for (uint256 i = 0; i < state.openPositions[trader].length;) {
(int256 paperAmount, int256 creditAmount) = IPerpetual(state.openPositions[trader][i]).balanceOf(trader);
Types.RiskParams storage params = state.perpRiskParams[state.openPositions[trader][i]];
int256 price = SafeCast.toInt256(IPriceSource(params.markPriceSource).getMarkPrice());
netPositionValue += paperAmount.decimalMul(price) + creditAmount;
uint256 exposureIncrement = paperAmount.decimalMul(price).abs();
exposure += exposureIncrement;
maintenanceMargin += (exposureIncrement * params.liquidationThreshold) / Types.ONE;
initialMargin += (exposureIncrement * params.initialMarginRatio) / Types.ONE;
unchecked {
++i;
}
}
netValue = netPositionValue + state.primaryCredit[trader] + SafeCast.toInt256(state.secondaryCredit[trader]);
}
function _isMMSafe(Types.State storage state, address trader) internal view returns (bool) {
(int256 netValue,,, uint256 maintenanceMargin) = getTotalExposure(state, trader);
return netValue >= SafeCast.toInt256(maintenanceMargin);
}
function _isIMSafe(Types.State storage state, address trader) internal view returns (bool) {
(int256 netValue,, uint256 initialMargin,) = getTotalExposure(state, trader);
return netValue >= SafeCast.toInt256(initialMargin);
}
/// @notice More strict than _isIMSafe.
/// Additional requirement: netPositionValue + primaryCredit >= 0
/// used when traders transfer out primary credit.
function _isSolidIMSafe(Types.State storage state, address trader) internal view returns (bool) {
(int256 netValue,, uint256 initialMargin,) = getTotalExposure(state, trader);
return netValue - SafeCast.toInt256(state.secondaryCredit[trader]) >= 0
&& netValue >= SafeCast.toInt256(initialMargin);
}
function _isAllMMSafe(Types.State storage state, address[] calldata traderList) internal view returns (bool) {
for (uint256 i = 0; i < traderList.length;) {
address trader = traderList[i];
if (!_isMMSafe(state, trader)) {
return false;
}
unchecked {
++i;
}
}
return true;
}
/// @return liquidationPrice It should be considered as the position can never be
/// liquidated (absolutely safe) or being liquidated at the present if return 0.
function getLiquidationPrice(
Types.State storage state,
address trader,
address perp
)
external
view
returns (uint256 liquidationPrice)
{
/*
To avoid liquidation, we need:
netValue >= maintenanceMargin
We first calculate the maintenanceMargin for all other markets' positions.
Let's call it maintenanceMargin'
Then we have netValue of the account.
Let's call it netValue'
So we have:
netValue' + paperAmount * price + creditAmount >=
maintenanceMargin' + abs(paperAmount) * price * liquidationThreshold
if paperAmount > 0
paperAmount * price * (1-liquidationThreshold) >= maintenanceMargin' - netValue' - creditAmount
price >= (maintenanceMargin' - netValue' - creditAmount)/paperAmount/(1-liquidationThreshold)
liqPrice = (maintenanceMargin' - netValue' - creditAmount)/paperAmount/(1-liquidationThreshold)
if paperAmount < 0
paperAmount * price * (1+liquidationThreshold) >= maintenanceMargin' - netValue' - creditAmount
price <= (maintenanceMargin' - netValue' - creditAmount)/paperAmount/(1+liquidationThreshold)
liqPrice = (maintenanceMargin' - netValue' - creditAmount)/paperAmount/(1+liquidationThreshold)
Let's call 1±liquidationThreshold "multiplier"
Then:
liqPrice = (maintenanceMargin' - netValue' - creditAmount)/paperAmount/multiplier
If liqPrice<0, it should be considered as the position can never be
liquidated (absolutely safe) or being liquidated at the present if return 0.
*/
int256 maintenanceMarginPrime;
int256 netValuePrime = state.primaryCredit[trader] + SafeCast.toInt256(state.secondaryCredit[trader]);
for (uint256 i = 0; i < state.openPositions[trader].length;) {
address p = state.openPositions[trader][i];
if (perp != p) {
(int256 paperAmountPrime, int256 creditAmountPrime) = IPerpetual(p).balanceOf(trader);
Types.RiskParams storage params = state.perpRiskParams[p];
int256 price = SafeCast.toInt256(IPriceSource(params.markPriceSource).getMarkPrice());
netValuePrime += paperAmountPrime.decimalMul(price) + creditAmountPrime;
maintenanceMarginPrime += SafeCast.toInt256(
(paperAmountPrime.decimalMul(price).abs() * params.liquidationThreshold) / Types.ONE
);
}
unchecked {
++i;
}
}
(int256 paperAmount, int256 creditAmount) = IPerpetual(perp).balanceOf(trader);
if (paperAmount == 0) {
return 0;
}
int256 multiplier = paperAmount > 0
? SafeCast.toInt256(Types.ONE - state.perpRiskParams[perp].liquidationThreshold)
: SafeCast.toInt256(Types.ONE + state.perpRiskParams[perp].liquidationThreshold);
int256 liqPrice =
(maintenanceMarginPrime - netValuePrime - creditAmount).decimalDiv(paperAmount).decimalDiv(multiplier);
return liqPrice < 0 ? 0 : uint256(liqPrice);
}
/// @notice Using a fixed discount price model.
/// Charge fee from liquidated trader.
/// Will limit you liquidation request to the position size.
function getLiquidateCreditAmount(
Types.State storage state,
address perp,
address liquidatedTrader,
int256 requestPaperAmount
)
public
view
returns (int256 liqtorPaperChange, int256 liqtorCreditChange, uint256 insuranceFee)
{
// can not liquidate a safe trader
require(!_isMMSafe(state, liquidatedTrader), Errors.ACCOUNT_IS_SAFE);
// calculate and limit the paper change to the position size
(int256 brokenPaperAmount,) = IPerpetual(perp).balanceOf(liquidatedTrader);
require(brokenPaperAmount != 0, Errors.TRADER_HAS_NO_POSITION);
require(requestPaperAmount * brokenPaperAmount > 0, Errors.LIQUIDATION_REQUEST_AMOUNT_WRONG);
liqtorPaperChange = requestPaperAmount.abs() > brokenPaperAmount.abs() ? brokenPaperAmount : requestPaperAmount;
// get price
Types.RiskParams storage params = state.perpRiskParams[perp];
uint256 price = IPriceSource(params.markPriceSource).getMarkPrice();
uint256 priceOffset = (price * params.liquidationPriceOff) / Types.ONE;
price = liqtorPaperChange > 0 ? price - priceOffset : price + priceOffset;
// calculate credit change
liqtorCreditChange = -1 * liqtorPaperChange.decimalMul(SafeCast.toInt256(price));
insuranceFee = (liqtorCreditChange.abs() * params.insuranceFeeRate) / Types.ONE;
}
/// @notice execute a liquidation request
function requestLiquidation(
Types.State storage state,
address perp,
address executor,
address liquidator,
address liquidatedTrader,
int256 requestPaperAmount
)
external
returns (int256 liqtorPaperChange, int256 liqtorCreditChange, int256 liqedPaperChange, int256 liqedCreditChange)
{
require(
executor == liquidator || state.operatorRegistry[liquidator][executor], Errors.INVALID_LIQUIDATION_EXECUTOR
);
require(liquidatedTrader != liquidator, Errors.SELF_LIQUIDATION_NOT_ALLOWED);
uint256 insuranceFee;
(liqtorPaperChange, liqtorCreditChange, insuranceFee) =
getLiquidateCreditAmount(state, perp, liquidatedTrader, requestPaperAmount);
state.primaryCredit[state.insurance] += SafeCast.toInt256(insuranceFee);
// liquidated trader balance change
liqedCreditChange = liqtorCreditChange * -1 - SafeCast.toInt256(insuranceFee);
liqedPaperChange = liqtorPaperChange * -1;
// events
uint256 ltSN = state.positionSerialNum[liquidatedTrader][perp];
uint256 liquidatorSN = state.positionSerialNum[liquidator][perp];
emit BeingLiquidated(perp, liquidatedTrader, liqedPaperChange, liqedCreditChange, ltSN);
emit JoinLiquidation(perp, liquidator, liquidatedTrader, liqtorPaperChange, liqtorCreditChange, liquidatorSN);
emit ChargeInsurance(perp, liquidatedTrader, insuranceFee);
}
function getMarkPrice(Types.State storage state, address perp) external view returns (uint256 price) {
price = IPriceSource(state.perpRiskParams[perp].markPriceSource).getMarkPrice();
}
function handleBadDebt(Types.State storage state, address liquidatedTrader) external {
if (state.openPositions[liquidatedTrader].length == 0 && !Liquidation._isMMSafe(state, liquidatedTrader)) {
int256 primaryCredit = state.primaryCredit[liquidatedTrader];
uint256 secondaryCredit = state.secondaryCredit[liquidatedTrader];
state.primaryCredit[liquidatedTrader] = 0;
state.secondaryCredit[liquidatedTrader] = 0;
state.primaryCredit[state.insurance] += primaryCredit;
state.secondaryCredit[state.insurance] += secondaryCredit;
emit HandleBadDebt(liquidatedTrader, primaryCredit, secondaryCredit);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
import "../interfaces/IPerpetual.sol";
import "../interfaces/internal/IDecimalERC20.sol";
import "../libraries/Errors.sol";
import "./Types.sol";
library Operation {
// ========== events ==========
event SetFundingRateKeeper(address oldKeeper, address newKeeper);
event SetInsurance(address oldInsurance, address newInsurance);
event SetMaxPositionAmount(uint256 oldMaxPositionAmount, uint256 newMaxPositionAmount);
event SetWithdrawTimeLock(uint256 oldWithdrawTimeLock, uint256 newWithdrawTimeLock);
event SetOrderSender(address orderSender, bool isValid);
event SetFastWithdrawalWhitelist(address target, bool isValid);
event SetWithdrawalWhitelist(address target, bool isValid);
event FastWithdrawDisabled(bool disabled);
event SetOperator(address indexed client, address indexed operator, bool isValid);
event FundOperatorAllowedChange(
address indexed client, address indexed operator, uint256 primaryAllowed, uint256 secondaryAllowed
);
event SetSecondaryAsset(address secondaryAsset);
event UpdatePerpRiskParams(address indexed perp, Types.RiskParams param);
event UpdateFundingRate(address indexed perp, int256 oldRate, int256 newRate);
// ========== functions ==========
function setPerpRiskParams(Types.State storage state, address perp, Types.RiskParams calldata param) external {
if (state.perpRiskParams[perp].isRegistered && !param.isRegistered) {
// remove perp
for (uint256 i; i < state.registeredPerp.length;) {
if (state.registeredPerp[i] == perp) {
state.registeredPerp[i] = state.registeredPerp[state.registeredPerp.length - 1];
state.registeredPerp.pop();
}
unchecked {
++i;
}
}
}
if (!state.perpRiskParams[perp].isRegistered && param.isRegistered) {
// new perp
state.registeredPerp.push(perp);
}
require(
param.liquidationPriceOff + param.insuranceFeeRate <= param.liquidationThreshold, Errors.INVALID_RISK_PARAM
);
state.perpRiskParams[perp] = param;
emit UpdatePerpRiskParams(perp, param);
}
function updateFundingRate(address[] calldata perpList, int256[] calldata rateList) external {
require(perpList.length == rateList.length, Errors.ARRAY_LENGTH_NOT_SAME);
for (uint256 i = 0; i < perpList.length;) {
int256 oldRate = IPerpetual(perpList[i]).getFundingRate();
IPerpetual(perpList[i]).updateFundingRate(rateList[i]);
emit UpdateFundingRate(perpList[i], oldRate, rateList[i]);
unchecked {
++i;
}
}
}
function setFundingRateKeeper(Types.State storage state, address newKeeper) external {
address oldKeeper = state.fundingRateKeeper;
state.fundingRateKeeper = newKeeper;
emit SetFundingRateKeeper(oldKeeper, newKeeper);
}
function setInsurance(Types.State storage state, address newInsurance) external {
address oldInsurance = state.insurance;
state.insurance = newInsurance;
emit SetInsurance(oldInsurance, newInsurance);
}
function setMaxPositionAmount(Types.State storage state, uint256 newMaxPositionAmount) external {
uint256 oldMaxPositionAmount = state.maxPositionAmount;
state.maxPositionAmount = newMaxPositionAmount;
emit SetMaxPositionAmount(oldMaxPositionAmount, newMaxPositionAmount);
}
function setWithdrawTimeLock(Types.State storage state, uint256 newWithdrawTimeLock) external {
uint256 oldWithdrawTimeLock = state.withdrawTimeLock;
state.withdrawTimeLock = newWithdrawTimeLock;
emit SetWithdrawTimeLock(oldWithdrawTimeLock, newWithdrawTimeLock);
}
function setOrderSender(Types.State storage state, address orderSender, bool isValid) external {
state.validOrderSender[orderSender] = isValid;
emit SetOrderSender(orderSender, isValid);
}
function setFastWithdrawalWhitelist(Types.State storage state, address target, bool isValid) external {
state.fastWithdrawalWhitelist[target] = isValid;
emit SetFastWithdrawalWhitelist(target, isValid);
}
function disableFastWithdraw(Types.State storage state, bool disabled) external {
state.fastWithdrawDisabled = disabled;
emit FastWithdrawDisabled(disabled);
}
function setWithdrawalWhitelist(Types.State storage state, address target, bool isValid) external {
state.isWithdrawalWhitelist[target] = isValid;
emit SetFastWithdrawalWhitelist(target, isValid);
}
function setOperator(Types.State storage state, address client, address operator, bool isValid) external {
state.operatorRegistry[client][operator] = isValid;
emit SetOperator(client, operator, isValid);
}
function approveFundOperator(
Types.State storage state,
address client,
address operator,
uint256 primaryAmount,
uint256 secondaryAmount
)
external
{
state.primaryCreditAllowed[client][operator] = primaryAmount;
state.secondaryCreditAllowed[client][operator] = secondaryAmount;
emit FundOperatorAllowedChange(client, operator, primaryAmount, secondaryAmount);
}
function setSecondaryAsset(Types.State storage state, address _secondaryAsset) external {
require(state.secondaryAsset == address(0), Errors.SECONDARY_ASSET_ALREADY_EXIST);
require(
IDecimalERC20(_secondaryAsset).decimals() == IDecimalERC20(state.primaryAsset).decimals(),
Errors.SECONDARY_ASSET_DECIMAL_WRONG
);
state.secondaryAsset = _secondaryAsset;
emit SetSecondaryAsset(_secondaryAsset);
}
}
// 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 "../libraries/Errors.sol";
import "./Types.sol";
library Position {
// ========== position register ==========
/// @notice add position when trade or liquidation happen
/// msg.sender is the perpetual contract
function _openPosition(Types.State storage state, address trader) internal {
require(state.openPositions[trader].length < state.maxPositionAmount, Errors.POSITION_AMOUNT_REACH_UPPER_LIMIT);
state.openPositions[trader].push(msg.sender);
}
/// @notice realize pnl and remove position from the registry
/// msg.sender is the perpetual contract
function _realizePnl(Types.State storage state, address trader, int256 pnl) internal {
state.primaryCredit[trader] += pnl;
state.positionSerialNum[trader][msg.sender] += 1;
address[] storage positionList = state.openPositions[trader];
for (uint256 i = 0; i < positionList.length;) {
if (positionList[i] == msg.sender) {
positionList[i] = positionList[positionList.length - 1];
positionList.pop();
break;
}
unchecked {
++i;
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
}
// 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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
/*
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;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
/*
Copyright 2022 JOJO Exchange
SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "../interfaces/IPerpetual.sol";
import "../interfaces/internal/IPriceSource.sol";
import "../libraries/SignedDecimalMath.sol";
import "../libraries/Errors.sol";
import "./EIP712.sol";
import "./Types.sol";
import "./Liquidation.sol";
import "./Position.sol";
library Trading {
using SignedDecimalMath for int256;
using Math for uint256;
// ========== events ==========
/*
orderFilledPaperAmount>0 and filledCreditAmount<0 if the order open long,
and vice versa.
filledCreditAmount including fees.
*/
event OrderFilled(
bytes32 indexed orderHash,
address indexed trader,
address indexed perp,
int256 orderFilledPaperAmount,
int256 filledCreditAmount,
uint256 positionSerialNum,
int256 fee
);
// ========== matching[important] ==========
/// @notice calculate balance changes
/// @dev Every matching contains 1 taker order and
/// at least 1 maker order.
/// orderList[0] is taker order and all others are maker orders.
/// Maker orders should be sorted by signer addresses in ascending.
/// So that the function could merge orders to save gas.
function _matchOrders(
Types.State storage state,
bytes32[] memory orderHashList,
Types.Order[] memory orderList,
uint256[] memory matchPaperAmount
)
internal
returns (Types.MatchResult memory result)
{
// check basic match paper amount and filter unique traders
{
require(orderList.length >= 2, Errors.INVALID_TRADER_NUMBER);
// de-duplicated maker
uint256 uniqueTraderNum = 2;
uint256 totalMakerFilledPaper = matchPaperAmount[1];
// start from the second maker, which is the third trader
for (uint256 i = 2; i < orderList.length;) {
totalMakerFilledPaper += matchPaperAmount[i];
if (orderList[i].signer > orderList[i - 1].signer) {
uniqueTraderNum = uniqueTraderNum + 1;
} else {
require(orderList[i].signer == orderList[i - 1].signer, Errors.ORDER_WRONG_SORTING);
}
unchecked {
++i;
}
}
// taker match amount must equals summary of makers' match amount
require(matchPaperAmount[0] == totalMakerFilledPaper, Errors.TAKER_TRADE_AMOUNT_WRONG);
// result.traderList[0] is taker
// result.traderList[1:] are makers
result.traderList = new address[](uniqueTraderNum);
result.traderList[0] = orderList[0].signer;
}
// calculating balance change
result.paperChangeList = new int256[](result.traderList.length);
result.creditChangeList = new int256[](result.traderList.length);
{
// the taker's trader index is 0
// the first maker's trader index is 1
uint256 currentTraderIndex = 1;
result.traderList[1] = orderList[1].signer;
for (uint256 i = 1; i < orderList.length;) {
_priceMatchCheck(orderList[0], orderList[i]);
// new maker, currentTraderIndex +1
if (i >= 2 && orderList[i].signer != orderList[i - 1].signer) {
currentTraderIndex = currentTraderIndex + 1;
result.traderList[currentTraderIndex] = orderList[i].signer;
}
// calculate matching result, use maker's price
int256 paperChange = orderList[i].paperAmount > 0
? SafeCast.toInt256(matchPaperAmount[i])
: -1 * SafeCast.toInt256(matchPaperAmount[i]);
int256 creditChange = (paperChange * orderList[i].creditAmount) / orderList[i].paperAmount;
int256 fee = SafeCast.toInt256(creditChange.abs()).decimalMul(_info2MakerFeeRate(orderList[i].info));
// serialNum is used for frontend level PNL calculation
uint256 serialNum = state.positionSerialNum[orderList[i].signer][msg.sender];
emit OrderFilled(
orderHashList[i], orderList[i].signer, msg.sender, paperChange, creditChange - fee, serialNum, fee
);
// store matching result, including fees
result.paperChangeList[currentTraderIndex] += paperChange;
result.creditChangeList[currentTraderIndex] += creditChange - fee;
result.paperChangeList[0] -= paperChange;
result.creditChangeList[0] -= creditChange;
result.orderSenderFee += fee;
unchecked {
++i;
}
}
}
// fee calculation
{
// calculate takerFee based on taker's credit matching amount
int256 takerFee =
SafeCast.toInt256(result.creditChangeList[0].abs()).decimalMul(_info2TakerFeeRate(orderList[0].info));
result.creditChangeList[0] -= takerFee;
result.orderSenderFee += takerFee;
emit OrderFilled(
orderHashList[0],
orderList[0].signer,
msg.sender,
result.paperChangeList[0],
result.creditChangeList[0],
state.positionSerialNum[orderList[0].signer][msg.sender],
takerFee
);
}
}
// ========== order check ==========
function _priceMatchCheck(Types.Order memory takerOrder, Types.Order memory makerOrder) private pure {
/*
Requirements:
takercredit * abs(makerpaper) / abs(takerpaper) + makercredit <= 0
makercredit - takercredit * makerpaper / takerpaper <= 0
if takerPaper > 0
makercredit * takerpaper <= takercredit * makerpaper
if takerPaper < 0
makercredit * takerpaper >= takercredit * makerpaper
*/
// let temp1 = makercredit * takerpaper
// let temp2 = takercredit * makerpaper
int256 temp1 = int256(makerOrder.creditAmount) * int256(takerOrder.paperAmount);
int256 temp2 = int256(takerOrder.creditAmount) * int256(makerOrder.paperAmount);
if (takerOrder.paperAmount > 0) {
// maker order should be in the opposite direction of taker order
require(makerOrder.paperAmount < 0, Errors.ORDER_PRICE_NOT_MATCH);
require(temp1 <= temp2, Errors.ORDER_PRICE_NOT_MATCH);
} else {
// maker order should be in the opposite direction of taker order
require(makerOrder.paperAmount > 0, Errors.ORDER_PRICE_NOT_MATCH);
require(temp1 >= temp2, Errors.ORDER_PRICE_NOT_MATCH);
}
}
// ========== EIP712 struct hash ==========
function _structHash(Types.Order memory order) internal pure returns (bytes32 structHash) {
/*
To save gas, we use assembly to implement the function:
keccak256(
abi.encode(
Types.ORDER_TYPEHASH,
order.perp,
order.signer,
order.paperAmount,
order.creditAmount,
order.info
)
)
This is equivalent to:
Insert ORDER_TYPEHASH before order's memory head. And then
hash the whole memory section.
Finally, restore the memory slot occupied by ORDER_TYPEHASH.
*/
bytes32 orderTypeHash = Types.ORDER_TYPEHASH;
assembly {
let start := sub(order, 32)
let tmp := mload(start)
// 192 = (1 + 5) * 32
// [0...32) bytes: EIP712_ORDER_TYPE
// [32...192) bytes: order
mstore(start, orderTypeHash)
structHash := keccak256(start, 192)
mstore(start, tmp)
}
}
// ========== parse fee rates from info ==========
function _info2MakerFeeRate(bytes32 info) internal pure returns (int256) {
bytes8 value = bytes8(info >> 192);
int64 makerFee;
assembly {
makerFee := value
}
return int256(makerFee);
}
function _info2TakerFeeRate(bytes32 info) internal pure returns (int256 takerFeeRate) {
bytes8 value = bytes8(info >> 128);
int64 takerFee;
assembly {
takerFee := value
}
return int256(takerFee);
}
function _info2Expiration(bytes32 info) internal pure returns (uint256) {
bytes8 value = bytes8(info >> 64);
uint64 expiration;
assembly {
expiration := value
}
return uint256(expiration);
}
}
/*
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/JOJODealer.sol": "JOJODealer"
},
"evmVersion": "paris",
"libraries": {
"src/libraries/Funding.sol:Funding": "0x37dbfb6d42c98063f7ef46e742b59cae0b7ae6fb",
"src/libraries/Liquidation.sol:Liquidation": "0x35a2bc818443a88f28042b1f53382fafa5927a06",
"src/libraries/Operation.sol:Operation": "0x4b25bcafe43de19fd0637bfe27054ebde02d449f"
},
"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":"_primaryAsset","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"uint256","name":"primaryAmount","type":"uint256"},{"internalType":"uint256","name":"secondaryAmount","type":"uint256"}],"name":"approveFundOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"orderSender","type":"address"},{"internalType":"bytes","name":"tradeData","type":"bytes"}],"name":"approveTrade","outputs":[{"internalType":"address[]","name":"","type":"address[]"},{"internalType":"int256[]","name":"","type":"int256[]"},{"internalType":"int256[]","name":"","type":"int256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"primaryAmount","type":"uint256"},{"internalType":"uint256","name":"secondaryAmount","type":"uint256"},{"internalType":"address","name":"to","type":"address"}],"name":"deposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"disabled","type":"bool"}],"name":"disableFastWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"domainSeparator","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bool","name":"isInternal","type":"bool"},{"internalType":"bytes","name":"param","type":"bytes"}],"name":"executeWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"primaryAmount","type":"uint256"},{"internalType":"uint256","name":"secondaryAmount","type":"uint256"},{"internalType":"bool","name":"isInternal","type":"bool"},{"internalType":"bytes","name":"param","type":"bytes"}],"name":"fastWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getAllRegisteredPerps","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"trader","type":"address"}],"name":"getCreditOf","outputs":[{"internalType":"int256","name":"primaryCredit","type":"int256"},{"internalType":"uint256","name":"secondaryCredit","type":"uint256"},{"internalType":"uint256","name":"pendingPrimaryWithdraw","type":"uint256"},{"internalType":"uint256","name":"pendingSecondaryWithdraw","type":"uint256"},{"internalType":"uint256","name":"executionTimestamp","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bool","name":"isInternal","type":"bool"},{"internalType":"bytes","name":"param","type":"bytes"}],"name":"getExecuteWithdrawCallData","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"perp","type":"address"}],"name":"getFundingRate","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"perp","type":"address"},{"internalType":"address","name":"liquidatedTrader","type":"address"},{"internalType":"int256","name":"requestPaperAmount","type":"int256"}],"name":"getLiquidationCost","outputs":[{"internalType":"int256","name":"liqtorPaperChange","type":"int256"},{"internalType":"int256","name":"liqtorCreditChange","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"trader","type":"address"},{"internalType":"address","name":"perp","type":"address"}],"name":"getLiquidationPrice","outputs":[{"internalType":"uint256","name":"liquidationPrice","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"perp","type":"address"}],"name":"getMarkPrice","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"orderHash","type":"bytes32"}],"name":"getOrderFilledAmount","outputs":[{"internalType":"uint256","name":"filledAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"trader","type":"address"}],"name":"getPositions","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256","name":"primaryAmount","type":"uint256"},{"internalType":"uint256","name":"secondaryAmount","type":"uint256"}],"name":"getRequestWithdrawCallData","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"perp","type":"address"}],"name":"getRiskParams","outputs":[{"components":[{"internalType":"uint256","name":"initialMarginRatio","type":"uint256"},{"internalType":"uint256","name":"liquidationThreshold","type":"uint256"},{"internalType":"uint256","name":"liquidationPriceOff","type":"uint256"},{"internalType":"uint256","name":"insuranceFeeRate","type":"uint256"},{"internalType":"address","name":"markPriceSource","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"bool","name":"isRegistered","type":"bool"}],"internalType":"struct Types.RiskParams","name":"params","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"isValid","type":"bool"}],"name":"getSetOperatorCallData","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"trader","type":"address"}],"name":"getTraderRisk","outputs":[{"internalType":"int256","name":"netValue","type":"int256"},{"internalType":"uint256","name":"exposure","type":"uint256"},{"internalType":"uint256","name":"initialMargin","type":"uint256"},{"internalType":"uint256","name":"maintenanceMargin","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"liquidatedTrader","type":"address"}],"name":"handleBadDebt","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"traderList","type":"address[]"}],"name":"isAllSafe","outputs":[{"internalType":"bool","name":"safe","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"isCreditAllowed","outputs":[{"internalType":"uint256","name":"primaryCreditAllowed","type":"uint256"},{"internalType":"uint256","name":"secondaryCreditAllowed","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"fastWithdrawOperator","type":"address"}],"name":"isFastWithdrawalValid","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"trader","type":"address"}],"name":"isIMSafe","outputs":[{"internalType":"bool","name":"safe","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"client","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isOperatorValid","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"orderSender","type":"address"}],"name":"isOrderSenderValid","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"trader","type":"address"}],"name":"isSafe","outputs":[{"internalType":"bool","name":"safe","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"trader","type":"address"}],"name":"openPosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"trader","type":"address"},{"internalType":"int256","name":"pnl","type":"int256"}],"name":"realizePnl","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"executor","type":"address"},{"internalType":"address","name":"liquidator","type":"address"},{"internalType":"address","name":"liquidatedTrader","type":"address"},{"internalType":"int256","name":"requestPaperAmount","type":"int256"}],"name":"requestLiquidation","outputs":[{"internalType":"int256","name":"liqtorPaperChange","type":"int256"},{"internalType":"int256","name":"liqtorCreditChange","type":"int256"},{"internalType":"int256","name":"liqedPaperChange","type":"int256"},{"internalType":"int256","name":"liqedCreditChange","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256","name":"primaryAmount","type":"uint256"},{"internalType":"uint256","name":"secondaryAmount","type":"uint256"}],"name":"requestWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bool","name":"isValid","type":"bool"}],"name":"setFastWithdrawalWhitelist","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newKeeper","type":"address"}],"name":"setFundingRateKeeper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newInsurance","type":"address"}],"name":"setInsurance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newMaxPositionAmount","type":"uint256"}],"name":"setMaxPositionAmount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"isValid","type":"bool"}],"name":"setOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"orderSender","type":"address"},{"internalType":"bool","name":"isValid","type":"bool"}],"name":"setOrderSender","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"perp","type":"address"},{"components":[{"internalType":"uint256","name":"initialMarginRatio","type":"uint256"},{"internalType":"uint256","name":"liquidationThreshold","type":"uint256"},{"internalType":"uint256","name":"liquidationPriceOff","type":"uint256"},{"internalType":"uint256","name":"insuranceFeeRate","type":"uint256"},{"internalType":"address","name":"markPriceSource","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"bool","name":"isRegistered","type":"bool"}],"internalType":"struct Types.RiskParams","name":"param","type":"tuple"}],"name":"setPerpRiskParams","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_secondaryAsset","type":"address"}],"name":"setSecondaryAsset","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newWithdrawTimeLock","type":"uint256"}],"name":"setWithdrawTimeLock","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bool","name":"isValid","type":"bool"}],"name":"setWithdrawlWhitelist","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"state","outputs":[{"internalType":"address","name":"primaryAsset","type":"address"},{"internalType":"address","name":"secondaryAsset","type":"address"},{"internalType":"uint256","name":"withdrawTimeLock","type":"uint256"},{"internalType":"bool","name":"fastWithdrawDisabled","type":"bool"},{"internalType":"address","name":"insurance","type":"address"},{"internalType":"address","name":"fundingRateKeeper","type":"address"},{"internalType":"uint256","name":"maxPositionAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"perpList","type":"address[]"},{"internalType":"int256[]","name":"rateList","type":"int256[]"}],"name":"updateFundingRate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"}]