Contract Source Code:
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "./GovernorAlpha.sol";
import "./RewardDistribution.sol";
import "../interface/IGovernor.sol";
import "../interface/ILiquidityPoolGetter.sol";
contract LpGovernor is
IGovernor,
Initializable,
ContextUpgradeable,
ERC20Upgradeable,
GovernorAlpha,
RewardDistribution
{
using SafeMathUpgradeable for uint256;
// admin: to mint/burn token
address internal _minter;
mapping(address => uint256) public lastMintBlock;
/**
* @notice Initialize LpGovernor instance.
*
* @param name ERC20 name of token.
* @param symbol ERC20 symbol of token.
* @param minter The role that has privilege to mint / burn token.
* @param target The target of execution, all action of proposal will be send to target.
* @param rewardToken The ERC20 token used as reward of mining / reward distribution.
* @param poolCreator The address of pool creator, whose owner will be the owner of governor.
*/
function initialize(
string memory name,
string memory symbol,
address minter,
address target,
address rewardToken,
address poolCreator
) external virtual override initializer {
__ERC20_init_unchained(name, symbol);
__GovernorAlpha_init_unchained(target);
__RewardDistribution_init_unchained(rewardToken, poolCreator);
_minter = minter;
_target = target;
}
function getMinter() public view returns (address) {
return _minter;
}
function getTarget() public view virtual override(IGovernor, GovernorAlpha) returns (address) {
return GovernorAlpha.getTarget();
}
/**
* @notice Mint token to account.
*/
function mint(address account, uint256 amount) public virtual override {
require(_msgSender() == _minter, "must be minter to mint");
lastMintBlock[account] = _getBlockNumber();
_mint(account, amount);
}
/**
* @notice Burn token from account. Voting will block also block burning.
*/
function burn(address account, uint256 amount) public virtual override {
require(_msgSender() == _minter, "must be minter to burn");
_burn(account, amount);
}
function isLocked(address account) public virtual returns (bool) {
bool isTransferLocked = _getBlockNumber() < lastMintBlock[account].add(_getTransferDelay());
bool isVoteLocked = GovernorAlpha.isLockedByVoting(account);
return isTransferLocked || isVoteLocked;
}
/**
* @notice Override ERC20 balanceOf.
*/
function balanceOf(address account)
public
view
virtual
override(IGovernor, ERC20Upgradeable, GovernorAlpha, RewardDistribution)
returns (uint256)
{
return ERC20Upgradeable.balanceOf(account);
}
/**
* @notice Override ERC20 balanceOf.
*/
function totalSupply()
public
view
virtual
override(IGovernor, ERC20Upgradeable, GovernorAlpha, RewardDistribution)
returns (uint256)
{
return ERC20Upgradeable.totalSupply();
}
function _beforeTokenTransfer(
address sender,
address recipient,
uint256 amount
) internal virtual override {
require(!isLocked(sender), "sender is locked");
_updateReward(sender);
_updateReward(recipient);
super._beforeTokenTransfer(sender, recipient, amount);
}
function _getTransferDelay() internal view virtual returns (uint256) {
(, , , , uint256[6] memory uintNums) = ILiquidityPoolGetter(_target).getLiquidityPoolInfo();
return uintNums[5];
}
bytes32[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when 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.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: BUSL-1.1
//
// The 3-Clause BSD License
// Copyright 2020 Compound Labs, Inc.
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
pragma solidity 0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "../interface/IPoolCreatorFull.sol";
import "../interface/ILiquidityPoolGetter.sol";
/**
* @notice Possible states that a proposal may be in.
*
* There basically are up to 4 stages for a proposal:
* 1. Pending: Period before voter can cast vote.
* 2. Active: Period for casting vote.
* Once voted, voter's all governor token will be locked until votingPeriod passed.
* 3. Defeated / Succeeded:
* For a defeated proposal, voting is done, all governor tokens are will unlock immediately;
* For a succeeded proposal, lock will be extended by `executionDelay` + `unlockDelay`.
* 4. Queued: Succeeded proposal can only be executed after an `executionDelay`;
* 5. Executed: After `executionDelay` a succeeded proposal is able to be called by anyone then marked as 'executed';
* 6. Expired: If a proposal succeeded but no one try to execute it, when the `unlockDelay` passed.
* it will be marked as expired and no longer can be executed.
*
*/
enum ProposalState {
Pending,
Active,
Defeated,
Succeeded,
Queued,
Executed,
Expired
}
struct Proposal {
// Unique id for looking up a proposal
uint256 id;
address target;
// Creator of the proposal
address proposer;
// The ordered list of function signatures to be called
string[] signatures;
// The ordered list of calldata to be passed to each call
bytes[] calldatas;
// The block at which voting begins: holders must delegate their votes prior to this block
uint256 startBlock;
// The block at which voting ends: votes must be cast prior to this block
uint256 endBlock;
// Minimal votes for a proposal to succeed
uint256 quorumVotes;
// Current number of votes in favor of this proposal
uint256 forVotes;
// Current number of votes in opposition to this proposal
uint256 againstVotes;
// Flag marking whether the proposal has been executed
bool executed;
// Receipts of ballots for the entire set of voters
mapping(address => Receipt) receipts;
}
/**
* @notice Ballot receipt record for a account.
*/
struct Receipt {
// Whether or not a vote has been cast
bool hasVoted;
// Whether or not the account supports the proposal
bool support;
// The number of votes the account had, which were cast
uint256 votes;
}
/**
* @notice This is a simplify version of 'Compound GovernorAlpha'.
* Timelock is integrated into GovernorAlpha.
*/
abstract contract GovernorAlpha is Initializable, ContextUpgradeable {
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
bytes4 public constant SIGNATURE_PERPETUAL_UPGRADE_AND_CALL =
bytes4(keccak256(bytes("upgradeToAndCall(bytes32,bytes,bytes)")));
bytes4 public constant SIGNATURE_PERPETUAL_SETTLE =
bytes4(keccak256(bytes("forceToSetEmergencyState(uint256,int256)")));
bytes4 public constant SIGNATURE_PERPETUAL_TRANSFER_OPERATOR =
bytes4(keccak256(bytes("transferOperator(address)")));
IPoolCreatorFull internal _creator;
address internal _target;
mapping(address => uint256) internal _voteLocks;
mapping(address => EnumerableSetUpgradeable.UintSet) internal _supportedProposals;
/**
* @notice The total number of proposals.
*/
uint256 public proposalCount;
/**
* @notice The official record of all proposals ever proposed.
*/
mapping(uint256 => Proposal) public proposals;
/**
* @notice The latest proposal for each proposer.
*/
mapping(address => uint256) public latestProposalIds;
/**
* @notice An event emitted when a new proposal is created.
*/
event ProposalCreated(
uint256 id,
address proposer,
address target,
string[] signatures,
bytes[] calldatas,
uint256 startBlock,
uint256 endBlock,
uint256 quorumVotes,
string description
);
/**
* @notice An event emitted when a proposal is executed.
*/
event ExecuteTransaction(
bytes32 indexed txHash,
address indexed target,
string signature,
bytes data,
uint256 eta
);
/**
* @notice An event emitted when a vote has been cast on a proposal.
*/
event VoteCast(address account, uint256 proposalId, bool support, uint256 votes);
/**
* @notice An event emitted when a proposal has been executed in the Timelock.
*/
event ProposalExecuted(uint256 id);
function __GovernorAlpha_init_unchained(address target_) internal initializer {
_target = target_;
_creator = IPoolCreatorFull(_msgSender());
}
function getTarget() public view virtual returns (address) {
return _target;
}
/**
* @notice Balance of vote token which must be implemented through inheritance.
*/
function balanceOf(address account) public view virtual returns (uint256);
/**
* @notice TotalSupply of vote token which must be implemented through inheritance.
*/
function totalSupply() public view virtual returns (uint256);
/**
* @notice The number of votes in support of a proposal required in order for a quorum to be reached
* and for a vote to succeed.
* @dev [ConfirmBeforeDeployment]
*/
function quorumRate() public pure virtual returns (uint256) {
return 1e17;
}
/**
* @notice The number of votes in support of a proposal required in order for a quorum to be reached
* and for a vote to succeed.
* @dev [ConfirmBeforeDeployment]
*/
function criticalQuorumRate() public pure virtual returns (uint256) {
return 2e17;
}
/**
* @notice The number of votes required in order for a account to become a proposer.
* @dev [ConfirmBeforeDeployment]
*/
function proposalThresholdRate() public pure virtual returns (uint256) {
return 1e16;
}
/**
* @notice The maximum number of actions that can be included in a proposal.
* @dev [ConfirmBeforeDeployment]
*/
function proposalMaxOperations() public pure virtual returns (uint256) {
return 10;
}
/**
* @notice The delay before voting on a proposal may take place, once proposed.
* See `ProposalState` for details;
* @dev [ConfirmBeforeDeployment]
*/
function votingDelay() public pure virtual returns (uint256) {
return 1;
}
/**
* @notice The duration of voting on a proposal, in blocks.
* See `ProposalState` for details;
* @dev [ConfirmBeforeDeployment]
*/
function votingPeriod() public pure virtual returns (uint256) {
return 17280;
}
/**
* @notice The delay before a succeeded proposal being executed (say, proposal in queued state).
* See `ProposalState` for details;
* @dev [ConfirmBeforeDeployment]
*/
function executionDelay() public pure virtual returns (uint256) {
return 11520;
}
/**
* @notice The duration after a proposal can be executed. See `ProposalState` for details;
* @dev [ConfirmBeforeDeployment]
*/
function unlockDelay() public pure virtual returns (uint256) {
return 17280;
}
function getProposalThreshold() public view virtual returns (uint256) {
uint256 totalVotes = totalSupply();
return totalVotes.mul(proposalThresholdRate()).div(1e18);
}
function getQuorumVotes(uint256 proposalId) public view virtual returns (uint256) {
Proposal storage proposal = proposals[proposalId];
uint256 length = proposal.signatures.length;
uint256 totalVotes = totalSupply();
for (uint256 i = 0; i < length; i++) {
if (isCriticalFunction(proposal.signatures[i])) {
return totalVotes.mul(criticalQuorumRate()).div(1e18);
}
}
return totalVotes.mul(quorumRate()).div(1e18);
}
/**
* @notice Return true if a signature matches critical functions, which means a proposal with critical actions
* will require more share (governance) token to reach quorum.
*
* @param functionSignature The string signature of function to test.
*/
function isCriticalFunction(string memory functionSignature) public pure returns (bool) {
bytes4 functionHash = bytes4(keccak256(bytes(functionSignature)));
return
functionHash == SIGNATURE_PERPETUAL_UPGRADE_AND_CALL ||
functionHash == SIGNATURE_PERPETUAL_SETTLE ||
functionHash == SIGNATURE_PERPETUAL_TRANSFER_OPERATOR;
}
/**
* @notice Execute a transaction in 'queue' state.
*
& @param proposalId The id of proposal to execute.
*/
function execute(uint256 proposalId) public payable {
require(
state(proposalId) == ProposalState.Queued,
"proposal can only be executed if it is success and queued"
);
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint256 i = 0; i < proposal.signatures.length; i++) {
_executeTransaction(
proposal.target,
proposal.signatures[i],
proposal.calldatas[i],
proposal.endBlock
);
}
emit ProposalExecuted(proposalId);
}
function getActions(uint256 proposalId)
public
view
returns (string[] memory signatures, bytes[] memory calldatas)
{
Proposal storage p = proposals[proposalId];
return (p.signatures, p.calldatas);
}
function getReceipt(uint256 proposalId, address account) public view returns (Receipt memory) {
return proposals[proposalId].receipts[account];
}
function state(uint256 proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > 0, "invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (
proposal.forVotes <= proposal.againstVotes ||
proposal.forVotes.add(proposal.againstVotes) < proposal.quorumVotes
) {
return ProposalState.Defeated;
} else if (block.number <= proposal.endBlock.add(executionDelay())) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.number > proposal.endBlock.add(executionDelay()).add(unlockDelay())) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
function propose(
string[] memory signatures,
bytes[] memory calldatas,
string memory description
) public virtual returns (uint256) {
require(signatures.length == calldatas.length, "function information arity mismatch");
require(signatures.length != 0, "must provide actions");
require(signatures.length <= proposalMaxOperations(), "too many actions");
address proposer = _msgSender();
uint256 proposalId = _createProposal(
proposer,
getTarget(),
signatures,
calldatas,
description
);
latestProposalIds[proposer] = proposalId;
_castVote(proposer, proposalId, true);
return proposalId;
}
/**
* @notice Since the governor itself is upgradeable too and
* the ProxyAdmin is a independent contract controlled by pool creator,
* upgrade now is a special proposal.
*
* @param targetVersionKey The key of target version to be upgrade to.
* @param dataForLiquidityPool A bytes array contains calldata to call a function of new liquidity pool after upgrade.
* This field will be ignored if left empty.
* @param dataForGovernor A bytes array contains calldata to call a function of new governor after upgrade.
* This field will be ignored if left empty.
* @param description A description of this proposal, only appears in transaction logs.
* @return proposalId The id of new proposal.
*
*/
function proposeToUpgradeAndCall(
bytes32 targetVersionKey,
bytes memory dataForLiquidityPool,
bytes memory dataForGovernor,
string memory description
) public virtual returns (uint256) {
_validateVersion(targetVersionKey);
address proposer = _msgSender();
string[] memory signatures = new string[](1);
signatures[0] = "upgradeToAndCall(bytes32,bytes,bytes)";
bytes[] memory calldatas = new bytes[](1);
calldatas[0] = abi.encode(targetVersionKey, dataForLiquidityPool, dataForGovernor);
uint256 proposalId = _createProposal(
proposer,
address(_creator),
signatures,
calldatas,
description
);
latestProposalIds[proposer] = proposalId;
_castVote(proposer, proposalId, true);
return proposalId;
}
function _validateVersion(bytes32 targetVersionKey) internal view {
require(_creator.isVersionKeyValid(targetVersionKey), "version to upgrade to is not valid");
bytes32 baseVersionKey = _creator.getAppliedVersionKey(getTarget(), address(this));
require(
_creator.isVersionCompatible(targetVersionKey, baseVersionKey),
"version to upgrade to is not compatible"
);
}
function _validateProposer(address proposer) internal view {
address operator = _getOperator();
if (operator != address(0)) {
require(proposer == operator, "proposer must be operator when operator exists");
} else {
require(balanceOf(proposer) >= getProposalThreshold(), "proposal threshold unmet");
}
if (latestProposalIds[proposer] != 0) {
ProposalState latestProposalState = state(latestProposalIds[proposer]);
require(latestProposalState != ProposalState.Pending, "last proposal is pending");
require(latestProposalState != ProposalState.Active, "last proposal is active");
}
}
function _createProposal(
address proposer,
address target,
string[] memory signatures,
bytes[] memory calldatas,
string memory description
) internal returns (uint256) {
_validateProposer(proposer);
uint256 startBlock = _getBlockNumber().add(votingDelay());
uint256 endBlock = startBlock.add(votingPeriod());
proposalCount++;
uint256 proposalId = proposalCount;
Proposal storage proposal = proposals[proposalId];
proposal.id = proposalId;
proposal.target = target;
proposal.proposer = proposer;
proposal.signatures = signatures;
proposal.calldatas = calldatas;
proposal.startBlock = startBlock;
proposal.endBlock = endBlock;
uint256 quorumVotes = getQuorumVotes(proposalId);
proposal.quorumVotes = quorumVotes;
emit ProposalCreated(
proposalId,
proposer,
target,
signatures,
calldatas,
startBlock,
endBlock,
quorumVotes,
description
);
return proposalId;
}
function castVote(uint256 proposalId, bool support) public virtual {
require(state(proposalId) == ProposalState.Active, "voting is closed");
_castVote(_msgSender(), proposalId, support);
}
function isLockedByVoting(address account) public virtual returns (bool) {
if (account == address(0)) {
return false;
}
return _getBlockNumber() <= _updateVoteLock(account, 0);
}
function getUnlockBlock(address account) public view virtual returns (uint256) {
(uint256 lastUnlockBlock, , ) = _getVoteLock(account);
return lastUnlockBlock;
}
function _getVoteLock(address account)
internal
view
virtual
returns (
uint256 lastUnlockBlock,
uint256 stableProposalCount,
uint256[] memory stableProposalIds
)
{
lastUnlockBlock = _voteLocks[account];
EnumerableSetUpgradeable.UintSet storage proposalIds = _supportedProposals[account];
uint256 length = proposalIds.length();
if (length > 0) {
stableProposalIds = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
uint256 proposalId = proposalIds.at(i);
ProposalState proposalState = state(proposalId);
if (
proposalState == ProposalState.Pending || proposalState == ProposalState.Active
) {
continue;
}
if (
proposalState == ProposalState.Succeeded ||
proposalState == ProposalState.Executed ||
proposalState == ProposalState.Queued ||
proposalState == ProposalState.Expired
) {
uint256 unlockBlock = proposals[proposalId].endBlock.add(
executionDelay().add(unlockDelay())
);
if (unlockBlock > lastUnlockBlock) {
lastUnlockBlock = unlockBlock;
}
}
stableProposalIds[stableProposalCount] = proposalId;
stableProposalCount++;
}
}
}
function _updateVoteLock(address account, uint256 blockNumber) internal returns (uint256) {
EnumerableSetUpgradeable.UintSet storage proposalIds = _supportedProposals[account];
(
uint256 lastUnlockBlock,
uint256 stableProposalCount,
uint256[] memory stableProposalIds
) = _getVoteLock(account);
for (uint256 i = 0; i < stableProposalCount; i++) {
uint256 proposalId = stableProposalIds[i];
if (proposalId != 0) {
proposalIds.remove(proposalId);
}
}
_voteLocks[account] = blockNumber > lastUnlockBlock ? blockNumber : lastUnlockBlock;
return _voteLocks[account];
}
function _castVote(
address account,
uint256 proposalId,
bool support
) internal {
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[account];
require(receipt.hasVoted == false, "account already voted");
uint256 votes = balanceOf(account);
if (support) {
proposal.forVotes = proposal.forVotes.add(votes);
} else {
proposal.againstVotes = proposal.againstVotes.add(votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
_updateVoteLock(account, proposal.endBlock.add(1));
if (support) {
_supportedProposals[account].add(proposalId);
}
emit VoteCast(account, proposalId, support, votes);
}
function _getOperator() internal view returns (address) {
(, , address[7] memory addresses, , ) = ILiquidityPoolGetter(_target)
.getLiquidityPoolInfo();
return addresses[1];
}
function _executeTransaction(
address target,
string memory signature,
bytes memory data,
uint256 eta
) internal returns (bytes memory) {
bytes32 txHash = keccak256(abi.encode(target, signature, data, eta));
uint256 blockNumber = _getBlockNumber();
require(
blockNumber >= eta.add(executionDelay()),
"Transaction hasn't surpassed time lock."
);
require(
blockNumber <= eta.add(executionDelay()).add(unlockDelay()),
"Transaction is stale."
);
bytes memory returnData = target.functionCall(
abi.encodePacked(bytes4(keccak256(bytes(signature))), data)
);
emit ExecuteTransaction(txHash, target, signature, data, eta);
return returnData;
}
function _getBlockNumber() internal view virtual returns (uint256) {
return block.number;
}
bytes32[50] private __gap;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.4;
import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "../interface/IPoolCreatorFull.sol";
abstract contract RewardDistribution is Initializable, ContextUpgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
IPoolCreatorFull public poolCreator;
IERC20Upgradeable public rewardToken;
uint256 public periodFinish;
uint256 public rewardRate;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
address public rewardDistribution;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
event RewardPaid(address indexed user, uint256 reward);
event RewardAdded(uint256 reward, uint256 periodFinish);
event RewardRateChanged(uint256 previousRate, uint256 currentRate, uint256 periodFinish);
modifier updateReward(address account) {
_updateReward(account);
_;
}
modifier onlyOwnerOfPoolCreator() {
require(_msgSender() == poolCreator.owner(), "caller must be owner of pool creator");
_;
}
// virtual methods
function balanceOf(address account) public view virtual returns (uint256);
function totalSupply() public view virtual returns (uint256);
function __RewardDistribution_init_unchained(address rewardToken_, address poolCreator_)
internal
initializer
{
rewardToken = IERC20Upgradeable(rewardToken_);
poolCreator = IPoolCreatorFull(poolCreator_);
}
/**
* @notice Set reward distribution rate. If there is unfinished distribution, the end block will be changed
* according to change of newRewardRate.
*
* @param newRewardRate New reward distribution rate.
*/
function setRewardRate(uint256 newRewardRate)
external
virtual
onlyOwnerOfPoolCreator
updateReward(address(0))
{
if (newRewardRate == 0) {
periodFinish = block.number;
} else if (periodFinish != 0) {
periodFinish = periodFinish.sub(lastUpdateTime).mul(rewardRate).div(newRewardRate).add(
block.number
);
}
emit RewardRateChanged(rewardRate, newRewardRate, periodFinish);
rewardRate = newRewardRate;
}
/**
* @notice Add new distributable reward to current pool, this will extend an exist distribution or
* start a new distribution if previous one is already ended.
*
* @param reward Amount of reward to add.
*/
function notifyRewardAmount(uint256 reward)
external
virtual
onlyOwnerOfPoolCreator
updateReward(address(0))
{
require(rewardRate > 0, "rewardRate is zero");
uint256 period = reward.div(rewardRate);
// already finished or not initialized
if (block.number > periodFinish) {
lastUpdateTime = block.number;
periodFinish = block.number.add(period);
emit RewardAdded(reward, periodFinish);
} else {
// not finished or not initialized
periodFinish = periodFinish.add(period);
emit RewardAdded(reward, periodFinish);
}
}
/**
* @notice Return end block if last distribution is done or current timestamp.
*/
function lastBlockRewardApplicable() public view returns (uint256) {
return block.number <= periodFinish ? block.number : periodFinish;
}
/**
* @notice Return the per token amount of reward.
* The expected reward of user is: [amount of share] x rewardPerToken - claimedReward.
*/
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastBlockRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(
totalSupply()
)
);
}
/**
* @notice Return real time reward of account.
*/
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
/**
* @notice Claim all remaining reward of account.
*/
function getReward() public updateReward(_msgSender()) {
address account = _msgSender();
uint256 reward = earned(account);
if (reward > 0) {
rewards[account] = 0;
rewardToken.safeTransfer(account, reward);
emit RewardPaid(account, reward);
}
}
function _updateReward(address account) internal {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastBlockRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
}
bytes32[50] private __gap;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.4;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IGovernor {
function initialize(
string memory name,
string memory symbol,
address minter,
address target_,
address rewardToken,
address poolCreator
) external;
function totalSupply() external view returns (uint256);
function getTarget() external view returns (address);
function mint(address account, uint256 amount) external;
function burn(address account, uint256 amount) external;
function balanceOf(address account) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.4;
pragma experimental ABIEncoderV2;
import "../Type.sol";
interface ILiquidityPoolGetter {
/**
* @notice Get the info of the liquidity pool
* @return isRunning True if the liquidity pool is running
* @return isFastCreationEnabled True if the operator of the liquidity pool is allowed to create new perpetual
* when the liquidity pool is running
* @return addresses The related addresses of the liquidity pool
* @return intNums Int type properties, see below for details.
* @return uintNums Uint type properties, see below for details.
*/
function getLiquidityPoolInfo()
external
view
returns (
bool isRunning,
bool isFastCreationEnabled,
// [0] creator,
// [1] operator,
// [2] transferringOperator,
// [3] governor,
// [4] shareToken,
// [5] collateralToken,
// [6] vault,
address[7] memory addresses,
// [0] vaultFeeRate,
// [1] poolCash,
// [2] insuranceFundCap,
// [3] insuranceFund,
// [4] donatedInsuranceFund,
int256[5] memory intNums,
// [0] collateralDecimals,
// [1] perpetualCount,
// [2] fundingTime,
// [3] operatorExpiration,
// [4] liquidityCap,
// [5] shareTransferDelay,
uint256[6] memory uintNums
);
/**
* @notice Get the info of the perpetual. Need to update the funding state and the oracle price
* of each perpetual before and update the funding rate of each perpetual after
* @param perpetualIndex The index of the perpetual in the liquidity pool
* @return state The state of the perpetual
* @return oracle The oracle's address of the perpetual
* @return nums The related numbers of the perpetual
*/
function getPerpetualInfo(uint256 perpetualIndex)
external
view
returns (
PerpetualState state,
address oracle,
// [0] totalCollateral
// [1] markPrice, (return settlementPrice if it is in EMERGENCY state)
// [2] indexPrice,
// [3] fundingRate,
// [4] unitAccumulativeFunding,
// [5] initialMarginRate,
// [6] maintenanceMarginRate,
// [7] operatorFeeRate,
// [8] lpFeeRate,
// [9] referralRebateRate,
// [10] liquidationPenaltyRate,
// [11] keeperGasReward,
// [12] insuranceFundRate,
// [13-15] halfSpread value, min, max,
// [16-18] openSlippageFactor value, min, max,
// [19-21] closeSlippageFactor value, min, max,
// [22-24] fundingRateLimit value, min, max,
// [25-27] ammMaxLeverage value, min, max,
// [28-30] maxClosePriceDiscount value, min, max,
// [31] openInterest,
// [32] maxOpenInterestRate,
// [33-35] fundingRateFactor value, min, max,
// [36-38] defaultTargetLeverage value, min, max,
int256[39] memory nums
);
/**
* @notice Get the account info of the trader. Need to update the funding state and the oracle price
* of each perpetual before and update the funding rate of each perpetual after
* @param perpetualIndex The index of the perpetual in the liquidity pool
* @param trader The address of the trader
* @return cash The cash(collateral) of the account
* @return position The position of the account
* @return availableMargin The available margin of the account
* @return margin The margin of the account
* @return settleableMargin The settleable margin of the account
* @return isInitialMarginSafe True if the account is initial margin safe
* @return isMaintenanceMarginSafe True if the account is maintenance margin safe
* @return isMarginSafe True if the total value of margin account is beyond 0
* @return targetLeverage The target leverage for openning position.
*/
function getMarginAccount(uint256 perpetualIndex, address trader)
external
view
returns (
int256 cash,
int256 position,
int256 availableMargin,
int256 margin,
int256 settleableMargin,
bool isInitialMarginSafe,
bool isMaintenanceMarginSafe,
bool isMarginSafe, // bankrupt
int256 targetLeverage
);
/**
* @notice Get the number of active accounts in the perpetual.
* Active means the trader's account is not empty in the perpetual.
* Empty means cash and position are zero
* @param perpetualIndex The index of the perpetual in the liquidity pool
* @return activeAccountCount The number of active accounts in the perpetual
*/
function getActiveAccountCount(uint256 perpetualIndex) external view returns (uint256);
/**
* @notice Get the active accounts in the perpetual whose index between begin and end.
* Active means the trader's account is not empty in the perpetual.
* Empty means cash and position are zero
* @param perpetualIndex The index of the perpetual in the liquidity pool
* @param begin The begin index
* @param end The end index
* @return result The active accounts in the perpetual whose index between begin and end
*/
function listActiveAccounts(
uint256 perpetualIndex,
uint256 begin,
uint256 end
) external view returns (address[] memory result);
/**
* @notice Get the progress of clearing active accounts.
* Return the number of total active accounts and the number of active accounts not cleared
* @param perpetualIndex The index of the perpetual in the liquidity pool
* @return left The left active accounts
* @return total The total active accounts
*/
function getClearProgress(uint256 perpetualIndex)
external
view
returns (uint256 left, uint256 total);
/**
* @notice Get the pool margin of the liquidity pool.
* Pool margin is how much collateral of the pool considering the AMM's positions of perpetuals
* @return poolMargin The pool margin of the liquidity pool
*/
function getPoolMargin() external view returns (int256 poolMargin, bool isSafe);
/**
* @notice Query the price, fees and cost when trade agaist amm.
* The trading price is determined by the AMM based on the index price of the perpetual.
* This method should returns the same result as a 'read-only' trade.
* WARN: the result of this function is base on current storage of liquidityPool, not the latest.
* To get the latest status, call `syncState` first.
*
* Flags is a 32 bit uint value which indicates: (from highest bit)
* - close only only close position during trading;
* - market order do not check limit price during trading;
* - stop loss only available in brokerTrade mode;
* - take profit only available in brokerTrade mode;
* For stop loss and take profit, see `validateTriggerPrice` in OrderModule.sol for details.
*
* @param perpetualIndex The index of the perpetual in liquidity pool.
* @param trader The address of trader.
* @param amount The amount of position to trader, positive for buying and negative for selling. The amount always use decimals 18.
* @param referrer The address of referrer who will get rebate from the deal.
* @param flags The flags of the trade.
* @return tradePrice The average fill price.
* @return totalFee The total fee collected from the trader after the trade.
* @return cost Deposit or withdraw to let effective leverage == targetLeverage if flags contain USE_TARGET_LEVERAGE. > 0 if deposit, < 0 if withdraw.
*/
function queryTrade(
uint256 perpetualIndex,
address trader,
int256 amount,
address referrer,
uint32 flags
)
external
returns (
int256 tradePrice,
int256 totalFee,
int256 cost
);
/**
* @notice Query cash to add / share to mint when adding liquidity to the liquidity pool.
* Only one of cashToAdd or shareToMint may be non-zero.
*
* @param cashToAdd The amount of cash to add, always use decimals 18.
* @param shareToMint The amount of share token to mint, always use decimals 18.
* @return cashToAddResult The amount of cash to add, always use decimals 18. Equal to cashToAdd if cashToAdd is non-zero.
* @return shareToMintResult The amount of cash to add, always use decimals 18. Equal to shareToMint if shareToMint is non-zero.
*/
function queryAddLiquidity(int256 cashToAdd, int256 shareToMint)
external
view
returns (int256 cashToAddResult, int256 shareToMintResult);
/**
* @notice Query cash to return / share to redeem when removing liquidity from the liquidity pool.
* Only one of shareToRemove or cashToReturn may be non-zero.
* Can only called when the pool is running.
*
* @param shareToRemove The amount of share token to redeem, always use decimals 18.
* @param cashToReturn The amount of cash to return, always use decimals 18.
* @return shareToRemoveResult The amount of share token to redeem, always use decimals 18. Equal to shareToRemove if shareToRemove is non-zero.
* @return cashToReturnResult The amount of cash to return, always use decimals 18. Equal to cashToReturn if cashToReturn is non-zero.
*/
function queryRemoveLiquidity(int256 shareToRemove, int256 cashToReturn)
external
view
returns (int256 shareToRemoveResult, int256 cashToReturnResult);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @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 GSN 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 ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 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://diligence.consensys.net/posts/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.5.11/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");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// 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
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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 `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, 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 `sender` to `recipient` 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 sender, address recipient, uint256 amount) external returns (bool);
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.4;
import "./IAccessControl.sol";
import "./IPoolCreator.sol";
import "./ITracer.sol";
import "./IVersionControl.sol";
import "./IVariables.sol";
import "./IKeeperWhitelist.sol";
interface IPoolCreatorFull is
IPoolCreator,
IVersionControl,
ITracer,
IVariables,
IAccessControl,
IKeeperWhitelist
{
/**
* @notice Owner of version control.
*/
function owner() external view override(IVersionControl, IVariables) returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.4;
interface IAccessControl {
function grantPrivilege(address trader, uint256 privilege) external;
function revokePrivilege(address trader, uint256 privilege) external;
function isGranted(
address owner,
address trader,
uint256 privilege
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.4;
import "./IProxyAdmin.sol";
interface IPoolCreator {
function upgradeAdmin() external view returns (IProxyAdmin proxyAdmin);
/**
* @notice Create a liquidity pool with the latest version.
* The sender will be the operator of pool.
*
* @param collateral he collateral address of the liquidity pool.
* @param collateralDecimals The collateral's decimals of the liquidity pool.
* @param nonce A random nonce to calculate the address of deployed contracts.
* @param initData A bytes array contains data to initialize new created liquidity pool.
* @return liquidityPool The address of the created liquidity pool.
*/
function createLiquidityPool(
address collateral,
uint256 collateralDecimals,
int256 nonce,
bytes calldata initData
) external returns (address liquidityPool, address governor);
/**
* @notice Upgrade a liquidity pool and governor pair then call a patch function on the upgraded contract (optional).
* This method checks the sender and forwards the request to ProxyAdmin to do upgrading.
*
* @param targetVersionKey The key of version to be upgrade up. The target version must be compatible with
* current version.
* @param dataForLiquidityPool The patch calldata for upgraded liquidity pool.
* @param dataForGovernor The patch calldata of upgraded governor.
*/
function upgradeToAndCall(
bytes32 targetVersionKey,
bytes memory dataForLiquidityPool,
bytes memory dataForGovernor
) external;
/**
* @notice Indicates the universe settle state.
* If the flag set to true:
* - all the pereptual created by this poolCreator can be settled immediately;
* - all the trading method will be unavailable.
*/
function isUniverseSettled() external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.4;
import "./IProxyAdmin.sol";
interface ITracer {
/**
* @notice Activate the perpetual for the trader. Active means the trader's account is not empty in
* the perpetual. Empty means cash and position are zero. Can only called by a liquidity pool.
*
* @param trader The address of the trader.
* @param perpetualIndex The index of the perpetual in the liquidity pool.
* @return True if the activation is successful.
*/
function activatePerpetualFor(address trader, uint256 perpetualIndex) external returns (bool);
/**
* @notice Deactivate the perpetual for the trader. Active means the trader's account is not empty in
* the perpetual. Empty means cash and position are zero. Can only called by a liquidity pool.
*
* @param trader The address of the trader.
* @param perpetualIndex The index of the perpetual in the liquidity pool.
* @return True if the deactivation is successful.
*/
function deactivatePerpetualFor(address trader, uint256 perpetualIndex) external returns (bool);
/**
* @notice Liquidity pool must call this method when changing its ownership to the new operator.
* Can only be called by a liquidity pool. This method does not affect 'ownership' or privileges
* of operator but only make a record for further query.
*
* @param liquidityPool The address of the liquidity pool.
* @param operator The address of the new operator, must be different from the old operator.
*/
function registerOperatorOfLiquidityPool(address liquidityPool, address operator) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.4;
import "./IProxyAdmin.sol";
interface IVersionControl {
function owner() external view returns (address);
function getLatestVersion() external view returns (bytes32 latestVersionKey);
/**
* @notice Get the details of the version.
*
* @param versionKey The key of the version to get.
* @return liquidityPoolTemplate The address of the liquidity pool template.
* @return governorTemplate The address of the governor template.
* @return compatibility The compatibility of the specified version.
*/
function getVersion(bytes32 versionKey)
external
view
returns (
address liquidityPoolTemplate,
address governorTemplate,
uint256 compatibility
);
/**
* @notice Get the description of the implementation of liquidity pool.
* Description contains creator, create time, compatibility and note
*
* @param liquidityPool The address of the liquidity pool.
* @param governor The address of the governor.
* @return appliedVersionKey The version key of given liquidity pool and governor.
*/
function getAppliedVersionKey(address liquidityPool, address governor)
external
view
returns (bytes32 appliedVersionKey);
/**
* @notice Check if a key is valid (exists).
*
* @param versionKey The key of the version to test.
* @return isValid Return true if the version of given key is valid.
*/
function isVersionKeyValid(bytes32 versionKey) external view returns (bool isValid);
/**
* @notice Check if the implementation of liquidity pool target is compatible with the implementation base.
* Being compatible means having larger compatibility.
*
* @param targetVersionKey The key of the version to be upgraded to.
* @param baseVersionKey The key of the version to be upgraded from.
* @return isCompatible True if the target version is compatible with the base version.
*/
function isVersionCompatible(bytes32 targetVersionKey, bytes32 baseVersionKey)
external
view
returns (bool isCompatible);
/**
* @dev Get a certain number of implementations of liquidity pool within range [begin, end).
*
* @param begin The index of first element to retrieve.
* @param end The end index of element, exclusive.
* @return versionKeys An array contains current version keys.
*/
function listAvailableVersions(uint256 begin, uint256 end)
external
view
returns (bytes32[] memory versionKeys);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.4;
import "./IProxyAdmin.sol";
interface IVariables {
function owner() external view returns (address);
/**
* @notice Get the address of the vault
* @return address The address of the vault
*/
function getVault() external view returns (address);
/**
* @notice Get the vault fee rate
* @return int256 The vault fee rate
*/
function getVaultFeeRate() external view returns (int256);
/**
* @notice Get the address of the access controller. It's always its own address.
*
* @return address The address of the access controller.
*/
function getAccessController() external view returns (address);
/**
* @notice Get the address of the symbol service.
*
* @return Address The address of the symbol service.
*/
function getSymbolService() external view returns (address);
/**
* @notice Set the vault address. Can only called by owner.
*
* @param newVault The new value of the vault fee rate
*/
function setVault(address newVault) external;
/**
* @notice Get the address of the mcb token.
* @dev [ConfirmBeforeDeployment]
*
* @return Address The address of the mcb token.
*/
function getMCBToken() external pure returns (address);
/**
* @notice Set the vault fee rate. Can only called by owner.
*
* @param newVaultFeeRate The new value of the vault fee rate
*/
function setVaultFeeRate(int256 newVaultFeeRate) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.4;
interface IKeeperWhitelist {
/**
* @notice Add an address to keeper whitelist.
*/
function addKeeper(address keeper) external;
/**
* @notice Remove an address from keeper whitelist.
*/
function removeKeeper(address keeper) external;
/**
* @notice Check if an address is in keeper whitelist.
*/
function isKeeper(address keeper) external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.4;
interface IProxyAdmin {
function getProxyImplementation(address proxy) external view returns (address);
/**
* @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgrade(address proxy, address implementation) external;
/**
* @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
* {TransparentUpgradeableProxy-upgradeToAndCall}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgradeAndCall(
address proxy,
address implementation,
bytes memory data
) external payable;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.4;
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
/**
* @notice Perpetual state:
* - INVALID: Uninitialized or not non-existent perpetual;
* - INITIALIZING: Only when LiquidityPoolStorage.isRunning == false. Traders cannot perform operations;
* - NORMAL: Full functional state. Traders is able to perform all operations;
* - EMERGENCY: Perpetual is unsafe and only clear is available;
* - CLEARED: All margin account is cleared. Trade could withdraw remaining margin balance.
*/
enum PerpetualState {
INVALID,
INITIALIZING,
NORMAL,
EMERGENCY,
CLEARED
}
enum OrderType {
LIMIT,
MARKET,
STOP
}
/**
* @notice Data structure to store risk parameter value.
*/
struct Option {
int256 value;
int256 minValue;
int256 maxValue;
}
/**
* @notice Data structure to store oracle price data.
*/
struct OraclePriceData {
int256 price;
uint256 time;
}
/**
* @notice Data structure to store user margin information. See MarginAccountModule.sol for details.
*/
struct MarginAccount {
int256 cash;
int256 position;
int256 targetLeverage;
}
/**
* @notice Data structure of an order object.
*/
struct Order {
address trader;
address broker;
address relayer;
address referrer;
address liquidityPool;
int256 minTradeAmount;
int256 amount;
int256 limitPrice;
int256 triggerPrice;
uint256 chainID;
uint64 expiredAt;
uint32 perpetualIndex;
uint32 brokerFeeLimit;
uint32 flags;
uint32 salt;
}
/**
* @notice Core data structure, a core .
*/
struct LiquidityPoolStorage {
bool isRunning;
bool isFastCreationEnabled;
// addresses
address creator;
address operator;
address transferringOperator;
address governor;
address shareToken;
address accessController;
bool reserved3; // isWrapped
uint256 scaler;
uint256 collateralDecimals;
address collateralToken;
// pool attributes
int256 poolCash;
uint256 fundingTime;
uint256 reserved5;
uint256 operatorExpiration;
mapping(address => int256) reserved1;
bytes32[] reserved2;
// perpetuals
uint256 perpetualCount;
mapping(uint256 => PerpetualStorage) perpetuals;
// insurance fund
int256 insuranceFundCap;
int256 insuranceFund;
int256 donatedInsuranceFund;
address reserved4;
uint256 liquidityCap;
uint256 shareTransferDelay;
// reserved slot for future upgrade
bytes32[14] reserved;
}
/**
* @notice Core data structure, storing perpetual information.
*/
struct PerpetualStorage {
uint256 id;
PerpetualState state;
address oracle;
int256 totalCollateral;
int256 openInterest;
// prices
OraclePriceData indexPriceData;
OraclePriceData markPriceData;
OraclePriceData settlementPriceData;
// funding state
int256 fundingRate;
int256 unitAccumulativeFunding;
// base parameters
int256 initialMarginRate;
int256 maintenanceMarginRate;
int256 operatorFeeRate;
int256 lpFeeRate;
int256 referralRebateRate;
int256 liquidationPenaltyRate;
int256 keeperGasReward;
int256 insuranceFundRate;
int256 reserved1;
int256 maxOpenInterestRate;
// risk parameters
Option halfSpread;
Option openSlippageFactor;
Option closeSlippageFactor;
Option fundingRateLimit;
Option fundingRateFactor;
Option ammMaxLeverage;
Option maxClosePriceDiscount;
// users
uint256 totalAccount;
int256 totalMarginWithoutPosition;
int256 totalMarginWithPosition;
int256 redemptionRateWithoutPosition;
int256 redemptionRateWithPosition;
EnumerableSetUpgradeable.AddressSet activeAccounts;
// insurance fund
int256 reserved2;
int256 reserved3;
// accounts
mapping(address => MarginAccount) marginAccounts;
Option defaultTargetLeverage;
// keeper
address reserved4;
EnumerableSetUpgradeable.AddressSet ammKeepers;
EnumerableSetUpgradeable.AddressSet reserved5;
// reserved slot for future upgrade
bytes32[12] reserved;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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'
// solhint-disable-next-line max-line-length
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));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @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(IERC20Upgradeable 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");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}