Verified contractExactMIT
Staking
Address0x4e5e8c5294f492865cae4e4e92cdd8c499ffdecc
- Balance
0 ETH
- Transactions
511
- Compiler
solc 0.6.12
- Same code
4 more contracts
Details
- Compiler
- solc 0.6.12+commit.27d51765
- Language
- solidity
- Optimization
- No
- EVM version
- istanbul
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 12,315,049
- Creation transaction
- 0x1ba2aacb34…14b6103f53
- Main copy (most transactions)
- 0x4e995d58…adcfa0b7
55 files
- contracts/Staking.solmain9.56 KB
- @openzeppelin/contracts/GSN/Context.sol933 B
- @openzeppelin/contracts/access/Ownable.sol2.23 KB
- @openzeppelin/contracts/math/Math.sol801 B
- @openzeppelin/contracts/math/SafeMath.sol5.2 KB
- @openzeppelin/contracts/math/SignedSafeMath.sol2.66 KB
- @openzeppelin/contracts/token/ERC20/ERC20.sol10.79 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.7 KB
- @openzeppelin/contracts/token/ERC20/SafeERC20.sol3.71 KB
- @openzeppelin/contracts/utils/Address.sol5.88 KB
- @openzeppelin/contracts/utils/EnumerableSet.sol7.79 KB
- @openzeppelin/contracts/utils/Pausable.sol2.16 KB
- @openzeppelin/contracts/utils/ReentrancyGuard.sol2.6 KB
- contracts/Budget.sol3.73 KB
- contracts/CollateralMarket.sol4.53 KB
- contracts/GovernanceToken.sol17.2 KB
- contracts/GovernorAlpha.sol15.49 KB
- contracts/Investment.sol9.26 KB
- contracts/Issuer.sol2.53 KB
- contracts/Market.sol11.05 KB
- contracts/StableToken.sol840 B
- contracts/Timelock.sol5.03 KB
- contracts/Treasury.sol1.66 KB
- contracts/Vesting.sol5.34 KB
- contracts/VestingSplitter.sol4.68 KB
- contracts/alert/CollateralBalanceValidator.sol3.52 KB
- contracts/alert/DepositaryUpdateValidator.sol1.87 KB
- contracts/alert/IValidator.sol222 B
- contracts/alert/ProtocolValidator.sol5.83 KB
- contracts/chainlink/CrossPriceFeed.sol1.25 KB
- contracts/chainlink/IPriceFeed.sol691 B
- contracts/chainlink/PriceFeedMock.sol1.68 KB
- contracts/curve/ILiquidityGauge.sol376 B
- contracts/curve/IMinter.sol270 B
- contracts/curve/IPool.sol375 B
- contracts/curve/IRegistry.sol256 B
- contracts/depositary/AgregateDepositaryBalanceView.sol3.72 KB
- contracts/depositary/BuybackDepositaryBalanceView.sol4.05 KB
- contracts/depositary/CompoundDepositaryBalanceView.sol4.65 KB
- contracts/depositary/CurveDepositaryBalanceView.sol9.68 KB
- contracts/depositary/DepositorCollateral.sol3.69 KB
- contracts/depositary/IDepositaryBalanceView.sol439 B
- contracts/depositary/IUpdatable.sol209 B
- contracts/depositary/RealAssetDepositaryBalanceView.sol4.12 KB
- contracts/depositary/StableTokenDepositaryBalanceView.sol2.83 KB
- contracts/mocks/MockERC20.sol616 B
- contracts/profit/Buyback.sol4.63 KB
- contracts/profit/ProfitSplitter.sol9.13 KB
- contracts/profit/UniswapMarketMaker.sol7.78 KB
- contracts/uniswap/IUniswapAnchoredView.sol164 B
- contracts/uniswap/IUniswapV2Factory.sol705 B
- contracts/uniswap/IUniswapV2Pair.sol2.45 KB
- contracts/uniswap/IUniswapV2Router02.sol5.41 KB
- contracts/utils/AccessControl.sol1.73 KB
- contracts/utils/OwnablePausable.sol1.24 KB
contracts/Staking.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./utils/OwnablePausable.sol";
contract Staking is OwnablePausable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice Address of rewards distributor.
address public rewardsDistribution;
/// @notice Rewards token address.
IERC20 public rewardsToken;
/// @notice Staking token address.
IERC20 public stakingToken;
/// @notice Block number of rewards distibution period finish.
uint256 public periodFinish;
/// @notice Reward distribution amount per block.
uint256 public rewardRate;
/// @notice Blocks count in current distribution period.
uint256 public rewardsDuration;
/// @notice Block number of last update.
uint256 public lastUpdateBlock;
/// @notice Static reward distribution amount per block.
uint256 public rewardPerTokenStored;
/// @notice Staking completion block number.
uint256 public stakingEndBlock;
/// @notice Unstaking start block number.
uint256 public unstakingStartBlock;
/// @notice Rewards paid.
mapping(address => uint256) public userRewardPerTokenPaid;
/// @notice Earned rewards.
mapping(address => uint256) public rewards;
/// @dev Total staking token amount.
uint256 internal _totalSupply;
/// @dev Staking balances.
mapping(address => uint256) internal _balances;
/// @notice An event thats emitted when an reward token addet to contract.
event RewardAdded(uint256 reward);
/// @notice An event thats emitted when an staking token added to contract.
event Staked(address indexed user, uint256 amount);
/// @notice An event thats emitted when an staking token withdrawal from contract.
event Withdrawn(address indexed user, uint256 amount);
/// @notice An event thats emitted when an reward token withdrawal from contract.
event RewardPaid(address indexed user, uint256 reward);
/// @notice An event thats emitted when an rewards distribution address changed.
event RewardsDistributionChanged(address newRewardsDistribution);
/// @notice An event thats emitted when an rewards tokens transfered to recipient.
event RewardsTransfered(address recipient, uint256 amount);
/// @notice An event thats emitted when an staking end block number changed.
event StakingEndBlockChanged(uint256 newBlockNumber);
/// @notice An event thats emitted when an unstaking start block number changed.
event UnstakingStartBlockChanged(uint256 newBlockNumber);
/**
* @param _rewardsDistribution Rewards distribution address.
* @param _rewardsDuration Duration of distribution.
* @param _rewardsToken Address of reward token.
* @param _stakingToken Address of staking token.
*/
constructor(
address _rewardsDistribution,
uint256 _rewardsDuration,
address _rewardsToken,
address _stakingToken,
uint256 _stakingEndBlock,
uint256 _unstakingStartBlock
) public {
rewardsDistribution = _rewardsDistribution;
rewardsDuration = _rewardsDuration;
rewardsToken = IERC20(_rewardsToken);
stakingToken = IERC20(_stakingToken);
stakingEndBlock = _stakingEndBlock;
unstakingStartBlock = _unstakingStartBlock;
}
/**
* @notice Update target account rewards state.
* @param account Target account.
*/
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateBlock = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
/**
* @return Total staking token amount.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @param account Target account.
* @return Staking token amount.
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
/**
* @return Block number of last reward.
*/
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.number, periodFinish);
}
/**
* @return Reward per token.
*/
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return rewardPerTokenStored.add(lastTimeRewardApplicable().sub(lastUpdateBlock).mul(rewardRate).mul(1e18).div(_totalSupply));
}
/**
* @param account Target account.
* @return Earned rewards.
*/
function earned(address account) public view returns (uint256) {
return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]);
}
/**
* @return Rewards amount for duration.
*/
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
/**
* @notice Stake token.
* @param amount Amount staking token.
*/
function stake(uint256 amount) external nonReentrant updateReward(_msgSender()) {
require(amount > 0, "Staking::stake: cannot stake 0");
if (stakingEndBlock > 0) {
require(block.number < stakingEndBlock, "Staking:stake: staking completed");
}
_totalSupply = _totalSupply.add(amount);
_balances[_msgSender()] = _balances[_msgSender()].add(amount);
stakingToken.safeTransferFrom(_msgSender(), address(this), amount);
emit Staked(_msgSender(), amount);
}
/**
* @notice Withdraw staking token.
* @param amount Amount withdraw token.
*/
function withdraw(uint256 amount) public nonReentrant updateReward(_msgSender()) {
require(amount > 0, "Staking::withdraw: Cannot withdraw 0");
require(block.number >= unstakingStartBlock, "Staking:withdraw: unstaking not started");
_totalSupply = _totalSupply.sub(amount);
_balances[_msgSender()] = _balances[_msgSender()].sub(amount);
stakingToken.safeTransfer(_msgSender(), amount);
emit Withdrawn(_msgSender(), amount);
}
/**
* @notice Withdraw reward token.
*/
function getReward() public nonReentrant updateReward(_msgSender()) {
uint256 reward = rewards[_msgSender()];
if (reward > 0) {
rewards[_msgSender()] = 0;
rewardsToken.safeTransfer(_msgSender(), reward);
emit RewardPaid(_msgSender(), reward);
}
}
/**
* @notice Withdraw reward and staking token.
*/
function exit() external {
withdraw(_balances[_msgSender()]);
getReward();
}
/**
* @notice Change rewards distribution address.
* @param _rewardDistribution New rewards distribution address.
*/
function changeRewardsDistribution(address _rewardDistribution) external onlyOwner {
rewardsDistribution = _rewardDistribution;
emit RewardsDistributionChanged(rewardsDistribution);
}
/**
* @notice Transfer rewards token to recipient if distribution not start.
* @param recipient Recipient.
* @param amount Amount transfered rewards token.
*/
function transfer(address recipient, uint256 amount) external onlyOwner {
require(block.number >= periodFinish, "Staking::transfer: distribution not ended");
rewardsToken.safeTransfer(recipient, amount);
emit RewardsTransfered(recipient, amount);
}
/**
* @notice Change staking end block number.
* @param _stakingEndBlock New staking end block number.
*/
function changeStakingEndBlock(uint256 _stakingEndBlock) external onlyOwner {
stakingEndBlock = _stakingEndBlock;
emit StakingEndBlockChanged(stakingEndBlock);
}
/**
* @notice Change unstaking start block number.
* @param _unstakingStartBlock New unstaking start block number.
*/
function changeUnstakingStartBlock(uint256 _unstakingStartBlock) external onlyOwner {
unstakingStartBlock = _unstakingStartBlock;
emit UnstakingStartBlockChanged(unstakingStartBlock);
}
/**
* @notice Start distribution.
* @param reward Distributed rewards amount.
*/
function notifyRewardAmount(uint256 reward) external updateReward(address(0)) {
require(_msgSender() == rewardsDistribution || _msgSender() == owner(), "Staking::notifyRewardAmount: caller is not RewardsDistribution or Owner address");
if (block.number >= periodFinish) {
rewardRate = reward.div(rewardsDuration);
} else {
uint256 remaining = periodFinish.sub(block.number);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(rewardsDuration);
}
uint256 balance = rewardsToken.balanceOf(address(this));
require(rewardRate <= balance.div(rewardsDuration), "Staking::notifyRewardAmount: provided reward too high");
lastUpdateBlock = block.number;
periodFinish = block.number.add(rewardsDuration);
emit RewardAdded(reward);
}
}
@openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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 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 Context {
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;
}
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../GSN/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.
*/
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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = 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");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
@openzeppelin/contracts/math/Math.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @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, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
@openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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 SafeMath {
/**
* @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) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* 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);
uint256 c = a - b;
return c;
}
/**
* @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) {
// 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 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts 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) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts 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) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
@openzeppelin/contracts/math/SignedSafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed integers. Reverts 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(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
@openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.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 ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
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.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view 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 returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view 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 {
_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 { }
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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);
}
@openzeppelin/contracts/token/ERC20/SafeERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.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 SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
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'
// 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(IERC20 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(IERC20 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(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");
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");
}
}
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in 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");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
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);
}
}
}
}
@openzeppelin/contracts/utils/EnumerableSet.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// 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];
}
// 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(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(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(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(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));
}
}
@openzeppelin/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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].
*/
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 () internal {
_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 make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
contracts/Budget.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "./utils/OwnablePausable.sol";
contract Budget is OwnablePausable {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/// @dev Expenditure item.
struct Expenditure {
address recipient;
uint256 min;
uint256 target;
}
/// @notice Expenditure item to address.
mapping(address => Expenditure) public expenditures;
/// @dev Recipients addresses list.
EnumerableSet.AddressSet internal recipients;
/// @notice An event emitted when expenditure item changed.
event ExpenditureChanged(address recipient, uint256 min, uint256 target);
/// @notice An event emitted when expenditure item payed.
event Payed(address recipient, uint256 amount);
receive() external payable {}
/**
* @notice Change expenditure item.
* @param recipient Recipient address.
* @param min Minimal balance for payment.
* @param target Target balance.
*/
function changeExpenditure(
address recipient,
uint256 min,
uint256 target
) external onlyOwner {
require(min <= target, "Budget::changeExpenditure: minimal balance should be less or equal target balance");
expenditures[recipient] = Expenditure(recipient, min, target);
if (target > 0) {
recipients.add(recipient);
} else {
recipients.remove(recipient);
}
emit ExpenditureChanged(recipient, min, target);
}
/**
* @notice Transfer ETH to recipient.
* @param recipient Recipient.
* @param amount Transfer amount.
*/
function transferETH(address payable recipient, uint256 amount) external onlyOwner returns (bool) {
recipient.transfer(amount);
return true;
}
/**
* @notice Return all recipients addresses.
* @return Recipients addresses.
*/
function getRecipients() external view returns (address[] memory) {
address[] memory result = new address[](recipients.length());
for (uint256 i = 0; i < recipients.length(); i++) {
result[i] = recipients.at(i);
}
return result;
}
/**
* @notice Return balance deficit of recipient.
* @param recipient Target recipient.
* @return Balance deficit of recipient.
*/
function deficitTo(address recipient) public view returns (uint256) {
require(recipients.contains(recipient), "Budget::deficitTo: recipient not in expenditure item");
if (recipient.balance > expenditures[recipient].min) return 0;
return expenditures[recipient].target.sub(recipient.balance);
}
/**
* @notice Return summary balance deficit of all recipients.
* @return Summary balance deficit of all recipients.
*/
function deficit() public view returns (uint256) {
uint256 result;
for (uint256 i = 0; i < recipients.length(); i++) {
result = result.add(deficitTo(recipients.at(i)));
}
return result;
}
/**
* @notice Pay ETH to all recipients with balance deficit.
*/
function pay() external {
for (uint256 i = 0; i < recipients.length(); i++) {
uint256 balance = address(this).balance;
address recipient = recipients.at(i);
uint256 amount = deficitTo(recipient);
if (amount == 0 || balance < amount) continue;
payable(recipient).transfer(amount);
emit Payed(recipient, amount);
}
}
}
contracts/CollateralMarket.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "./utils/OwnablePausable.sol";
import "./Issuer.sol";
import "./Treasury.sol";
contract CollateralMarket is OwnablePausable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
using EnumerableSet for EnumerableSet.AddressSet;
/// @notice Address of issuer contract.
Issuer public issuer;
/// @notice Address of treasury contract.
Treasury public treasury;
/// @notice Address of depositary contract.
address public depositary;
/// @dev Allowed tokens list.
EnumerableSet.AddressSet private _allowedTokens;
/// @notice An event emitted when token allowed.
event TokenAllowed(address token);
/// @notice An event emitted when token denied.
event TokenDenied(address token);
/// @notice An event thats emitted when an Issuer contract address changed.
event IssuerChanged(address newIssuer);
/// @notice An event thats emitted when an Treasury contract address changed.
event TreasuryChanged(address newTreasury);
/// @notice An event thats emitted when an Depositary contract address changed.
event DepositaryChanged(address newDepositary);
/// @notice An event thats emitted when an account buyed token.
event Buy(address customer, address token, uint256 amount, uint256 buy);
constructor(
address _issuer,
address payable _treasury,
address _depositary
) public {
issuer = Issuer(_issuer);
treasury = Treasury(_treasury);
depositary = _depositary;
}
/**
* @notice Allow token.
* @param token Allowable token.
*/
function allowToken(address token) external onlyOwner {
_allowedTokens.add(token);
emit TokenAllowed(token);
}
/**
* @notice Deny token.
* @param token Denied token.
*/
function denyToken(address token) external onlyOwner {
_allowedTokens.remove(token);
emit TokenDenied(token);
}
/**
* @return Allowed tokens list.
*/
function allowedTokens() external view returns (address[] memory) {
address[] memory result = new address[](_allowedTokens.length());
for (uint256 i = 0; i < _allowedTokens.length(); i++) {
result[i] = _allowedTokens.at(i);
}
return result;
}
/**
* @notice Change Issuer contract address.
* @param _issuer New address Issuer contract.
*/
function changeIssuer(address _issuer) external onlyOwner {
issuer = Issuer(_issuer);
emit IssuerChanged(_issuer);
}
/**
* @notice Change Treasury contract address.
* @param _treasury New address Treasury contract.
*/
function changeTreasury(address payable _treasury) external onlyOwner {
treasury = Treasury(_treasury);
emit TreasuryChanged(_treasury);
}
/**
* @notice Change Depositary contract address.
* @param _depositary New address Depositary contract.
*/
function changeDepositary(address _depositary) external onlyOwner {
require(issuer.hasDepositary(_depositary), "CollateralMarket::changeDepositary: collateral depositary is not allowed");
depositary = _depositary;
emit DepositaryChanged(depositary);
}
/**
* @notice Buy stable token with ERC20 payment token amount.
* @param token Payment token.
* @param amount Amount of payment token.
*/
function buy(ERC20 token, uint256 amount) external whenNotPaused {
require(_allowedTokens.contains(address(token)), "CollateralMarket::buy: token is not allowed");
require(issuer.hasDepositary(depositary), "CollateralMarket::buy: collateral depositary is not allowed");
token.safeTransferFrom(_msgSender(), address(this), amount);
token.transfer(depositary, amount);
ERC20 stableToken = ERC20(issuer.stableToken());
uint256 stableTokenDecimals = stableToken.decimals();
uint256 tokenDecimals = token.decimals();
uint256 reward = amount.mul(10**(stableTokenDecimals.sub(tokenDecimals)));
issuer.rebalance();
treasury.transfer(address(stableToken), _msgSender(), reward);
emit Buy(_msgSender(), address(token), amount, reward);
}
}
contracts/GovernanceToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
contract GovernanceToken is IERC20, Ownable {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/// @notice EIP-20 token name for this token
string public name = "BondAppetit Governance";
/// @notice EIP-20 token symbol for this token
string public symbol = "BAG";
/// @notice EIP-20 token decimals for this token
uint8 public decimals = 18;
/// @notice Total number of tokens in circulation
uint256 public override totalSupply = 100000000e18; // 100 million tokens
/// @dev Allowance amounts on behalf of others
mapping(address => mapping(address => uint96)) internal allowances;
/// @dev Official record of token balances for each account
mapping(address => uint96) internal balances;
/// @notice Amount of blocked token
struct Lock {
uint96 amount;
uint256 date;
}
/// @notice Locking amounts
mapping(address => Lock) public locking;
/// @dev Locking amounts
EnumerableSet.AddressSet internal lockingAllowed;
/// @notice A record of each accounts delegate
mapping(address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external override view returns (uint256) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 rawAmount) external override returns (bool) {
uint96 amount;
if (rawAmount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "GovernanceToken::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external override view returns (uint256) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 rawAmount) external override returns (bool) {
uint96 amount = safe96(rawAmount, "GovernanceToken::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 rawAmount
) external override returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "GovernanceToken::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "GovernanceToken::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Add account to transfer lock method allowed list
* @param account Allowable account
*/
function allowTransferLock(address account) external onlyOwner returns (bool) {
return lockingAllowed.add(account);
}
/**
* @notice Remove account from transfer lock method allowed list
* @param account Denied account
*/
function denyTransferLock(address account) external onlyOwner returns (bool) {
return lockingAllowed.remove(account);
}
function transferLock(address dst, uint256 rawAmount, uint256 date) external returns (bool) {
require(lockingAllowed.contains(msg.sender), "GovernanceToken::transferLock: access is denied");
require(locking[dst].date == 0 || locking[dst].date == date, "GovernanceToken::transferLock: lock date cannot be changed");
uint96 amount = safe96(rawAmount, "GovernanceToken::transferLock: amount exceeds 96 bits");
locking[dst].date = date;
locking[dst].amount = add96(locking[dst].amount, amount, "GovernanceToken::transferLock: transfer amount overflows");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* @param account Recipient of created token.
* @param amount Amount of token to be created.
*/
function mint(address account, uint256 amount) public onlyOwner {
_mint(account, amount);
}
/**
* @param account Owner of removed token.
* @param amount Amount of token to be removed.
*/
function burn(address account, uint256 amount) public onlyOwner {
_burn(account, amount);
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernanceToken::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "GovernanceToken::delegateBySig: invalid nonce");
require(now <= expiry, "GovernanceToken::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "GovernanceToken::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(
address src,
address dst,
uint96 amount
) internal {
require(src != address(0), "GovernanceToken::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "GovernanceToken::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "GovernanceToken::_transferTokens: transfer amount exceeds balance");
if (locking[src].date > block.timestamp && locking[src].amount > 0 && balances[src] < locking[src].amount) {
revert("GovernanceToken::_transferTokens: amount are locked");
}
balances[dst] = add96(balances[dst], amount, "GovernanceToken::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint96 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "GovernanceToken::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "GovernanceToken::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber = safe32(block.number, "GovernanceToken::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
/** @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 rawAmount) internal virtual {
require(account != address(0), "GovernanceToken::_mint: mint to the zero address");
uint96 amount = safe96(rawAmount, "GovernanceToken::_mint: amount exceeds 96 bits");
totalSupply = totalSupply.add(rawAmount);
balances[account] = add96(balances[account], amount, "GovernanceToken::_mint: mint amount overflows");
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 rawAmount) internal virtual {
require(account != address(0), "GovernanceToken::_burn: burn from the zero address");
uint96 amount = safe96(rawAmount, "GovernanceToken::_burn: amount exceeds 96 bits");
balances[account] = sub96(balances[account], amount, "GovernanceToken::_burn: burn amount exceeds balance");
totalSupply = totalSupply.sub(rawAmount);
emit Transfer(account, address(0), amount);
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
contracts/GovernorAlpha.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract GovernorAlpha {
/// @notice The name of this contract
string public constant name = "BondAppetit Governor Alpha";
/// @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
function quorumVotes() public pure returns (uint256) {
return 4000000e18;
} // 4,000,000 = 4% of governance token
/// @notice The number of votes required in order for a voter to become a proposer
function proposalThreshold() public pure returns (uint256) {
return 1000000e18;
} // 1,000,000 = 1% of governance token
/// @notice The maximum number of actions that can be included in a proposal
function proposalMaxOperations() public pure returns (uint256) {
return 10;
} // 10 actions
/// @notice The delay before voting on a proposal may take place, once proposed
function votingDelay() public pure returns (uint256) {
return 1;
} // 1 block
/// @notice The duration of voting on a proposal, in blocks
function votingPeriod() public pure returns (uint256) {
return 10;
} // ~3 days in blocks (assuming 15s blocks)
/// @notice The address of the Timelock contract
TimelockInterface public timelock;
/// @notice The address of the governance token
GovernanceTokenInterface public governanceToken;
/// @notice The address of the Governor Guardian
address public guardian;
/// @notice The total number of proposals
uint256 public proposalCount;
struct Proposal {
// Unique id for looking up a proposal
uint256 id;
// Creator of the proposal
address proposer;
// The timestamp that the proposal will be available for execution, set once the vote succeeds
uint256 eta;
// the ordered list of target addresses for calls to be made
address[] targets;
// The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint256[] values;
// 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;
// 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 canceled
bool canceled;
// 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 voter
struct Receipt {
// Whether or not a vote has been cast
bool hasVoted;
// Whether or not the voter supports the proposal
bool support;
// The number of votes the voter had, which were cast
uint96 votes;
}
/// @notice Possible states that a proposal may be in
enum ProposalState {Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed}
/// @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 The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)");
/// @notice An event emitted when a new proposal is created
event ProposalCreated(uint256 id, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description);
/// @notice An event emitted when a vote has been cast on a proposal
event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes);
/// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(uint256 id);
/// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint256 id, uint256 eta);
/// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint256 id);
constructor(
address _timelock,
address _governanceToken,
address _guardian
) public {
timelock = TimelockInterface(_timelock);
governanceToken = GovernanceTokenInterface(_governanceToken);
guardian = _guardian;
}
function propose(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
string memory description
) public returns (uint256) {
require(governanceToken.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch");
require(targets.length != 0, "GovernorAlpha::propose: must provide actions");
require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions");
uint256 latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal");
}
uint256 startBlock = add256(block.number, votingDelay());
uint256 endBlock = add256(startBlock, votingPeriod());
proposalCount++;
Proposal memory newProposal = Proposal({
id: proposalCount,
proposer: msg.sender,
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: startBlock,
endBlock: endBlock,
forVotes: 0,
againstVotes: 0,
canceled: false,
executed: false
});
proposals[newProposal.id] = newProposal;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return newProposal.id;
}
function queue(uint256 proposalId) public {
require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
uint256 eta = add256(block.timestamp, timelock.delay());
for (uint256 i = 0; i < proposal.targets.length; i++) {
_queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function _queueOrRevert(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) internal {
require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta");
timelock.queueTransaction(target, value, signature, data, eta);
}
function execute(uint256 proposalId) public payable {
require(state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction{value: proposal.values[i]}(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
function cancel(uint256 proposalId) public {
ProposalState state = state(proposalId);
require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(msg.sender == guardian || governanceToken.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha::cancel: proposer above threshold");
proposal.canceled = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
function getActions(uint256 proposalId)
public
view
returns (
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas
)
{
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
function getReceipt(uint256 proposalId, address voter) public view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
function state(uint256 proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else 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 < quorumVotes()) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
function castVote(uint256 proposalId, bool support) public {
return _castVote(msg.sender, proposalId, support);
}
function castVoteBySig(
uint256 proposalId,
bool support,
uint8 v,
bytes32 r,
bytes32 s
) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernorAlpha::castVoteBySig: invalid signature");
return _castVote(signatory, proposalId, support);
}
function _castVote(
address voter,
uint256 proposalId,
bool support
) internal {
require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted");
uint96 votes = governanceToken.getPriorVotes(voter, proposal.startBlock);
if (support) {
proposal.forVotes = add256(proposal.forVotes, votes);
} else {
proposal.againstVotes = add256(proposal.againstVotes, votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
emit VoteCast(voter, proposalId, support, votes);
}
function __acceptAdmin() public {
require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian");
timelock.acceptAdmin();
}
function __abdicate() public {
require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian");
guardian = address(0);
}
function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public {
require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian");
timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public {
require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian");
timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function add256(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "addition overflow");
return c;
}
function sub256(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "subtraction underflow");
return a - b;
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
interface TimelockInterface {
function delay() external view returns (uint256);
function GRACE_PERIOD() external view returns (uint256);
function acceptAdmin() external;
function queuedTransactions(bytes32 hash) external view returns (bool);
function queueTransaction(
address target,
uint256 value,
string calldata signature,
bytes calldata data,
uint256 eta
) external returns (bytes32);
function cancelTransaction(
address target,
uint256 value,
string calldata signature,
bytes calldata data,
uint256 eta
) external;
function executeTransaction(
address target,
uint256 value,
string calldata signature,
bytes calldata data,
uint256 eta
) external payable returns (bytes memory);
}
interface GovernanceTokenInterface {
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96);
}
contracts/Investment.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "./utils/OwnablePausable.sol";
import "./uniswap/IUniswapV2Router02.sol";
import "./GovernanceToken.sol";
contract Investment is OwnablePausable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
using EnumerableSet for EnumerableSet.AddressSet;
///@notice Address of cumulative token
ERC20 public cumulative;
///@notice Address of governance token
GovernanceToken public governanceToken;
///@notice Date of locking governance token
uint256 public governanceTokenLockDate;
uint8 internal constant GOVERNANCE_TOKEN_PRICE_DECIMALS = 6;
///@notice Price governance token
uint256 public governanceTokenPrice;
///@dev Address of UniswapV2Router
IUniswapV2Router02 internal uniswapRouter;
/// @dev Allowed tokens list.
EnumerableSet.AddressSet private _allowedTokens;
/// @notice An event thats emitted when an uniswap router contract address changed.
event UniswapRouterChanged(address newUniswapRouter);
/// @notice An event thats emitted when an invest token allowed.
event InvestTokenAllowed(address token);
/// @notice An event thats emitted when an invest token denied.
event InvestTokenDenied(address token);
/// @notice An event thats emitted when an governance token price changed.
event GovernanceTokenPriceChanged(uint256 newPrice);
/// @notice An event thats emitted when an governance token lock date changed.
event GovernanceTokenLockDateChanged(uint256 newLockDate);
/// @notice An event thats emitted when an invested token.
event Invested(address investor, address token, uint256 amount, uint256 reward);
/// @notice An event thats emitted when an withdrawal token.
event Withdrawal(address recipient, address token, uint256 amount);
/**
* @param _cumulative Address of cumulative token
* @param _governanceToken Address of governance token
* @param _governanceTokenLockDate Lock date of governance token
* @param _governanceTokenPrice Governance token price
* @param _uniswapRouter Address of UniswapV2Router
*/
constructor(
address _cumulative,
address _governanceToken,
uint256 _governanceTokenLockDate,
uint256 _governanceTokenPrice,
address _uniswapRouter
) public {
cumulative = ERC20(_cumulative);
governanceToken = GovernanceToken(_governanceToken);
governanceTokenLockDate = _governanceTokenLockDate;
governanceTokenPrice = _governanceTokenPrice;
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
}
/**
* @notice Changed uniswap router contract address.
* @param _uniswapRouter Address new uniswap router contract.
*/
function changeUniswapRouter(address _uniswapRouter) external onlyOwner {
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
emit UniswapRouterChanged(_uniswapRouter);
}
/**
* @notice Add token to investable tokens white list
* @param token Allowable token
*/
function allowToken(address token) external onlyOwner {
_allowedTokens.add(token);
emit InvestTokenAllowed(token);
}
/**
* @notice Remove token from investable tokens white list
* @param token Denied token
*/
function denyToken(address token) external onlyOwner {
_allowedTokens.remove(token);
emit InvestTokenDenied(token);
}
/**
* @return Allowed tokens list.
*/
function allowedTokens() external view returns (address[] memory) {
address[] memory result = new address[](_allowedTokens.length());
for (uint256 i = 0; i < _allowedTokens.length(); i++) {
result[i] = _allowedTokens.at(i);
}
return result;
}
/**
* @notice Update governance token price
* @param newPrice New price of governance token of USD (6 decimal)
*/
function changeGovernanceTokenPrice(uint256 newPrice) external onlyOwner {
require(newPrice > 0, "Investment::changeGovernanceTokenPrice: invalid new governance token price");
governanceTokenPrice = newPrice;
emit GovernanceTokenPriceChanged(newPrice);
}
/**
* @notice Update governance token lock date.
* @param _governanceTokenLockDate New lock date of governance token.
*/
function changeGovernanceTokenLockDate(uint256 _governanceTokenLockDate) external onlyOwner {
governanceTokenLockDate = _governanceTokenLockDate;
emit GovernanceTokenLockDateChanged(governanceTokenLockDate);
}
/**
* @param token Invested token
* @return Pools for each consecutive pair of addresses must exist and have liquidity
*/
function _path(address token) internal view returns (address[] memory) {
address weth = uniswapRouter.WETH();
if (weth == token) {
address[] memory path = new address[](2);
path[0] = token;
path[1] = address(cumulative);
return path;
}
address[] memory path = new address[](3);
path[0] = token;
path[1] = weth;
path[2] = address(cumulative);
return path;
}
/**
* @param token Invested token
* @param amount Invested amount
* @return Amount cumulative token after swap
*/
function _amountOut(address token, uint256 amount) internal view returns (uint256) {
uint256[] memory amountsOut = uniswapRouter.getAmountsOut(amount, _path(token));
require(amountsOut.length != 0, "Investment::_amountOut: invalid amounts out length");
return amountsOut[amountsOut.length - 1];
}
/**
* @param amount Cumulative amount invested
* @return Amount governance token after swap
*/
function _governanceTokenPrice(uint256 amount) internal view returns (uint256) {
uint256 decimals = cumulative.decimals();
return amount.mul(10**(18 - decimals + GOVERNANCE_TOKEN_PRICE_DECIMALS)).div(governanceTokenPrice);
}
/**
* @param token Invested token
* @param amount Invested amount
* @return Amount governance token after swap
*/
function price(address token, uint256 amount) external view returns (uint256) {
require(_allowedTokens.contains(token), "Investment::price: invalid investable token");
uint256 amountOut = amount;
if (token != address(cumulative)) {
amountOut = _amountOut(token, amount);
}
return _governanceTokenPrice(amountOut);
}
/**
* @notice Invest tokens to protocol
* @param token Invested token
* @param amount Invested amount
*/
function invest(address token, uint256 amount) external whenNotPaused returns (bool) {
require(_allowedTokens.contains(token), "Investment::invest: invalid investable token");
uint256 reward = _governanceTokenPrice(amount);
ERC20(token).safeTransferFrom(_msgSender(), address(this), amount);
if (token != address(cumulative)) {
uint256 amountOut = _amountOut(token, amount);
require(amountOut != 0, "Investment::invest: liquidity pool is empty");
reward = _governanceTokenPrice(amountOut);
ERC20(token).safeApprove(address(uniswapRouter), amount);
uniswapRouter.swapExactTokensForTokens(amount, amountOut, _path(token), address(this), block.timestamp);
}
governanceToken.transferLock(_msgSender(), reward, governanceTokenLockDate);
emit Invested(_msgSender(), token, amount, reward);
return true;
}
/**
* @notice Invest ETH to protocol
*/
function investETH() external payable whenNotPaused returns (bool) {
address token = uniswapRouter.WETH();
require(_allowedTokens.contains(token), "Investment::investETH: invalid investable token");
uint256 reward = _governanceTokenPrice(msg.value);
if (token != address(cumulative)) {
uint256 amountOut = _amountOut(token, msg.value);
require(amountOut != 0, "Investment::invest: liquidity pool is empty");
reward = _governanceTokenPrice(amountOut);
uniswapRouter.swapExactETHForTokens{value: msg.value}(amountOut, _path(token), address(this), block.timestamp);
}
governanceToken.transferLock(_msgSender(), reward, governanceTokenLockDate);
emit Invested(_msgSender(), token, msg.value, reward);
return true;
}
/**
* @notice Withdraw invested token to address
* @param recipient Recipient of tokens
*/
function withdraw(address recipient) external onlyOwner {
require(recipient != address(0), "Investment::withdraw: cannot transfer to the zero address");
uint256 balance = cumulative.balanceOf(address(this));
cumulative.safeTransfer(recipient, balance);
emit Withdrawal(recipient, address(cumulative), balance);
}
}
contracts/Issuer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./depositary/AgregateDepositaryBalanceView.sol";
import "./StableToken.sol";
contract Issuer is AgregateDepositaryBalanceView {
using Math for uint256;
using SafeMath for uint256;
/// @notice Stable token contract address.
StableToken public stableToken;
/// @notice Treasury contract address.
address public treasury;
/// @notice An event thats emitted when an Treasury contract transfered.
event TransferTreasury(address newTreasury);
/// @notice An event thats emitted when an stable token total supply rebalanced.
event Rebalance();
/**
* @param _stableToken Stable token contract address.
* @param _treasury Treasury contract address.
*/
constructor(address _stableToken, address _treasury) public AgregateDepositaryBalanceView(StableToken(_stableToken).decimals(), 50) {
stableToken = StableToken(_stableToken);
treasury = _treasury;
}
/**
* @notice Transfer Treasury contract to new address.
* @param _treasury New address Treasury contract.
*/
function changeTreasury(address _treasury) external onlyOwner {
treasury = _treasury;
emit TransferTreasury(treasury);
}
/**
* @notice Change owner of Stable token contract.
* @param _owner New owner address.
*/
function changeStableTokenOwner(address _owner) external onlyOwner {
stableToken.transferOwnership(_owner);
}
/**
* @notice Rebalance stable token total supply by depositary balance. Mint stable token if depositary balance greater token total supply and burn otherwise.
*/
function rebalance() external whenNotPaused {
uint256 currentDepositaryBalance = this.balance();
uint256 stableTokenTotalSupply = stableToken.totalSupply();
if (stableTokenTotalSupply > currentDepositaryBalance) {
uint256 burningBalance = stableToken.balanceOf(address(this));
if (burningBalance > 0) {
stableToken.burn(address(this), burningBalance.min(stableTokenTotalSupply.sub(currentDepositaryBalance)));
emit Rebalance();
}
} else if (stableTokenTotalSupply < currentDepositaryBalance) {
stableToken.mint(treasury, currentDepositaryBalance.sub(stableTokenTotalSupply));
emit Rebalance();
}
}
}
contracts/Market.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./utils/OwnablePausable.sol";
import "./uniswap/IUniswapV2Router02.sol";
import "./uniswap/IUniswapAnchoredView.sol";
contract Market is OwnablePausable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
uint256 public constant PRICE_DECIMALS = 6;
uint256 public constant REWARD_DECIMALS = 12;
/// @notice Address of cumulative token.
ERC20 public cumulative;
/// @notice Address of product token contract.
ERC20 public productToken;
/// @notice Address of reward token contract.
ERC20 public rewardToken;
/// @dev Address of UniswapV2Router.
IUniswapV2Router02 public uniswapRouter;
/// @dev Address of IUniswapAnchoredView.
IUniswapAnchoredView public priceOracle;
/// @dev Allowed tokens symbols list.
mapping(address => string) internal allowedTokens;
/// @notice An event thats emitted when an price oracle contract address changed.
event PriceOracleChanged(address newPriceOracle);
/// @notice An event thats emitted when an uniswap router contract address changed.
event UniswapRouterChanged(address newUniswapRouter);
/// @notice An event thats emitted when an cumulative token changed.
event CumulativeChanged(address newToken);
/// @notice An event thats emitted when an token allowed.
event TokenAllowed(address token, string symbol);
/// @notice An event thats emitted when an token denied.
event TokenDenied(address token);
/// @notice An event thats emitted when an account buyed token.
event Buy(address customer, address token, uint256 amount, uint256 buy, uint256 reward);
/// @notice An event thats emitted when an cumulative token withdrawal.
event Withdrawal(address recipient, address token, uint256 amount);
/**
* @param _cumulative Address of cumulative token.
* @param _productToken Address of product token.
* @param _rewardToken Address of reward token.
* @param _uniswapRouter Address of Uniswap router contract.
* @param _priceOracle Address of Price oracle contract.
*/
constructor(
address _cumulative,
address _productToken,
address _rewardToken,
address _uniswapRouter,
address _priceOracle
) public {
cumulative = ERC20(_cumulative);
productToken = ERC20(_productToken);
rewardToken = ERC20(_rewardToken);
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
priceOracle = IUniswapAnchoredView(_priceOracle);
}
/**
* @notice Changed uniswap router contract address.
* @param _uniswapRouter Address new uniswap router contract.
*/
function changeUniswapRouter(address _uniswapRouter) external onlyOwner {
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
emit UniswapRouterChanged(_uniswapRouter);
}
/**
* @notice Changed price oracle contract address.
* @param _priceOracle Address new price oracle contract.
*/
function changePriceOracle(address _priceOracle) external onlyOwner {
priceOracle = IUniswapAnchoredView(_priceOracle);
emit PriceOracleChanged(_priceOracle);
}
/**
* @notice Changed cumulative token address.
* @param newToken Address new cumulative token.
* @param recipient Address of recipient for withdraw current cumulative balance.
*/
function changeCumulativeToken(address newToken, address recipient) external onlyOwner {
withdraw(recipient);
cumulative = ERC20(newToken);
emit CumulativeChanged(newToken);
}
/**
* @notice Add token to tokens white list.
* @param token Allowable token.
* @param symbol Symbol target token of price oracle contract.
*/
function allowToken(address token, string calldata symbol) external onlyOwner {
allowedTokens[token] = symbol;
emit TokenAllowed(token, symbol);
}
/**
* @notice Remove token from tokens white list.
* @param token Denied token.
*/
function denyToken(address token) external onlyOwner {
allowedTokens[token] = "";
emit TokenDenied(token);
}
/**
* @param token Target token.
* @return Is target token allowed.
*/
function isAllowedToken(address token) public view returns (bool) {
return bytes(allowedTokens[token]).length != 0;
}
/**
* @dev Transfer token to recipient.
* @param from Address of transfered token contract.
* @param recipient Address of recipient.
* @param amount Amount of transfered token.
*/
function transfer(
ERC20 from,
address recipient,
uint256 amount
) internal {
require(recipient != address(0), "Market::transfer: cannot transfer to the zero address");
uint256 currentBalance = from.balanceOf(address(this));
require(amount <= currentBalance, "Market::transfer: not enough tokens");
from.safeTransfer(recipient, amount);
}
/**
* @notice Transfer product token to recipient.
* @param recipient Address of recipient.
* @param amount Amount of transfered token.
*/
function transferProductToken(address recipient, uint256 amount) external onlyOwner {
transfer(productToken, recipient, amount);
}
/**
* @notice Transfer reward token to recipient.
* @param recipient Address of recipient.
* @param amount Amount of transfered token.
*/
function transferRewardToken(address recipient, uint256 amount) external onlyOwner {
transfer(rewardToken, recipient, amount);
}
/**
* @notice Get token price.
* @param currency Currency token.
* @param payment Amount of payment.
* @return product Amount of product token.
* @return reward Amount of reward token.
*/
function price(address currency, uint256 payment) public view returns (uint256 product, uint256 reward) {
require(isAllowedToken(currency), "Market::price: currency not allowed");
uint256 tokenDecimals = ERC20(currency).decimals();
uint256 productDecimals = productToken.decimals();
uint256 tokenPrice = priceOracle.price(allowedTokens[currency]);
uint256 cumulativePrice = priceOracle.price(cumulative.symbol());
product = payment.mul(10**productDecimals.sub(tokenDecimals));
if (address(productToken) != currency) {
product = tokenPrice.mul(10**PRICE_DECIMALS).div(cumulativePrice).mul(payment).div(10**PRICE_DECIMALS).mul(10**productDecimals.sub(tokenDecimals));
}
uint256 productTokenBalance = productToken.balanceOf(address(this));
if (productTokenBalance > 0) {
uint256 rewardTokenBalance = rewardToken.balanceOf(address(this));
reward = product.mul(10**REWARD_DECIMALS).div(productTokenBalance).mul(rewardTokenBalance).div(10**REWARD_DECIMALS);
}
}
/**
* @param currency Currency token.
* @return Pools for each consecutive pair of addresses must exist and have liquidity
*/
function _path(address currency) internal view returns (address[] memory) {
address weth = uniswapRouter.WETH();
if (weth == currency) {
address[] memory path = new address[](2);
path[0] = currency;
path[1] = address(cumulative);
return path;
}
address[] memory path = new address[](3);
path[0] = currency;
path[1] = weth;
path[2] = address(cumulative);
return path;
}
/**
* @param currency Currency token.
* @param payment Amount of payment.
* @return Amount cumulative token after swap.
*/
function _amountOut(address currency, uint256 payment) internal view returns (uint256) {
uint256[] memory amountsOut = uniswapRouter.getAmountsOut(payment, _path(currency));
require(amountsOut.length != 0, "Market::_amountOut: invalid amounts out length");
return amountsOut[amountsOut.length - 1];
}
/**
* @notice Buy token with ERC20.
* @param currency Currency token.
* @param payment Amount of payment.
* @return True if success.
*/
function buy(address currency, uint256 payment) external whenNotPaused returns (bool) {
(uint256 product, uint256 reward) = price(currency, payment);
uint256 productTokenBalance = productToken.balanceOf(address(this));
require(productTokenBalance > 0 && product <= productTokenBalance, "Market::buy: exceeds balance");
ERC20(currency).safeTransferFrom(_msgSender(), address(this), payment);
if (currency != address(cumulative)) {
uint256 amountOut = _amountOut(currency, payment);
require(amountOut != 0, "Market::buy: liquidity pool is empty");
ERC20(currency).safeApprove(address(uniswapRouter), payment);
uniswapRouter.swapExactTokensForTokens(payment, amountOut, _path(currency), address(this), block.timestamp);
}
productToken.safeTransfer(_msgSender(), product);
if (reward > 0) {
rewardToken.safeTransfer(_msgSender(), reward);
}
emit Buy(_msgSender(), currency, payment, product, reward);
return true;
}
/**
* @notice Buy token with ETH.
* @return True if success.
*/
function buyFromETH() external payable whenNotPaused returns (bool) {
address currency = uniswapRouter.WETH();
uint256 payment = msg.value;
(uint256 product, uint256 reward) = price(currency, payment);
uint256 productTokenBalance = productToken.balanceOf(address(this));
require(product <= productTokenBalance, "Market::buyFromETH: balance is empty");
if (currency != address(cumulative)) {
uint256 amountOut = _amountOut(currency, payment);
require(amountOut != 0, "Market::buyFromETH: liquidity pool is empty");
uniswapRouter.swapExactETHForTokens{value: payment}(amountOut, _path(currency), address(this), block.timestamp);
}
productToken.safeTransfer(_msgSender(), product);
if (reward > 0) {
rewardToken.safeTransfer(_msgSender(), reward);
}
emit Buy(_msgSender(), currency, payment, product, reward);
return true;
}
/**
* @notice Withdraw cumulative token to address.
* @param recipient Recipient of token.
*/
function withdraw(address recipient) public onlyOwner {
require(recipient != address(0), "Market::withdraw: cannot transfer to the zero address");
uint256 balance = cumulative.balanceOf(address(this));
cumulative.safeTransfer(recipient, balance);
emit Withdrawal(recipient, address(cumulative), balance);
}
}
contracts/StableToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./utils/AccessControl.sol";
contract StableToken is ERC20, AccessControl {
/**
* @param initialSupply Total supply.
*/
constructor(uint256 initialSupply) public ERC20("Appetite USD", "USDap") {
_mint(_msgSender(), initialSupply);
}
/**
* @param account Recipient of created token.
* @param amount Amount of token to be created.
*/
function mint(address account, uint256 amount) public onlyAllowed {
_mint(account, amount);
}
/**
* @param account Owner of removed token.
* @param amount Amount of token to be removed.
*/
function burn(address account, uint256 amount) public onlyAllowed {
_burn(account, amount);
}
}
contracts/Timelock.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
contract Timelock {
using SafeMath for uint256;
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint256 indexed newDelay);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta);
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta);
uint256 public constant GRACE_PERIOD = 14 days;
uint256 public constant MINIMUM_DELAY = 0 days;
uint256 public constant MAXIMUM_DELAY = 30 days;
address public admin;
address public pendingAdmin;
uint256 public delay;
mapping(bytes32 => bool) public queuedTransactions;
constructor(address admin_, uint256 delay_) public {
require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
admin = admin_;
delay = delay_;
}
receive() external payable {}
function setDelay(uint256 delay_) public {
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = delay_;
emit NewDelay(delay);
}
function acceptAdmin() public {
require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin.");
admin = msg.sender;
pendingAdmin = address(0);
emit NewAdmin(admin);
}
function setPendingAdmin(address pendingAdmin_) public {
require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock.");
pendingAdmin = pendingAdmin_;
emit NewPendingAdmin(pendingAdmin);
}
function __transferAdmin(address _newAdmin) public {
require(msg.sender == admin, "Timelock::__transferAdmin: caller is not the admin");
admin = _newAdmin;
emit NewAdmin(admin);
}
function queueTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) public returns (bytes32) {
require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin.");
require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QueueTransaction(txHash, target, value, signature, data, eta);
return txHash;
}
function cancelTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) public {
require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = false;
emit CancelTransaction(txHash, target, value, signature, data, eta);
}
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) public payable returns (bytes memory) {
require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued.");
require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock.");
require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale.");
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
(bool success, bytes memory returnData) = target.call{value: value}(callData);
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(txHash, target, value, signature, data, eta);
return returnData;
}
function getBlockTimestamp() internal view returns (uint256) {
return block.timestamp;
}
}
contracts/Treasury.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./utils/AccessControl.sol";
contract Treasury is AccessControl {
using SafeMath for uint256;
using SafeERC20 for ERC20;
receive() external payable {}
/**
* @notice Transfer target token to recipient.
* @param token Target token.
* @param recipient Recipient.
* @param amount Transfer amount.
*/
function transfer(
address token,
address recipient,
uint256 amount
) external onlyAllowed returns (bool) {
ERC20(token).safeTransfer(recipient, amount);
return true;
}
/**
* @notice Transfer ETH to recipient.
* @param recipient Recipient.
* @param amount Transfer amount.
*/
function transferETH(address payable recipient, uint256 amount) external onlyAllowed returns (bool) {
recipient.transfer(amount);
return true;
}
/**
* @notice Approve target token to recipient.
* @param token Target token.
* @param recipient Recipient.
* @param amount Approve amount.
*/
function approve(
address token,
address recipient,
uint256 amount
) external onlyAllowed returns (bool) {
uint256 allowance = ERC20(token).allowance(address(this), recipient);
if (allowance > 0) {
ERC20(token).safeApprove(recipient, 0);
}
ERC20(token).safeApprove(recipient, amount);
return true;
}
}
contracts/Vesting.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./utils/OwnablePausable.sol";
contract Vesting is OwnablePausable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
using EnumerableSet for EnumerableSet.AddressSet;
/// @notice The number of periods for a per recipient.
function maxPeriodsPerRecipient() public pure returns (uint256) {
return 5;
} // 5 perios per recipient.
/// @notice Address of vesting token.
ERC20 public token;
struct Period {
// Identifier.
uint256 id;
// Reward amount.
uint256 amount;
// Unlockd date.
uint256 date;
// Description.
string description;
// Reward withdrawal flag.
bool withdrawal;
}
/// @dev Index last period.
uint256 internal currentPeriod = 0;
/// @dev Participants list.
EnumerableSet.AddressSet internal participants;
/// @dev All registered periods.
mapping(address => mapping(uint256 => Period)) internal periods;
/// @dev Period identifiers index.
mapping(address => uint256[]) internal periodsIndex;
/// @notice An event emitted when all votes delegate to.
event DelegateVotes(address delegatee);
/// @notice An event emitted when locking a period.
event Locked(uint256 periodId);
/// @notice An event emitted when revoked a period.
event Revoked(uint256 periodId);
/// @notice An event emitted when withdrawal a period.
event Withdrawal(address recipient, uint256 periodId);
/**
* @param _token Address of vesting token contract.
*/
constructor(address _token) public {
token = ERC20(_token);
}
/**
* @notice Delegate votes to delegatee.
* @param delegatee The address to delegate votes to
*/
function delegate(address governanceToken, address delegatee) external onlyOwner {
GovernanceTokenInterface(governanceToken).delegate(delegatee);
emit DelegateVotes(delegatee);
}
/**
* @notice Add new period.
* @param recipient Recipient of reward.
* @param amount Reward amount.
* @param date Date of unlockd period.
* @return Added period identifier.
*/
function lock(
address recipient,
uint256 amount,
string memory description,
uint256 date
) external onlyOwner returns (uint256) {
require(periodsIndex[recipient].length <= maxPeriodsPerRecipient(), "Vesting::lock: too many periods");
token.safeTransferFrom(_msgSender(), address(this), amount);
currentPeriod += 1;
participants.add(recipient);
periods[recipient][currentPeriod] = Period(currentPeriod, amount, date, description, false);
periodsIndex[recipient].push(currentPeriod);
emit Locked(currentPeriod);
return currentPeriod;
}
/**
* @notice Revoke period.
* @param recipient Recipient of reward.
* @param periodId Period identifier.
*/
function revoke(address recipient, uint256 periodId) external onlyOwner {
Period storage period = periods[recipient][periodId];
require(!period.withdrawal, "Vesting::revoke: already withdraw");
address owner = _msgSender();
uint256 amount = period.amount;
period.amount = 0;
token.safeTransfer(owner, amount);
emit Revoked(periodId);
}
/**
* @notice Return all participants addresses.
* @return Participants addresses.
*/
function getParticipants() external view returns (address[] memory) {
address[] memory result = new address[](participants.length());
for (uint256 i = 0; i < participants.length(); i++) {
result[i] = participants.at(i);
}
return result;
}
/**
* @notice Get information of period.
* @param recipient Recipient address.
* @return Recipient periods list.
*/
function info(address recipient) external view returns (Period[] memory) {
Period[] memory result = new Period[](periodsIndex[recipient].length);
for (uint256 i = 0; i < periodsIndex[recipient].length; i++) {
uint256 periodId = periodsIndex[recipient][i];
result[i] = periods[recipient][periodId];
}
return result;
}
/**
* @notice Withdraw reward.
* @param periodId Target period identifier.
*/
function withdraw(uint256 periodId) external whenNotPaused {
address recipient = _msgSender();
Period storage period = periods[recipient][periodId];
require(period.amount > 0, "Vesting::withdraw: period is empty");
require(!period.withdrawal, "Vesting::withdraw: already withdraw");
require(block.timestamp > period.date, "Vesting::withdraw: access denied");
period.withdrawal = true;
token.safeTransfer(recipient, period.amount);
emit Withdrawal(recipient, periodId);
}
}
interface GovernanceTokenInterface {
function delegate(address delegatee) external;
}
contracts/VestingSplitter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./Vesting.sol";
contract VestingSplitter is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
/**
* @notice Distributed tokens.
*/
mapping(address => uint256) public totalSupply;
/**
* @dev Accounts balances.
*/
mapping(address => mapping(address => uint256)) internal _balances;
/**
* @dev Accounts list.
*/
address[] internal _accounts;
/**
* @dev Shares of account in split.
*/
mapping(address => uint256) internal _share;
/// @notice An event emitted when shares changed.
event SharesChanged();
/// @notice An event emitted when vesting period withdrawal.
event VestingWithdraw(address vesting, uint256 periodId);
/// @notice An event emitted when split a balance.
event Split(address token);
/// @notice An event emitted when withdrawal a token.
event Withdraw(address token, address account, uint256 reward);
/**
* @notice Get accounts limit for split.
* @return Max accounts for split.
*/
function getMaxAccounts() public pure returns (uint256) {
return 100;
}
/**
* @notice Get accounts with share list.
* @return Addresses of all accounts with share.
*/
function getAccounts() public view returns (address[] memory) {
return _accounts;
}
/**
* @notice Get balance of account.
* @param token Target token.
* @param account Target account.
* @return Balance of account.
*/
function balanceOf(address token, address account) public view returns (uint256) {
return _balances[token][account];
}
/**
* @notice Get share of account in split.
* @param account Target account.
* @return Share in split.
*/
function shareOf(address account) public view returns (uint256) {
return _share[account];
}
/**
* @notice Change shares of accounts in split.
* @param accounts Accounts list.
* @param shares Shares in split.
*/
function changeShares(address[] memory accounts, uint256[] memory shares) external onlyOwner {
require(accounts.length <= getMaxAccounts(), "VestingSplitter::changeShares: too many accounts");
require(accounts.length == shares.length, "VestingSplitter::changeShares: shares function information arity mismatch");
uint256 sharesSum;
for (uint256 i = 0; i < accounts.length; i++) {
address account = accounts[i];
uint256 share = shares[i];
require(share <= 100 && share > 0, "VestingSplitter::changeShares: invalid value of share");
_share[account] = share;
sharesSum = sharesSum.add(share);
}
require(sharesSum == 100, "VestingSplitter::changeShares: invalid sum of shares");
_accounts = accounts;
emit SharesChanged();
}
/**
* @notice Withdraw reward from vesting contract.
* @param vesting Address of vesting contract.
* @param periodId Target vesting period.
*/
function vestingWithdraw(Vesting vesting, uint256 periodId) external {
vesting.withdraw(periodId);
emit VestingWithdraw(address(vesting), periodId);
}
/**
* @notice Split token to all accounts.
* @param token Target token.
*/
function split(address token) external {
uint256 balance = ERC20(token).balanceOf(address(this)).sub(totalSupply[token]);
require(balance > 0, "VestingSplitter::split: empty balance");
for (uint256 i = 0; i < _accounts.length; i++) {
address account = _accounts[i];
uint256 share = _share[account];
uint256 reward = balance.div(100).mul(share);
_balances[token][account] = _balances[token][account].add(reward);
totalSupply[token] = totalSupply[token].add(reward);
}
emit Split(token);
}
/**
* @notice Withdraw token balance to sender.
* @param token Target token.
*/
function withdraw(address token) external {
uint256 reward = _balances[token][_msgSender()];
_balances[token][_msgSender()] = 0;
totalSupply[token] = totalSupply[token].sub(reward);
ERC20(token).safeTransfer(_msgSender(), reward);
emit Withdraw(token, _msgSender(), reward);
}
}
contracts/alert/CollateralBalanceValidator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../depositary/IDepositaryBalanceView.sol";
import "./IValidator.sol";
contract CollateralBalanceValidator is IValidator, Ownable {
using SafeMath for uint256;
/// @notice Accuracy of permissible imbalance.
uint256 public constant PERMISSIBLE_DECIMALS = 2;
/// @notice Address of stable token.
ERC20 public stableToken;
/// @notice Address of collateral.
IDepositaryBalanceView public collateral;
/// @notice Permissible imbalance of stable token total supply and collateral balance.
uint256 public permissibleImbalance;
/// @notice An event thats emitted when stable token address updated.
event StableTokenUpdated(address newStableToken);
/// @notice An event thats emitted when collateral address updated.
event CollateralUpdated(address newCollateral);
/// @notice An event thats emitted when permissible imbalance updated.
event PermissibleImbalanceUpdated(uint256 newPermissibleImbalance);
/**
* @param _stableToken Address of stable token.
* @param _collateral Address of collateral.
* @param _permissibleImbalance Permissible imbalance of stable token total supply and collateral balance.
*/
constructor(
address _stableToken,
address _collateral,
uint256 _permissibleImbalance
) public {
stableToken = ERC20(_stableToken);
collateral = IDepositaryBalanceView(_collateral);
permissibleImbalance = _permissibleImbalance;
}
/**
* @param _stableToken New stable token address.
*/
function changeStableToken(address _stableToken) external onlyOwner {
require(_stableToken != address(0), "CollateralBalanceValidator::changeStableToken: invalid stable token address");
stableToken = ERC20(_stableToken);
emit StableTokenUpdated(_stableToken);
}
/**
* @param _collateral New collateral address.
*/
function changeCollateral(address _collateral) external onlyOwner {
require(_collateral != address(0), "CollateralBalanceValidator::changeCollateral: invalid collateral address");
collateral = IDepositaryBalanceView(_collateral);
emit CollateralUpdated(_collateral);
}
/**
* @param _permissibleImbalance New permissible imbalance value.
*/
function changePermissibleImbalance(uint256 _permissibleImbalance) external onlyOwner {
permissibleImbalance = _permissibleImbalance;
emit PermissibleImbalanceUpdated(_permissibleImbalance);
}
function validate() external view override returns (bool) {
uint256 stableTotalSupply = stableToken.totalSupply();
uint256 stableTokenDecimals = stableToken.decimals();
uint256 collateralBalance = collateral.balance();
uint256 collateralDecimals = collateral.decimals();
if (stableTokenDecimals > collateralDecimals) {
collateralBalance = collateralBalance.mul(10**(stableTokenDecimals - collateralDecimals));
} else if (collateralDecimals > stableTokenDecimals) {
stableTotalSupply = stableTotalSupply.mul(10**(collateralDecimals - stableTokenDecimals));
}
return collateralBalance.mul(10**PERMISSIBLE_DECIMALS).div(stableTotalSupply).add(permissibleImbalance) >= 100;
}
}
contracts/alert/DepositaryUpdateValidator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./IValidator.sol";
import "../depositary/IUpdatable.sol";
contract DepositaryUpdateValidator is IValidator, Ownable {
using SafeMath for uint256;
/// @notice Depositary address.
address public depositary;
/// @notice Number of blocks from current.
uint256 public blockLimit;
/// @notice An event thats emitted when depositary address updated.
event DepositaryUpdated(address newDepositary);
/// @notice An event thats emitted when block limit updated.
event BlockLimitUpdated(uint256 newBlockLimit);
/**
* @param _depositary Depositary address.
* @param _blockLimit Number of blocks from current.
*/
constructor(address _depositary, uint256 _blockLimit) public {
depositary = _depositary;
blockLimit = _blockLimit;
}
/**
* @notice Update depositary address.
* @param _depositary New depositary address.
*/
function changeDepositary(address _depositary) external onlyOwner {
require(_depositary != address(0), "DepositaryUpdateValidator::changeDepositary: invalid depositary address");
depositary = _depositary;
emit DepositaryUpdated(_depositary);
}
/**
* @notice Update block limit.
* @param _blockLimit New block limit.
*/
function changeBlockLimit(uint256 _blockLimit) external onlyOwner {
blockLimit = _blockLimit;
emit BlockLimitUpdated(_blockLimit);
}
function validate() external view override returns (bool) {
uint256 depositaryUpdatedAt = IUpdatable(depositary).lastUpdateBlockNumber();
return depositaryUpdatedAt == 0 || block.number.sub(blockLimit) <= depositaryUpdatedAt;
}
}
contracts/alert/IValidator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IValidator {
/**
* @notice Validate protocol state.
* @return Is state valid.
*/
function validate() external view returns(bool);
}
contracts/alert/ProtocolValidator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../utils/OwnablePausable.sol";
import "./IValidator.sol";
contract ProtocolValidator is Ownable {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/// @notice The number of validators in agregate.
uint256 public maxSize;
/// @dev Protocol contracts list.
EnumerableSet.AddressSet internal protocolContracts;
/// @notice Validator and controlled contract (zero address for all protocol contracts).
mapping(address => address) public validators;
/// @dev Validators list.
EnumerableSet.AddressSet internal validatorsIndex;
/// @notice An event thats emitted when protocol contract added.
event ProtocolContractAdded(address newContract);
/// @notice An event thats emitted when protocol contract removed.
event ProtocolContractRemoved(address removedContract);
/// @notice An event thats emitted when validator added.
event ValidatorAdded(address validator, address controlledContract);
/// @notice An event thats emitted when validator removed.
event ValidatorRemoved(address validator);
/// @notice An event thats emitted when state invalid.
event InvalidState(address validator, address controlledContract);
/**
* @param _maxSize Maximal count of protocol contracts and validators.
*/
constructor(uint256 _maxSize) public {
maxSize = _maxSize;
}
/**
* @return Validators count of agregate.
*/
function size() public view returns (uint256) {
return validatorsIndex.length().add(protocolContracts.length());
}
/**
* @param _contract Protocol contract address.
*/
function addProtocolContract(address _contract) external onlyOwner {
require(_contract != address(0), "ProtocolValidator::addProtocolContract: invalid contract address");
require(protocolContracts.contains(_contract) || size() < maxSize, "ProtocolValidator::addProtocolContract: too many protocol contracts");
protocolContracts.add(_contract);
emit ProtocolContractAdded(_contract);
}
/**
* @param _contract Protocol contract address.
*/
function removeProtocolContract(address _contract) external onlyOwner {
require(_contract != address(0), "ProtocolValidator::removeProtocolContract: invalid contract address");
protocolContracts.remove(_contract);
emit ProtocolContractRemoved(_contract);
}
/**
* @return Addresses of all protocol contracts.
*/
function protocolContractsList() external view returns (address[] memory) {
address[] memory result = new address[](protocolContracts.length());
for (uint256 i = 0; i < protocolContracts.length(); i++) {
result[i] = protocolContracts.at(i);
}
return result;
}
/**
* @param validator Validator address.
* @param controlledContract Pausable contract address (zero address for all protocol contracts).
*/
function addValidator(address validator, address controlledContract) external onlyOwner {
require(validator != address(0), "ProtocolValidator::addValidator: invalid validator address");
require(validatorsIndex.contains(validator) || size() < maxSize, "ProtocolValidator::addValidator: too many validators");
validators[validator] = controlledContract;
validatorsIndex.add(validator);
emit ValidatorAdded(validator, controlledContract);
}
/**
* @param validator Validator address.
*/
function removeValidator(address validator) external onlyOwner {
require(validator != address(0), "ProtocolValidator::removeValidator: invalid validator address");
validators[validator] = address(0);
validatorsIndex.remove(validator);
emit ValidatorRemoved(validator);
}
/**
* @return Validators addresses list.
*/
function validatorsList() external view returns (address[] memory) {
address[] memory result = new address[](validatorsIndex.length());
for (uint256 i = 0; i < validatorsIndex.length(); i++) {
result[i] = validatorsIndex.at(i);
}
return result;
}
/**
* @dev Pause contract or all protocol contracts.
* @param controlledContract Paused contract (zero address for all protocol contracts).
*/
function _pause(address controlledContract) internal {
if (controlledContract == address(0)) {
for (uint256 i = 0; i < protocolContracts.length(); i++) {
_pause(protocolContracts.at(i));
}
} else {
OwnablePausable target = OwnablePausable(controlledContract);
address pauser = target.pauser();
require(pauser == address(this), "ProtocolValidator::_pause: target contract not control");
bool paused = target.paused();
if (!paused) {
target.pause();
}
}
}
/**
* @notice Validate protocol state and pause controlled contract if state invalid.
* @param validator Target validator.
* @return Is state valid.
*/
function validate(address validator) external returns (bool) {
require(validatorsIndex.contains(validator), "ProtocolValidator::validate: validator not found");
bool isValid = IValidator(validator).validate();
if (!isValid) {
_pause(validators[validator]);
emit InvalidState(validator, validators[validator]);
}
return isValid;
}
}
contracts/chainlink/CrossPriceFeed.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
import "./IPriceFeed.sol";
library CrossPriceFeed {
using SignedSafeMath for int256;
/**
* @param path Price feeds chain.
* @param amountIn Input amount.
* @return amounts Output amount of all price feeds.
*/
function getAmountsOut(address[] memory path, int256 amountIn) internal view returns (int256[] memory amounts) {
require(path.length > 0, "ChainlinkCrossPriceFeed: invalid path");
amounts = new int256[](path.length + 1);
amounts[0] = amountIn;
for (uint256 i; i < path.length; i++) {
IPriceFeed priceFeed = IPriceFeed(path[i]);
uint8 decimals = priceFeed.decimals();
(, int256 price, , , ) = priceFeed.latestRoundData();
amounts[i + 1] = amounts[i].mul(price).div(int128(10)**decimals);
}
}
/**
* @param path Price feeds chain.
* @param amountIn Input amount.
* @return Output amount of latest price feed.
*/
function getAmountOut(address[] memory path, int256 amountIn) internal view returns (int256) {
return getAmountsOut(path, amountIn)[path.length];
}
}
contracts/chainlink/IPriceFeed.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IPriceFeed {
function decimals() external view returns (uint8);
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function version() external view returns (uint256);
}contracts/chainlink/PriceFeedMock.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IPriceFeed.sol";
contract PriceFeedMock is IPriceFeed {
uint8 override public decimals;
uint256 override public version;
struct Round {
uint80 roundId;
int256 answer;
uint256 startedAt;
uint256 updatedAt;
uint80 answeredInRound;
}
mapping(uint80 => Round) internal _rounds;
uint80 public latestRoundId;
constructor(uint8 _decimals, uint256 _version) public {
decimals = _decimals;
version = _version;
}
function addRound(
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
) public {
_rounds[++latestRoundId] = Round(roundId, answer, startedAt, updatedAt, answeredInRound);
}
function getRoundData(uint80 _roundId)
override
public
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
roundId = _rounds[_roundId].roundId;
answer = _rounds[_roundId].answer;
startedAt = _rounds[_roundId].startedAt;
updatedAt = _rounds[_roundId].updatedAt;
answeredInRound = _rounds[_roundId].answeredInRound;
}
function latestRoundData()
override
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return getRoundData(latestRoundId);
}
}
contracts/curve/ILiquidityGauge.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface ILiquidityGauge {
function minter() external view returns (address);
function crv_token() external view returns (address);
function claimable_tokens(address recipient) external returns (uint256);
function deposit(uint256 amount) external;
function withdraw(uint256 amount) external;
}
contracts/curve/IMinter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IMinter {
function token() external view returns (address);
function minted(address recipient, address gauge) external view returns (uint256);
function mint(address gauge_addr) external;
}
contracts/curve/IPool.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IPool {
function coins(uint256 i) external view returns (address);
function add_liquidity(uint256[3] memory _deposit_amounts, uint256 _min_mint_amount) external;
function remove_liquidity_one_coin(
uint256 _burn_amount,
int128 i,
uint256 _min_received
) external;
}
contracts/curve/IRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IRegistry {
function get_lp_token(address pool) external view returns (address);
function get_gauges(address pool) external view returns (address[10] memory, int128[10] memory);
}
contracts/depositary/AgregateDepositaryBalanceView.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../utils/OwnablePausable.sol";
import "./IDepositaryBalanceView.sol";
contract AgregateDepositaryBalanceView is IDepositaryBalanceView, OwnablePausable {
using SafeMath for uint256;
/// @notice The number of depositaries in agregate.
uint256 public maxSize;
/// @notice Decimals balance.
uint256 public override decimals;
/// @notice Depositaries in agregate.
IDepositaryBalanceView[] public depositaries;
/// @dev Depositaries index.
mapping(address => uint256) internal depositariesIndex;
/// @notice An event thats emitted when an new depositary added to agregate.
event DepositaryAdded(address depositary);
/// @notice An event thats emitted when an depositary removed from agregate.
event DepositaryRemoved(address depositary);
/**
* @param _decimals Decimals balance.
* @param _maxSize Max number depositaries in agregate.
*/
constructor(uint256 _decimals, uint256 _maxSize) public {
decimals = _decimals;
maxSize = _maxSize;
}
/**
* @return Depositaries count of agregate.
*/
function size() public view returns (uint256) {
return depositaries.length;
}
/**
* @notice Add depositary address to agregate.
* @param depositary Added depositary address.
*/
function addDepositary(address depositary) external onlyOwner {
require(depositariesIndex[depositary] == 0, "AgregateDepositaryBalanceView::addDepositary: depositary already added");
require(size() < maxSize, "AgregateDepositaryBalanceView::addDepositary: too many depositaries");
depositaries.push(IDepositaryBalanceView(depositary));
depositariesIndex[depositary] = size();
emit DepositaryAdded(depositary);
}
/**
* @notice Removed depositary address from agregate.
* @param depositary Removed depositary address.
*/
function removeDepositary(address depositary) external onlyOwner {
uint256 valueIndex = depositariesIndex[depositary];
require(valueIndex != 0, "AgregateDepositaryBalanceView::removeDepositary: depositary already removed");
uint256 toDeleteIndex = valueIndex.sub(1);
uint256 lastIndex = size().sub(1);
IDepositaryBalanceView lastValue = depositaries[lastIndex];
depositaries[toDeleteIndex] = lastValue;
depositariesIndex[address(lastValue)] = toDeleteIndex.add(1);
depositaries.pop();
delete depositariesIndex[depositary];
emit DepositaryRemoved(depositary);
}
/**
* @param depositary Target depositary address.
* @return True if target depositary is allowed.
*/
function hasDepositary(address depositary) external view returns (bool) {
return depositariesIndex[depositary] != 0;
}
/**
* @return Allowed depositaries list.
*/
function allowedDepositaries() external view returns (address[] memory) {
address[] memory result = new address[](size());
for (uint256 i = 0; i < size(); i++) {
result[i] = address(depositaries[i]);
}
return result;
}
function balance() external view override returns (uint256) {
uint256 result;
for (uint256 i = 0; i < size(); i++) {
uint256 depositaryBalance = depositaries[i].balance();
uint256 depositaryDecimals = depositaries[i].decimals();
uint256 decimalsPower = decimals.sub(depositaryDecimals);
result = result.add(depositaryBalance.mul(10**decimalsPower));
}
return result;
}
}
contracts/depositary/BuybackDepositaryBalanceView.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "../utils/OwnablePausable.sol";
import "./IDepositaryBalanceView.sol";
import "../Issuer.sol";
import "../Treasury.sol";
contract BuybackDepositaryBalanceView is IDepositaryBalanceView, OwnablePausable {
using Math for uint256;
using SafeMath for uint256;
using SafeERC20 for ERC20;
/// @notice Balance decimals.
uint256 public override decimals = 18;
/// @notice Address of product token.
ERC20 public product;
/// @notice Address of issuer contract.
Issuer public issuer;
/// @notice An event thats emitted when an issuer contract address changed.
event IssuerChanged(address newIssuer);
/// @notice An event thats emitted when an account buyback stable token.
event Buyback(address customer, uint256 amount, uint256 buy);
/**
* @param _issuer Issuer contract address.
* @param _product Product token address.
*/
constructor(address _issuer, address _product) public {
issuer = Issuer(_issuer);
product = ERC20(_product);
require(product.decimals() <= decimals, "BuybackDepositaryBalanceView::constructor: invalid decimals of product token");
}
/**
* @notice Change issuer contract address.
* @param _issuer New issuer contract address.
*/
function changeIssuer(address _issuer) external onlyOwner {
issuer = Issuer(_issuer);
emit IssuerChanged(_issuer);
}
/**
* @dev Transfer token to recipient.
* @param token Transfered token.
* @param recipient Address of recipient.
* @param amount Amount of transfered token.
*/
function _transfer(
ERC20 token,
address recipient,
uint256 amount
) internal {
require(recipient != address(0), "BuybackDepositaryBalanceView::_transfer: cannot transfer to the zero address");
token.safeTransfer(recipient, amount);
}
/**
* @notice Transfer product token.
* @param recipient Address of recipient.
* @param amount Amount of transfered token.
*/
function transferProductToken(address recipient, uint256 amount) external onlyOwner {
_transfer(product, recipient, amount);
}
/**
* @notice Transfer stable token.
* @param recipient Address of recipient.
* @param amount Amount of transfered token.
*/
function transferStableToken(address recipient, uint256 amount) external onlyOwner {
_transfer(ERC20(issuer.stableToken()), recipient, amount);
}
/**
* @notice Buyback stable token.
* @param amount Amount of payment token.
*/
function buy(uint256 amount) external whenNotPaused {
uint256 productAmount = amount.div(10**(decimals.sub(product.decimals())));
require(productAmount > 0, "BuybackDepositaryBalanceView::buy: invalid product amount");
require(productAmount >= product.balanceOf(address(this)), "BuybackDepositaryBalanceView::buy: product amount exceeds balance");
ERC20 stableToken = ERC20(issuer.stableToken());
stableToken.safeTransferFrom(_msgSender(), address(this), amount);
product.safeTransfer(_msgSender(), productAmount);
uint256 issuerInbalance = stableToken.totalSupply().sub(issuer.balance());
uint256 burningAmount = issuerInbalance.min(stableToken.balanceOf(address(this)));
if (burningAmount > 0) {
stableToken.safeTransfer(address(issuer), burningAmount);
issuer.rebalance();
}
emit Buyback(_msgSender(), amount, productAmount);
}
function balance() external view override returns (uint256) {
uint256 productBalance = product.balanceOf(address(this));
return productBalance.mul(10**(decimals.sub(product.decimals())));
}
}
contracts/depositary/CompoundDepositaryBalanceView.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "./IDepositaryBalanceView.sol";
contract CompoundDepositaryBalanceView is Ownable, IDepositaryBalanceView {
using SafeMath for uint256;
using SafeERC20 for ERC20;
using EnumerableSet for EnumerableSet.AddressSet;
/// @dev Invested cTokens.
EnumerableSet.AddressSet private tokens;
/// @notice Balance decimals.
uint256 public override decimals = 18;
/// @dev Invested balances.
mapping(address => uint256) internal balances;
/// @notice An event thats emitted when an invested token.
event Invested(address cToken, uint256 amount);
/// @notice An event thats emitted when an withdrawal token.
event Withdrawal(address cToken, uint256 amount, uint256 profit, address investRecipient, address profitRecipient);
/**
* @param cToken Invested cToken.
* @return Balance of invested token.
*/
function balanceOf(address cToken) external view returns (uint256) {
return balances[cToken];
}
/**
* @notice Invest token to Compound.
* @param cToken Invested cToken. Target ERC20 token should be approved to contract before call.
* @param amount Amount of invested token.
*/
function invest(address cToken, uint256 amount) external onlyOwner {
require(amount > 0, "CompoundDepositaryBalanceView::invest: invalid amount");
ERC20 token = ERC20(CToken(cToken).underlying());
uint256 tokenDecimals = token.decimals();
require(tokenDecimals <= decimals, "CompoundDepositaryBalanceView::invest: invalid token decimals");
token.safeTransferFrom(_msgSender(), address(this), amount);
token.safeApprove(cToken, 0);
token.safeApprove(cToken, amount);
CToken(cToken).mint(amount);
balances[cToken] = balances[cToken].add(amount);
tokens.add(cToken);
emit Invested(cToken, amount);
}
/**
* @notice Withdraw invested token and reward.
* @param cToken Invested cToken.
* @param investRecipient Recipient of invested token.
* @param profitRecipient Recipient of reward token.
*/
function withdraw(
address cToken,
address investRecipient,
address profitRecipient
) external onlyOwner {
uint256 investAmount = balances[cToken];
require(investAmount > 0, "CompoundDepositaryBalanceView::withdraw: token not invested");
balances[cToken] = 0;
tokens.remove(cToken);
uint256 cTokenBalance = ERC20(cToken).balanceOf(address(this));
CToken(cToken).redeem(cTokenBalance);
ERC20 token = ERC20(CToken(cToken).underlying());
uint256 balance = token.balanceOf(address(this));
uint256 profitAmount;
if (balance >= investAmount) {
profitAmount = balance.sub(investAmount);
} else {
investAmount = balance;
}
token.safeTransfer(investRecipient, investAmount);
if (profitAmount > 0) {
token.safeTransfer(profitRecipient, profitAmount);
}
emit Withdrawal(cToken, investAmount, profitAmount, investRecipient, profitRecipient);
}
/**
* @return Invested cTokens.
*/
function investedTokens() external view returns (address[] memory) {
address[] memory result = new address[](tokens.length());
for (uint256 i = 0; i < tokens.length(); i++) {
result[i] = tokens.at(i);
}
return result;
}
function balance() external view override returns (uint256) {
uint256 result;
for (uint256 i = 0; i < tokens.length(); i++) {
address cToken = tokens.at(i);
ERC20 token = ERC20(CToken(cToken).underlying());
uint256 tokenDecimals = token.decimals();
result = result.add(balances[cToken].mul(10**(decimals.sub(tokenDecimals))));
}
return result;
}
}
abstract contract CToken {
address public underlying;
function exchangeRateCurrent() public virtual returns (uint256);
function mint(uint256 mintAmount) external virtual returns (uint256);
function redeem(uint256 redeemTokens) external virtual returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256);
}
contracts/depositary/CurveDepositaryBalanceView.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../curve/IRegistry.sol";
import "../uniswap/IUniswapV2Router02.sol";
import "./IDepositaryBalanceView.sol";
import "../curve/IPool.sol";
import "../curve/ILiquidityGauge.sol";
import "../curve/IMinter.sol";
contract CurveDepositaryBalanceView is Ownable, IDepositaryBalanceView {
using SafeMath for uint256;
using SafeERC20 for ERC20;
using EnumerableSet for EnumerableSet.AddressSet;
/// @notice Curve registry contract.
IRegistry public registry;
/// @notice Uniswap router contract.
IUniswapV2Router02 public uniswapRouter;
/// @dev Invested pools.
EnumerableSet.AddressSet private pools;
/// @notice Balance decimals.
uint256 public override decimals = 18;
/// @dev Invested balances.
mapping(address => uint256) internal balances;
/// @notice An event thats emitted when an curve registry address changed.
event RegistryChanged(address registry);
/// @notice An event thats emitted when an uniswap router address changed.
event UniswapRouterChanged(address uniswapRouter);
/// @notice An event thats emitted when an invested token.
event Invested(address pool, address token, uint256 amount);
/// @notice An event thats emitted when an withdrawal token.
event Withdrawal(address token, uint256 amount, address recipient);
/// @notice An event thats emitted when an withdrawal proft token.
event Mint(address token, uint256 amount, address recipient);
/**
* @param _registry Curve registry contract address.
* @param _uniswapRouter Uniswap router contract address.
*/
constructor(address _registry, address _uniswapRouter) public {
registry = IRegistry(_registry);
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
}
/**
* @param _registry New Curve registry contract address.
*/
function changeRegistry(address _registry) external onlyOwner {
require(_registry != address(0), "CurveDepositaryBalanceView::changeRegistry: invalid registry address");
registry = IRegistry(_registry);
emit RegistryChanged(_registry);
}
/**
* @param _uniswapRouter New Uniswap router contract address.
*/
function changeUniswap(address _uniswapRouter) external onlyOwner {
require(_uniswapRouter != address(0), "CurveDepositaryBalanceView::changeUniswap: invalid uniswap address");
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
emit UniswapRouterChanged(_uniswapRouter);
}
/**
* @param pool Target liquidity pool address.
* @return Liquidity pool token.
*/
function _getPoolLiquidityToken(address pool) internal view returns (ERC20) {
address tokenAddress = registry.get_lp_token(pool);
require(tokenAddress != address(0), "CurveDepositaryBalanceView::_getPoolLiquidityToken: liquidity token not found");
return ERC20(tokenAddress);
}
/**
* @param pool Target liquidity pool address.
* @return Liquidity gauge.
*/
function _getPoolLiquidityGauge(address pool) internal view returns (ILiquidityGauge) {
(address[10] memory gauges, ) = registry.get_gauges(pool);
require(gauges[0] != address(0), "CurveDepositaryBalanceView::_getPoolLiquidityGauge: liquidity gauge not found");
return ILiquidityGauge(gauges[0]);
}
/**
* @param pool Invested pool.
* @return Balance of invested pool.
*/
function balanceOf(address pool) external view returns (uint256) {
return balances[pool];
}
/**
* @notice Lock all liquidity pool token in liquidity gauge.
* @param pool Target liquidity pool address.
*/
function _lock(address pool) internal {
ILiquidityGauge gauge = _getPoolLiquidityGauge(pool);
ERC20 lpToken = _getPoolLiquidityToken(pool);
uint256 balance = lpToken.balanceOf(address(this));
if (balance == 0) return;
lpToken.safeApprove(address(gauge), 0);
lpToken.safeApprove(address(gauge), balance);
gauge.deposit(balance);
}
/**
* @notice Unlock all liquidity pool token from liquidity gauge.
* @param pool Target liquidity pool address.
*/
function _unlock(address pool) internal {
ILiquidityGauge gauge = _getPoolLiquidityGauge(pool);
uint256 balance = ERC20(address(gauge)).balanceOf(address(this));
gauge.withdraw(balance);
}
/**
* @notice Mint CRV tokens and swap to target token.
* @param pool Target liquidity pool.
* @param toToken Target token.
* @param recipient Recipient.
*/
function mint(
address pool,
address toToken,
address recipient
) public onlyOwner {
require(toToken != address(0), "CurveDepositaryBalanceView::mintCrv: invalid target token address");
ILiquidityGauge gauge = _getPoolLiquidityGauge(pool);
IMinter minter = IMinter(gauge.minter());
minter.mint(address(gauge));
ERC20 crv = ERC20(minter.token());
uint256 crvBalance = crv.balanceOf(address(this));
if (crvBalance == 0) return;
if (toToken != address(crv)) {
address[] memory path = new address[](2);
path[0] = address(address(crv));
path[1] = address(toToken);
uint256[] memory amountsOut = uniswapRouter.getAmountsOut(crvBalance, path);
require(amountsOut.length == 2, "CurveDepositaryBalanceView::mintCrv: invalid amount out");
uint256 amountOut = amountsOut[amountsOut.length - 1];
require(amountOut > 0, "CurveDepositaryBalanceView::mintCrv: liquidity pool is empty");
crv.safeApprove(address(uniswapRouter), 0);
crv.safeApprove(address(uniswapRouter), crvBalance);
uint256[] memory profitAmount = uniswapRouter.swapExactTokensForTokens(crvBalance, amountOut, path, recipient, block.timestamp);
emit Mint(toToken, profitAmount[profitAmount.length - 1], recipient);
} else {
crv.safeTransfer(recipient, crvBalance);
emit Mint(address(crv), crvBalance, recipient);
}
}
/**
* @notice Invest token to Curve.
* @param pool Target liquidity pool.
* @param tokenIndex Invested token index in the pool. Target ERC20 token should be approved to contract before call.
* @param amount Amount of invested token.
*/
function invest(
address pool,
uint256 tokenIndex,
uint256 amount
) external onlyOwner {
require(amount > 0, "CurveDepositaryBalanceView::invest: invalid amount");
require(tokenIndex < 3, "CurveDepositaryBalanceView::invest: invalid token index");
address tokenAddress = IPool(pool).coins(tokenIndex);
require(tokenAddress != address(0), "CurveDepositaryBalanceView::invest: invalid invest token");
ERC20 token = ERC20(tokenAddress);
uint256 tokenDecimals = token.decimals();
require(tokenDecimals <= decimals, "CurveDepositaryBalanceView::invest: invalid token decimals");
token.safeTransferFrom(_msgSender(), address(this), amount);
balances[pool] = balances[pool].add(amount.mul(10**(decimals.sub(tokenDecimals)))); // Only stable token sum
pools.add(pool);
token.safeApprove(pool, 0);
token.safeApprove(pool, amount);
uint256[3] memory deposit;
deposit[tokenIndex] = amount;
IPool(pool).add_liquidity(deposit, 0);
_lock(pool);
emit Invested(pool, tokenAddress, amount);
}
/**
* @notice Withdraw invested token and reward.
* @param pool Target liquidity pool.
* @param tokenIndex Invested token index in the pool.
* @param recipient Recipient of invested token.
*/
function withdraw(
address pool,
uint256 tokenIndex,
address recipient
) external onlyOwner {
require(tokenIndex < 3, "CurveDepositaryBalanceView::invest: invalid token index");
address tokenAddress = IPool(pool).coins(tokenIndex);
require(tokenAddress != address(0), "CurveDepositaryBalanceView::withdraw: invalid withdraw token");
ERC20 lpToken = _getPoolLiquidityToken(pool);
balances[pool] = 0;
pools.remove(pool);
_unlock(pool);
uint256 lpBalance = lpToken.balanceOf(address(this));
IPool(pool).remove_liquidity_one_coin(lpBalance, int128(tokenIndex), 0);
ERC20 token = ERC20(tokenAddress);
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(recipient, balance);
emit Withdrawal(tokenAddress, balance, recipient);
}
/**
* @return Invested liquidity pools.
*/
function investedPools() external view returns (address[] memory) {
address[] memory result = new address[](pools.length());
for (uint256 i = 0; i < pools.length(); i++) {
result[i] = pools.at(i);
}
return result;
}
function balance() external view override returns (uint256) {
uint256 result;
for (uint256 i = 0; i < pools.length(); i++) {
address pool = pools.at(i);
result = result.add(balances[pool]);
}
return result;
}
}
contracts/depositary/DepositorCollateral.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
contract DepositorCollateral is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
using EnumerableSet for EnumerableSet.AddressSet;
/// @notice Max number of depositors.
uint256 public maxSize;
/**
* @notice Locked tokens.
*/
mapping(address => uint256) public totalSupply;
/**
* @dev Depositors list.
*/
mapping(address => EnumerableSet.AddressSet) internal _depositors;
/**
* @dev Depositors balances.
*/
mapping(address => mapping(address => uint256)) internal _balances;
/// @notice An event emitted when collateral locked.
event Lock(address token, address depositor, uint256 amount);
/// @notice An event emitted when collateral withdraw.
event Withdraw(address token, address depositor, uint256 amount);
/**
* @param _maxSize Max number of depositors.
*/
constructor(uint256 _maxSize) public {
maxSize = _maxSize;
}
/**
* @notice Get depositors.
* @param token Collateral token.
* @return Addresses of all depositors.
*/
function getDepositors(address token) public view returns (address[] memory) {
address[] memory result = new address[](_depositors[token].length());
for (uint256 i = 0; i < _depositors[token].length(); i++) {
result[i] = _depositors[token].at(i);
}
return result;
}
/**
* @notice Get balance of depositor.
* @param token Target token.
* @param depositor Target depositor.
* @return Balance of depositor.
*/
function balanceOf(address token, address depositor) public view returns (uint256) {
return _balances[token][depositor];
}
/**
* @notice Lock depositor collateral.
* @param token Locked token.
* @param depositor Depositor address.
* @param amount Locked amount.
*/
function lock(
address token,
address depositor,
uint256 amount
) external onlyOwner {
require(amount > 0, "DepositorCollateral::lock: empty amount");
_depositors[token].add(depositor);
require(_depositors[token].length() <= maxSize, "DepositorCollateral::lock: too many depositors");
ERC20(token).safeTransferFrom(depositor, address(this), amount);
_balances[token][depositor] = _balances[token][depositor].add(amount);
totalSupply[token] = totalSupply[token].add(amount);
emit Lock(token, depositor, amount);
}
/**
* @notice Withdraw depositor collateral.
* @param token Withdraw token.
* @param depositor Depositor address.
* @param amount Withdraw amount.
*/
function withdraw(
address token,
address depositor,
uint256 amount
) external onlyOwner {
require(amount > 0, "DepositorCollateral::withdraw: empty amount");
require(balanceOf(token, depositor) >= amount, "DepositorCollateral::withdraw: negative balance");
_balances[token][depositor] = _balances[token][depositor].sub(amount);
if (_balances[token][depositor] == 0) {
_depositors[token].remove(depositor);
}
totalSupply[token] = totalSupply[token].sub(amount);
ERC20(token).safeTransfer(depositor, amount);
emit Withdraw(token, depositor, amount);
}
}
contracts/depositary/IDepositaryBalanceView.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title The Depositary Balance interface.
*/
interface IDepositaryBalanceView {
/**
* @notice Get decimals balance.
* @return Decimals balance.
*/
function decimals() external view returns(uint256);
/**
* @notice Get balance of depositary.
* @return Balance of depositary.
*/
function balance() external view returns(uint256);
}contracts/depositary/IUpdatable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IUpdatable {
/**
* @return Last update block number.
*/
function lastUpdateBlockNumber() external view returns (uint256);
}
contracts/depositary/RealAssetDepositaryBalanceView.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../utils/AccessControl.sol";
import "./IDepositaryBalanceView.sol";
import "./IUpdatable.sol";
contract RealAssetDepositaryBalanceView is IDepositaryBalanceView, IUpdatable, AccessControl {
using SafeMath for uint256;
/// @notice Signed data of asset information.
struct Proof {
string data;
string signature;
}
/// @notice Asset information.
struct Asset {
string id;
uint256 amount;
uint256 price;
uint256 updatedBlockAt;
}
/// @notice The number of assets in depositary.
uint256 public maxSize;
/// @notice Decimals balance.
uint256 public override decimals = 6;
/// @notice Assets list.
Asset[] public portfolio;
/// @dev Assets list index.
mapping(string => uint256) internal portfolioIndex;
/// @notice An event thats emitted when asset updated in portfolio.
event AssetUpdated(string id, uint256 updatedAt, Proof proof);
/// @notice An event thats emitted when asset removed from portfolio.
event AssetRemoved(string id);
/**
* @param _decimals Decimals balance.
* @param _maxSize Max number assets in depositary.
*/
constructor(uint256 _decimals, uint256 _maxSize) public {
decimals = _decimals;
maxSize = _maxSize;
}
/**
* @return Assets count of depositary.
*/
function size() public view returns (uint256) {
return portfolio.length;
}
/**
* @return Assets list.
*/
function assets() external view returns (Asset[] memory) {
Asset[] memory result = new Asset[](size());
for (uint256 i = 0; i < size(); i++) {
result[i] = portfolio[i];
}
return result;
}
function lastUpdateBlockNumber() external view override returns (uint256) {
uint256 result;
for (uint256 i = 0; i < size(); i++) {
result = portfolio[i].updatedBlockAt > result ? portfolio[i].updatedBlockAt : result;
}
return result;
}
/**
* @notice Update information of asset.
* @param id Asset identificator.
* @param amount Amount of asset.
* @param price Cost of one asset in base currency.
* @param updatedAt Timestamp of updated.
* @param proofData Signed data.
* @param proofSignature Data signature.
*/
function put(
string calldata id,
uint256 amount,
uint256 price,
uint256 updatedAt,
string calldata proofData,
string calldata proofSignature
) external onlyAllowed {
require(size() < maxSize, "RealAssetDepositaryBalanceView::put: too many assets");
uint256 valueIndex = portfolioIndex[id];
if (valueIndex != 0) {
portfolio[valueIndex.sub(1)] = Asset(id, amount, price, block.number);
} else {
portfolio.push(Asset(id, amount, price, block.number));
portfolioIndex[id] = size();
}
emit AssetUpdated(id, updatedAt, Proof(proofData, proofSignature));
}
/**
* @notice Remove information of asset.
* @param id Asset identificator.
*/
function remove(string calldata id) external onlyAllowed {
uint256 valueIndex = portfolioIndex[id];
require(valueIndex != 0, "RealAssetDepositaryBalanceView::remove: asset already removed");
uint256 toDeleteIndex = valueIndex.sub(1);
uint256 lastIndex = size().sub(1);
Asset memory lastValue = portfolio[lastIndex];
portfolio[toDeleteIndex] = lastValue;
portfolioIndex[lastValue.id] = toDeleteIndex.add(1);
portfolio.pop();
delete portfolioIndex[id];
emit AssetRemoved(id);
}
function balance() external view override returns (uint256) {
uint256 result;
for (uint256 i = 0; i < size(); i++) {
result = result.add(portfolio[i].amount.mul(portfolio[i].price));
}
return result;
}
}
contracts/depositary/StableTokenDepositaryBalanceView.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "./IDepositaryBalanceView.sol";
contract StableTokenDepositaryBalanceView is Ownable, IDepositaryBalanceView {
using SafeMath for uint256;
using SafeERC20 for ERC20;
using EnumerableSet for EnumerableSet.AddressSet;
/// @notice Balance decimals.
uint256 public override decimals = 18;
/// @dev Allowed tokens.
EnumerableSet.AddressSet private tokens;
/// @notice An event emitted when token allowed.
event TokenAllowed(address token);
/// @notice An event emitted when token denied.
event TokenDenied(address token);
/**
* @notice Allow token.
* @param token Allowed token.
*/
function allowToken(address token) external onlyOwner {
require(!tokens.contains(token), "TokenDepositary::allowToken: token already allowed");
uint256 tokenDecimals = ERC20(token).decimals();
require(tokenDecimals <= decimals, "TokenDepositary::allowToken: invalid token decimals");
tokens.add(token);
emit TokenAllowed(token);
}
/**
* @notice Deny token.
* @param token Denied token.
*/
function denyToken(address token) external onlyOwner {
require(tokens.contains(token), "TokenDepositary::denyToken: token already denied");
tokens.remove(token);
emit TokenDenied(token);
}
/**
* @notice Transfer target token to recipient.
* @param token Target token.
* @param recipient Recipient.
* @param amount Transfer amount.
*/
function transfer(
address token,
address recipient,
uint256 amount
) external onlyOwner {
ERC20(token).safeTransfer(recipient, amount);
}
/**
* @return Allowed tokens list.
*/
function allowedTokens() external view returns (address[] memory) {
address[] memory result = new address[](tokens.length());
for(uint256 i = 0; i < tokens.length(); i++) {
result[i] = tokens.at(i);
}
return result;
}
function balance() external override view returns (uint256) {
uint256 result;
for(uint256 i = 0; i < tokens.length(); i++) {
ERC20 token = ERC20(tokens.at(i));
uint256 tokenBalance = token.balanceOf(address(this));
uint256 tokenDecimals = token.decimals();
result = result.add(tokenBalance.mul(10**(decimals.sub(tokenDecimals))));
}
return result;
}
}
contracts/mocks/MockERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract MockERC20 is ERC20, Ownable {
constructor(
string memory name,
string memory symbol,
uint256 initialSupply
) public ERC20(name, symbol) {
_mint(_msgSender(), initialSupply);
}
function mint(address account, uint256 amount) public onlyOwner {
_mint(account, amount);
}
function burn(address account, uint256 amount) public onlyOwner {
_burn(account, amount);
}
}
contracts/profit/Buyback.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../utils/OwnablePausable.sol";
import "../uniswap/IUniswapV2Router02.sol";
contract Buyback is OwnablePausable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
/// @notice Incoming token.
ERC20 public incoming;
/// @notice Outcoming token.
ERC20 public outcoming;
/// @notice Recipient address.
address public recipient;
/// @notice Uniswap router contract address.
IUniswapV2Router02 public uniswapRouter;
/// @notice An event thats emitted when an incoming token transferred to recipient.
event Transfer(address recipient, uint256 amount);
/// @notice An event thats emitted when an recipient address changed.
event RecipientChanged(address newRecipient);
/// @notice An event thats emitted when an incoming token changed.
event IncomingChanged(address newIncoming);
/// @notice An event thats emitted when an uniswap router contract address changed.
event UniswapRouterChanged(address newUniswapRouter);
/// @notice An event thats emitted when an buyback successed.
event BuybackSuccessed(uint256 incoming, uint256 outcoming);
/**
* @param _incoming Address of incoming token.
* @param _outcoming Address of outcoming token.
* @param _recipient Address of recipient outcoming token.
* @param _uniswapRouter Address of Uniswap router contract.
*/
constructor(
address _incoming,
address _outcoming,
address _recipient,
address _uniswapRouter
) public {
incoming = ERC20(_incoming);
outcoming = ERC20(_outcoming);
recipient = _recipient;
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
}
/**
* @notice Change recipient address.
* @param _recipient New recipient address.
*/
function changeRecipient(address _recipient) external onlyOwner {
recipient = _recipient;
emit RecipientChanged(recipient);
}
/**
* @notice Changed uniswap router contract address.
* @param _uniswapRouter Address new uniswap router contract.
*/
function changeUniswapRouter(address _uniswapRouter) external onlyOwner {
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
emit UniswapRouterChanged(_uniswapRouter);
}
/**
* @notice Transfer incoming token to recipient.
* @param _recipient Address of recipient.
* @param amount Amount of transferred token.
*/
function transfer(address _recipient, uint256 amount) public onlyOwner {
require(_recipient != address(0), "Buyback::transfer: cannot transfer to the zero address");
incoming.safeTransfer(_recipient, amount);
emit Transfer(_recipient, amount);
}
/**
* @notice Change incoming token address.
* @param _incoming New incoming token address.
* @param _recipient Address of recipient.
*/
function changeIncoming(address _incoming, address _recipient) external onlyOwner {
require(address(incoming) != _incoming, "Buyback::changeIncoming: duplicate incoming token address");
uint256 balance = incoming.balanceOf(address(this));
if (balance > 0) {
transfer(_recipient, balance);
}
incoming = ERC20(_incoming);
emit IncomingChanged(_incoming);
}
/**
* @notice Make buyback attempt.
* @param amount Amount of tokens to buyback.
*/
function buy(uint256 amount) external whenNotPaused {
if (amount > 0) {
incoming.safeTransferFrom(_msgSender(), address(this), amount);
}
address[] memory path = new address[](2);
path[0] = address(incoming);
path[1] = address(outcoming);
uint256 amountIn = incoming.balanceOf(address(this));
require(amountIn > 0, "Buyback::buy: incoming token balance is empty");
uint256[] memory amountsOut = uniswapRouter.getAmountsOut(amountIn, path);
require(amountsOut.length != 0, "Buyback::buy: invalid amounts out length");
uint256 amountOut = amountsOut[amountsOut.length - 1];
require(amountOut > 0, "Buyback::buy: liquidity pool is empty");
incoming.safeApprove(address(uniswapRouter), amountIn);
uniswapRouter.swapExactTokensForTokens(amountIn, amountOut, path, recipient, block.timestamp);
emit BuybackSuccessed(amountIn, amountOut);
}
}
contracts/profit/ProfitSplitter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../utils/OwnablePausable.sol";
import "../uniswap/IUniswapV2Router02.sol";
contract ProfitSplitter is OwnablePausable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
using EnumerableSet for EnumerableSet.AddressSet;
uint256 public constant SHARE_ACCURACY = 6;
uint256 public constant SHARE_DIGITS = 2;
/// @notice Incoming token.
ERC20 public incoming;
/// @notice Budget contract address.
address payable public budget;
/// @notice Target budget ETH balance.
uint256 public budgetBalance;
/// @notice Recipients share.
mapping(address => uint256) public shares;
/// @dev Recipients addresses index.
EnumerableSet.AddressSet private recipientsIndex;
/// @notice Uniswap router contract address.
IUniswapV2Router02 public uniswapRouter;
/// @notice An event thats emitted when an incoming token transferred to recipient.
event Transfer(address recipient, uint256 amount);
/// @notice An event thats emitted when an budget contract address and target balance changed.
event BudgetChanged(address newBudget, uint256 newBalance);
/// @notice An event thats emitted when an incoming token changed.
event IncomingChanged(address newIncoming);
/// @notice An event thats emitted when an uniswap router contract address changed.
event UniswapRouterChanged(address newUniswapRouter);
/// @notice An event thats emitted when an recipient added.
event RecipientAdded(address recipient, uint256 share);
/// @notice An event thats emitted when an recipient removed.
event RecipientRemoved(address recipient);
/// @notice An event thats emitted when an profit payed to budget.
event PayToBudget(address recipient, uint256 amount);
/// @notice An event thats emitted when an profit payed to recipient.
event PayToRecipient(address recipient, uint256 amount);
receive() external payable {}
/**
* @param _incoming Address of incoming token.
* @param _uniswapRouter Address of Uniswap router contract.
*/
constructor(address _incoming, address _uniswapRouter) public {
incoming = ERC20(_incoming);
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
}
/**
* @notice Changed uniswap router contract address.
* @param _uniswapRouter Address new uniswap router contract.
*/
function changeUniswapRouter(address _uniswapRouter) external onlyOwner {
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
emit UniswapRouterChanged(_uniswapRouter);
}
/**
* @notice Changed budget contract address and target balance.
* @param _budget Address of budget contract.
* @param _budgetBalance Target budget balance.
*/
function changeBudget(address payable _budget, uint256 _budgetBalance) external onlyOwner {
budget = _budget;
budgetBalance = _budgetBalance;
emit BudgetChanged(budget, budgetBalance);
}
/**
* @notice Transfer incoming token to recipient.
* @param _recipient Address of recipient.
* @param amount Amount of transferred token.
*/
function transfer(address _recipient, uint256 amount) public onlyOwner {
require(_recipient != address(0), "ProfitSplitter::transfer: cannot transfer to the zero address");
incoming.safeTransfer(_recipient, amount);
emit Transfer(_recipient, amount);
}
/**
* @notice Change incoming token address.
* @param _incoming New incoming token address.
* @param _recipient Address of recipient.
*/
function changeIncoming(address _incoming, address _recipient) external onlyOwner {
require(address(incoming) != _incoming, "ProfitSplitter::changeIncoming: duplicate incoming token address");
uint256 balance = incoming.balanceOf(address(this));
if (balance > 0) {
transfer(_recipient, balance);
}
incoming = ERC20(_incoming);
emit IncomingChanged(_incoming);
}
/**
* @dev Current share value.
* @return result Current share value.
*/
function _currentShare() internal view returns (uint256 result) {
for (uint256 i = 0; i < recipientsIndex.length(); i++) {
result = result.add(shares[recipientsIndex.at(i)]);
}
}
/**
* @notice Add recipient.
* @param recipient Address of recipient contract.
* @param share Target share.
*/
function addRecipient(address recipient, uint256 share) external onlyOwner {
require(!recipientsIndex.contains(recipient), "ProfitSplitter::addRecipient: recipient already added");
require(_currentShare().add(share) <= 100, "ProfitSplitter::addRecipient: invalid share");
recipientsIndex.add(recipient);
shares[recipient] = share;
emit RecipientAdded(recipient, share);
}
/**
* @notice Remove recipient.
* @param recipient Address of recipient contract.
*/
function removeRecipient(address recipient) external onlyOwner {
require(recipientsIndex.contains(recipient), "ProfitSplitter::removeRecipient: recipient already removed");
recipientsIndex.remove(recipient);
shares[recipient] = 0;
emit RecipientRemoved(recipient);
}
/**
* @notice Get addresses of recipients.
* @return Current recipients list.
*/
function getRecipients() public view returns (address[] memory) {
address[] memory result = new address[](recipientsIndex.length());
for (uint256 i = 0; i < recipientsIndex.length(); i++) {
result[i] = recipientsIndex.at(i);
}
return result;
}
/**
* @dev Pay ETH to budget contract.
*/
function _payToBudget() internal returns (bool) {
uint256 splitterIncomingBalance = incoming.balanceOf(address(this));
if (splitterIncomingBalance == 0) return false;
uint256 currentBudgetBalance = budget.balance;
if (currentBudgetBalance >= budgetBalance) return false;
uint256 amount = budgetBalance.sub(currentBudgetBalance);
uint256 splitterEthBalance = address(this).balance;
if (splitterEthBalance < amount) {
uint256 amountOut = amount.sub(splitterEthBalance);
address[] memory path = new address[](2);
path[0] = address(incoming);
path[1] = uniswapRouter.WETH();
uint256[] memory amountsIn = uniswapRouter.getAmountsIn(amountOut, path);
require(amountsIn.length == 2, "ProfitSplitter::_payToBudget: invalid amounts in length");
require(amountsIn[0] > 0, "ProfitSplitter::_payToBudget: liquidity pool is empty");
if (amountsIn[0] <= splitterIncomingBalance) {
incoming.safeApprove(address(uniswapRouter), amountsIn[0]);
uniswapRouter.swapTokensForExactETH(amountOut, amountsIn[0], path, address(this), block.timestamp);
} else {
uint256[] memory amountsOut = uniswapRouter.getAmountsOut(splitterIncomingBalance, path);
require(amountsOut.length == 2, "ProfitSplitter::_payToBudget: invalid amounts out length");
require(amountsOut[1] > 0, "ProfitSplitter::_payToBudget: amounts out liquidity pool is empty");
amount = amountsOut[1];
incoming.safeApprove(address(uniswapRouter), splitterIncomingBalance);
uniswapRouter.swapExactTokensForETH(splitterIncomingBalance, amountsOut[1], path, address(this), block.timestamp);
}
}
budget.transfer(amount);
emit PayToBudget(budget, amount);
return true;
}
/**
* @dev Pay incoming token to all recipients.
*/
function _payToRecipients() internal returns (bool) {
uint256 splitterIncomingBalance = incoming.balanceOf(address(this));
if (splitterIncomingBalance == 0) return false;
for (uint256 i = 0; i < recipientsIndex.length(); i++) {
address recipient = recipientsIndex.at(i);
uint256 share = shares[recipient];
uint256 amount = splitterIncomingBalance.mul(10**SHARE_ACCURACY).mul(share).div(10**SHARE_ACCURACY.add(SHARE_DIGITS));
incoming.safeTransfer(recipient, amount);
emit PayToRecipient(recipient, amount);
}
return true;
}
/**
* @notice Split all incoming token balance to recipients and budget contract.
* @param amount Approved amount incoming token.
*/
function split(uint256 amount) external whenNotPaused {
if (amount > 0) {
incoming.safeTransferFrom(_msgSender(), address(this), amount);
}
_payToBudget();
_payToRecipients();
}
}
contracts/profit/UniswapMarketMaker.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../utils/OwnablePausable.sol";
import "../uniswap/IUniswapV2Router02.sol";
import "../uniswap/IUniswapV2Factory.sol";
contract UniswapMarketMaker is OwnablePausable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
/// @notice Incoming token.
ERC20 public incoming;
/// @notice Support token.
ERC20 public support;
/// @notice Uniswap router contract address.
IUniswapV2Router02 public uniswapRouter;
/// @notice An event thats emitted when an token transferred to recipient.
event TokenTransfer(address token, address recipient, uint256 amount);
/// @notice An event thats emitted when an uniswap router contract address changed.
event UniswapRouterChanged(address newUniswapRouter);
/// @notice An event thats emitted when an incoming token changed.
event IncomingChanged(address newIncoming);
/// @notice An event thats emitted when an liquidity added.
event LiquidityIncreased(uint256 incoming, uint256 support);
/// @notice An event thats emitted when an liquidity removed.
event LiquidityReduced(uint256 lp, uint256 incoming, uint256 support);
/**
* @param _incoming Address of incoming token.
* @param _support Address of support token.
* @param _uniswapRouter Address of Uniswap router contract.
*/
constructor(
address _incoming,
address _support,
address _uniswapRouter
) public {
incoming = ERC20(_incoming);
support = ERC20(_support);
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
}
/**
* @notice Transfer incoming token to recipient.
* @param token Address of transferred token.
* @param recipient Address of recipient.
* @param amount Amount of transferred token.
*/
function transfer(
address token,
address recipient,
uint256 amount
) external onlyOwner {
require(recipient != address(0), "UniswapMarketMaker::transfer: cannot transfer to the zero address");
ERC20(token).safeTransfer(recipient, amount);
emit TokenTransfer(token, recipient, amount);
}
/**
* @notice Changed uniswap router contract address.
* @param _uniswapRouter Address new uniswap router contract.
*/
function changeUniswapRouter(address _uniswapRouter) external onlyOwner {
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
emit UniswapRouterChanged(_uniswapRouter);
}
/**
* @notice Change incoming token address.
* @param _incoming New incoming token address.
* @param _recipient Address of recipient.
*/
function changeIncoming(address _incoming, address _recipient) external onlyOwner {
require(address(incoming) != _incoming, "UniswapMarketMaker::changeIncoming: duplicate incoming token address");
uint256 balance = incoming.balanceOf(address(this));
if (balance > 0) {
incoming.safeTransfer(_recipient, balance);
}
incoming = ERC20(_incoming);
emit IncomingChanged(_incoming);
}
/**
* @notice Buy support token and add liquidity.
* @param amount Amount of incoming token.
*/
function buyLiquidity(uint256 amount) external whenNotPaused {
if (amount > 0) {
incoming.safeTransferFrom(_msgSender(), address(this), amount);
}
address[] memory path = new address[](2);
path[0] = address(incoming);
path[1] = address(support);
uint256 amountIn = incoming.balanceOf(address(this)).div(2);
require(amountIn > 0, "UniswapMarketMaker::buyLiquidity: not enough funds to buy back");
uint256[] memory amountsOut = uniswapRouter.getAmountsOut(amountIn, path);
require(amountsOut.length != 0, "UniswapMarketMaker::buyLiquidity: invalid amounts out length");
uint256 amountOut = amountsOut[amountsOut.length - 1];
require(amountOut > 0, "UniswapMarketMaker::buyLiquidity: liquidity pool is empty");
incoming.safeApprove(address(uniswapRouter), amountIn);
uniswapRouter.swapExactTokensForTokens(amountIn, amountOut, path, address(this), block.timestamp);
uint256 incomingBalance = incoming.balanceOf(address(this));
require(incomingBalance > 0, "UniswapMarketMaker::buyLiquidity: incoming token balance is empty");
uint256 supportBalance = support.balanceOf(address(this));
require(supportBalance > 0, "UniswapMarketMaker::buyLiquidity: support token balance is empty");
incoming.safeApprove(address(uniswapRouter), incomingBalance);
support.safeApprove(address(uniswapRouter), supportBalance);
(uint256 amountA, uint256 amountB, ) = uniswapRouter.addLiquidity(address(incoming), address(support), incomingBalance, supportBalance, 0, 0, address(this), block.timestamp);
emit LiquidityIncreased(amountA, amountB);
incoming.safeApprove(address(uniswapRouter), 0);
support.safeApprove(address(uniswapRouter), 0);
}
/**
* @notice Add liquidity.
* @param incomingAmount Amount of incoming token.
* @param supportAmount Amount of support token.
*/
function addLiquidity(uint256 incomingAmount, uint256 supportAmount) external whenNotPaused {
if (incomingAmount > 0) {
incoming.safeTransferFrom(_msgSender(), address(this), incomingAmount);
}
if (supportAmount > 0) {
support.safeTransferFrom(_msgSender(), address(this), supportAmount);
}
uint256 incomingBalance = incoming.balanceOf(address(this));
require(incomingBalance > 0, "UniswapMarketMaker::addLiquidity: incoming token balance is empty");
uint256 supportBalance = support.balanceOf(address(this));
require(supportBalance > 0, "UniswapMarketMaker::addLiquidity: support token balance is empty");
incoming.safeApprove(address(uniswapRouter), incomingBalance);
support.safeApprove(address(uniswapRouter), supportBalance);
(uint256 amountA, uint256 amountB, ) = uniswapRouter.addLiquidity(address(incoming), address(support), incomingBalance, supportBalance, 0, 0, address(this), block.timestamp);
emit LiquidityIncreased(amountA, amountB);
incoming.safeApprove(address(uniswapRouter), 0);
support.safeApprove(address(uniswapRouter), 0);
}
/**
* @notice Return liquidity pair address.
* @return Liquidity pair address.
*/
function liquidityPair() public view returns (address) {
IUniswapV2Factory uniswapFactory = IUniswapV2Factory(uniswapRouter.factory());
return uniswapFactory.getPair(address(incoming), address(support));
}
/**
* @notice Remove liquidity.
* @param amount Amount of liquidity pool token.
*/
function removeLiquidity(uint256 amount) external onlyOwner {
address pair = liquidityPair();
require(pair != address(0), "UniswapMarketMaker::removeLiquidity: liquidity pair not found");
uint256 lpBalance = ERC20(pair).balanceOf(address(this));
amount = lpBalance < amount ? lpBalance : amount;
require(amount > 0, "UniswapMarketMaker::removeLiquidity: zero amount");
ERC20(pair).safeApprove(address(uniswapRouter), amount);
(uint256 incomingAmount, uint256 supportAmount) = uniswapRouter.removeLiquidity(address(incoming), address(support), amount, 0, 0, address(this), block.timestamp);
emit LiquidityReduced(amount, incomingAmount, supportAmount);
}
}
contracts/uniswap/IUniswapAnchoredView.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IUniswapAnchoredView {
function price(string calldata symbol) external view returns (uint);
}contracts/uniswap/IUniswapV2Factory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
contracts/uniswap/IUniswapV2Pair.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}contracts/uniswap/IUniswapV2Router02.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
contracts/utils/AccessControl.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
contract AccessControl is Ownable {
using EnumerableSet for EnumerableSet.AddressSet;
/// @dev Allowed address list.
EnumerableSet.AddressSet private allowed;
/// @notice An event emitted when address allowed.
event AccessAllowed(address member);
/// @notice An event emitted when address denied.
event AccessDenied(address member);
/**
* @notice Allow access.
* @param member Target address.
*/
function allowAccess(address member) external onlyOwner {
require(!allowed.contains(member), "AccessControl::allowAccess: member already allowed");
allowed.add(member);
emit AccessAllowed(member);
}
/**
* @notice Deny access.
* @param member Target address.
*/
function denyAccess(address member) external onlyOwner {
require(allowed.contains(member), "AccessControl::denyAccess: member already denied");
allowed.remove(member);
emit AccessDenied(member);
}
/**
* @return Allowed address list.
*/
function accessList() external view returns (address[] memory) {
address[] memory result = new address[](allowed.length());
for (uint256 i = 0; i < allowed.length(); i++) {
result[i] = allowed.at(i);
}
return result;
}
/**
* @dev Throws if called by any account other than allowed.
*/
modifier onlyAllowed() {
require(allowed.contains(_msgSender()) || _msgSender() == owner(), "AccessControl: caller is not allowed");
_;
}
}
contracts/utils/OwnablePausable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
contract OwnablePausable is Ownable, Pausable {
/// @notice Address that can pause a contract.
address public pauser;
/// @notice An event thats emitted when an pauser address changed.
event PauserChanged(address newPauser);
constructor() internal {
pauser = owner();
}
/**
* @notice Change pauser account.
* @param newPauser Address of new pauser account.
*/
function changePauser(address newPauser) external onlyOwner {
pauser = newPauser;
emit PauserChanged(pauser);
}
/**
* @notice Triggers stopped state.
*/
function pause() public virtual {
require(pauser == _msgSender() || owner() == _msgSender(), "OwnablePausable::pause: only pauser and owner must pause contract");
_pause();
}
/**
* @notice Returns to normal state.
*/
function unpause() public virtual {
require(pauser == _msgSender() || owner() == _msgSender(), "OwnablePausable::unpause: only pauser and owner must unpause contract");
_unpause();
}
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": false
},
"evmVersion": "istanbul",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.