Created
November 2, 2020 20:13
-
-
Save alcuadrado/06c1ad0cf7e23758e17a32e829f26497 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"language": "Solidity", | |
"sources": { | |
"contracts/distribution/VELOStakingPool.sol": { | |
"content": "/**\n *Submitted for verification at Etherscan.io on 2020-07-17\n*/\n\n/*\n ____ __ __ __ _\n / __/__ __ ___ / /_ / / ___ / /_ (_)__ __\n _\\ \\ / // // _ \\/ __// _ \\/ -_)/ __// / \\ \\ /\n/___/ \\_, //_//_/\\__//_//_/\\__/ \\__//_/ /_\\_\\\n /___/\n\n* Synthetix: VELORewards.sol\n*\n* Docs: https://docs.synthetix.io/\n*\n*\n* MIT License\n* ===========\n*\n* Copyright (c) 2020 Synthetix\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in all\n* copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n*/\n\n// File: @openzeppelin/contracts/math/Math.sol\n\npragma solidity ^0.5.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a >= b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow, so we distribute\n return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);\n }\n}\n\n// File: @openzeppelin/contracts/math/SafeMath.sol\n\npragma solidity ^0.5.0;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n * - Subtraction cannot overflow.\n *\n * _Available since v2.4.0._\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n uint256 c = a - b;\n\n return c;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n *\n * _Available since v2.4.0._\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n // Solidity only automatically asserts when dividing by 0\n require(b > 0, errorMessage);\n uint256 c = a / b;\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n return c;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return mod(a, b, \"SafeMath: modulo by zero\");\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts with custom message when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n *\n * _Available since v2.4.0._\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b != 0, errorMessage);\n return a % b;\n }\n}\n\n// File: @openzeppelin/contracts/GSN/Context.sol\n\npragma solidity ^0.5.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\ncontract Context {\n // Empty internal constructor, to prevent people from mistakenly deploying\n // an instance of this contract, which should be used via inheritance.\n constructor () internal { }\n // solhint-disable-previous-line no-empty-blocks\n\n function _msgSender() internal view returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n}\n\n// File: @openzeppelin/contracts/ownership/Ownable.sol\n\npragma solidity ^0.5.0;\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\ncontract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor () internal {\n _owner = _msgSender();\n emit OwnershipTransferred(address(0), _owner);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(isOwner(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Returns true if the caller is the current owner.\n */\n function isOwner() public view returns (bool) {\n return _msgSender() == _owner;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public onlyOwner {\n emit OwnershipTransferred(_owner, address(0));\n _owner = address(0);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public onlyOwner {\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n */\n function _transferOwnership(address newOwner) internal {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n emit OwnershipTransferred(_owner, newOwner);\n _owner = newOwner;\n }\n}\n\n// File: @openzeppelin/contracts/token/ERC20/IERC20.sol\n\npragma solidity ^0.5.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP. Does not include\n * the optional functions; to access them see \\{ERC20Detailed}.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a \\{Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through \\{transferFrom}. This is\n * zero by default.\n *\n * This value changes when \\{approve} or \\{transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an \\{Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a \\{Transfer} event.\n */\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to \\{approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n\n// File: @openzeppelin/contracts/utils/Address.sol\n\npragma solidity ^0.5.5;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * This test is non-exhaustive, and there may be false-negatives: during the\n * execution of a contract's constructor, its address will be reported as\n * not containing a contract.\n *\n * IMPORTANT: It is unsafe to assume that an address for which this\n * function returns false is an externally-owned account (EOA) and not a\n * contract.\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies in extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n // According to EIP-1052, 0x0 is the value returned for not-yet created accounts\n // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned\n // for accounts without code, i.e. `keccak256('')`\n bytes32 codehash;\n bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\n // solhint-disable-next-line no-inline-assembly\n assembly { codehash := extcodehash(account) }\n return (codehash != 0x0 && codehash != accountHash);\n }\n\n /**\n * @dev Converts an `address` into `address payable`. Note that this is\n * simply a type cast: the actual underlying value is not changed.\n *\n * _Available since v2.4.0._\n */\n function toPayable(address account) internal pure returns (address payable) {\n return address(uint160(account));\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. \\{sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * \n * \\{ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n *\n * _Available since v2.4.0._\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-call-value\n (bool success, ) = recipient.call.value(amount)(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n}\n\n// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol\n\npragma solidity ^0.5.0;\n\n\n\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using SafeMath for uint256;\n using Address for address;\n\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n function safeApprove(IERC20 token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n // solhint-disable-next-line max-line-length\n require((value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).add(value);\n callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).sub(value, \"SafeERC20: decreased allowance below zero\");\n callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves.\n\n // A Solidity high level call has three parts:\n // 1. The target address is checked to verify it contains contract code\n // 2. The call itself is made, and success asserted\n // 3. The return value is decoded, which in turn checks the size of the returned data.\n // solhint-disable-next-line max-line-length\n require(address(token).isContract(), \"SafeERC20: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = address(token).call(data);\n require(success, \"SafeERC20: low-level call failed\");\n\n if (returndata.length > 0) { // Return data is optional\n // solhint-disable-next-line max-line-length\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n\n// File: contracts/IRewardDistributionRecipient.sol\n\npragma solidity ^0.5.0;\n\n\n\ncontract IRewardDistributionRecipient is Ownable {\n address public rewardDistribution;\n\n function notifyRewardAmount(uint256 reward) external;\n\n modifier onlyRewardDistribution() {\n require(_msgSender() == rewardDistribution, \"Caller is not reward distribution\");\n _;\n }\n\n function setRewardDistribution(address _rewardDistribution)\n external\n onlyOwner\n {\n rewardDistribution = _rewardDistribution;\n }\n}\n\n// File: contracts/CurveRewards.sol\n\npragma solidity ^0.5.0;\n\n\n\ninterface VELO {\n function velosScalingFactor() external returns (uint256);\n}\n\n\ncontract LPTokenWrapper {\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n\n IERC20 public erc20_token;\n\n uint256 private _totalSupply;\n mapping(address => uint256) private _balances;\n\n constructor(address _erc20_token_address) public {\n erc20_token = IERC20(_erc20_token_address);\n }\n\n function totalSupply() public view returns (uint256) {\n return _totalSupply;\n }\n\n function balanceOf(address account) public view returns (uint256) {\n return _balances[account];\n }\n\n function stake(uint256 amount) public {\n _totalSupply = _totalSupply.add(amount);\n _balances[msg.sender] = _balances[msg.sender].add(amount);\n erc20_token.safeTransferFrom(msg.sender, address(this), amount);\n }\n\n function withdraw(uint256 amount) public {\n _totalSupply = _totalSupply.sub(amount);\n _balances[msg.sender] = _balances[msg.sender].sub(amount);\n erc20_token.safeTransfer(msg.sender, amount);\n }\n}\n\ncontract VELOStakingPool is LPTokenWrapper, IRewardDistributionRecipient {\n IERC20 public velo;\n uint256 public duration; \n\n uint256 public starttime; \n uint256 public periodFinish = 0;\n uint256 public rewardRate = 0;\n uint256 public lastUpdateTime;\n uint256 public rewardPerTokenStored;\n mapping(address => uint256) public userRewardPerTokenPaid;\n mapping(address => uint256) public rewards;\n\n event RewardAdded(uint256 reward);\n event Staked(address indexed user, uint256 amount);\n event Withdrawn(address indexed user, uint256 amount);\n event RewardPaid(address indexed user, uint256 reward);\n\n\n constructor(address _velo, \n\t\taddress _erc20_token_address,\n\t\tuint256 _starttime,\n\t\tuint256 _duration) public \n LPTokenWrapper(_erc20_token_address)\n {\n velo = IERC20(_velo);\n starttime = _starttime;\n duration = _duration;\n }\n\n modifier checkStart() {\n require(block.timestamp >= starttime,\"not start\");\n _;\n }\n\n modifier updateReward(address account) {\n rewardPerTokenStored = rewardPerToken();\n lastUpdateTime = lastTimeRewardApplicable();\n if (account != address(0)) {\n rewards[account] = earned(account);\n userRewardPerTokenPaid[account] = rewardPerTokenStored;\n }\n _;\n }\n\n\n function lastTimeRewardApplicable() public view returns (uint256) {\n return Math.min(block.timestamp, periodFinish);\n }\n\n function rewardPerToken() public view returns (uint256) {\n if (totalSupply() == 0) {\n return rewardPerTokenStored;\n }\n return\n rewardPerTokenStored.add(\n lastTimeRewardApplicable()\n .sub(lastUpdateTime)\n .mul(rewardRate)\n .mul(1e18)\n .div(totalSupply())\n );\n }\n\n function earned(address account) public view returns (uint256) {\n return\n balanceOf(account)\n .mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))\n .div(1e18)\n .add(rewards[account]);\n }\n\n // stake visibility is public as overriding LPTokenWrapper's stake() function\n function stake(uint256 amount) public updateReward(msg.sender) checkStart {\n require(amount > 0, \"Cannot stake 0\");\n super.stake(amount);\n emit Staked(msg.sender, amount);\n }\n\n function withdraw(uint256 amount) public updateReward(msg.sender) checkStart {\n require(amount > 0, \"Cannot withdraw 0\");\n super.withdraw(amount);\n emit Withdrawn(msg.sender, amount);\n }\n\n function exit() external {\n withdraw(balanceOf(msg.sender));\n getReward();\n }\n\n function getReward() public updateReward(msg.sender) checkStart {\n uint256 reward = earned(msg.sender);\n if (reward > 0) {\n rewards[msg.sender] = 0;\n uint256 scalingFactor = VELO(address(velo)).velosScalingFactor();\n uint256 trueReward = reward.mul(scalingFactor).div(10**18);\n velo.safeTransfer(msg.sender, trueReward);\n emit RewardPaid(msg.sender, trueReward);\n }\n }\n\n function notifyRewardAmount(uint256 reward)\n external\n onlyRewardDistribution\n updateReward(address(0))\n {\n if (block.timestamp > starttime) {\n if (block.timestamp >= periodFinish) {\n rewardRate = reward.div(duration);\n } else {\n uint256 remaining = periodFinish.sub(block.timestamp);\n uint256 leftover = remaining.mul(rewardRate);\n rewardRate = reward.add(leftover).div(duration);\n }\n lastUpdateTime = block.timestamp;\n periodFinish = block.timestamp.add(duration);\n emit RewardAdded(reward);\n } else {\n rewardRate = reward.div(duration);\n lastUpdateTime = starttime;\n periodFinish = starttime.add(duration);\n emit RewardAdded(reward);\n }\n }\n}\n" | |
}, | |
"contracts/feeCharger/VELOFeeCharger.sol": { | |
"content": "pragma solidity 0.5.17;\n\nimport \"../lib/ICHI.sol\";\nimport {VELOTokenInterface as IVELO} from \"../token/VELOTokenInterface.sol\";\n\ncontract VELOFeeCharger {\n\n ICHI public constant chi = ICHI(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c);\n IVELO public velo;\n\n uint256 public govFactor;\n address public gov;\n address public beneficiary;\n\n uint256 public max_gas_block;\n uint256 public min_gas_tx;\n uint256 public gov_fee_factor;\n\n uint256 public last_block_number;\n uint256 public chi_fee_remaining;\n\n function setMaxGasBlock(uint256 value) public {\n max_gas_block = value;\n }\n\n function setMinGasTx(uint256 value) public {\n min_gas_tx = value;\n }\n\n function setGovFeeFactor(uint256 value) public {\n gov_fee_factor = value;\n }\n\n modifier onlyGov() {\n require(msg.sender == gov, \"!gov\");\n _;\n }\n\n constructor(address velo_) public {\n velo\t = IVELO(velo_);\n\n // government levers\n gov = msg.sender;\n gov_fee_factor = 1 * 10**18;\n max_gas_block = 135 * 10**18;\n min_gas_tx = 2 * 10**18;\n\n // tracking amount of chi charged\n // in a block.\n last_block_number = 0;\n chi_fee_remaining = 0;\n\n }\n\n function setGov(address newGov) external onlyGov {\n gov = newGov;\n }\n\n function setGovFactor(uint256 factor) external onlyGov {\n govFactor = factor;\n }\n\n function setBeneficiary(address beneficiary_) external onlyGov {\n beneficiary = beneficiary_;\n }\n\n function chargeFee(uint256 fEMA, uint256 sEMA, uint256 totalSupply, uint256 _amount) public {\n uint256 chi_fee = \n calc_fee_gas(max_gas_block, min_gas_tx, sEMA, _amount, totalSupply, gov_fee_factor);\n\n // count total amount of chi charges within a block. If the current\n // chi_fee charged in a block overflows the max_gas_block it will be\n // discounted to exactly max_gas_block\n if(last_block_number == block.number) {\n // protect against overflow\n if (chi_fee_remaining < chi_fee) {\n\tchi_fee = chi_fee_remaining;\n }\n chi_fee_remaining = chi_fee_remaining - chi_fee;\n } else {\n last_block_number = block.number;\n // the chi_fee can be maximal max_gas_block, limited\n // in the calc_fee_gas function. So no safe math needed\n // here.\n chi_fee_remaining = max_gas_block - chi_fee;\n }\n\n // velo token will only allow max_gas_block to be charged\n // we will not charge for transactions exceeding the max_gas_block\n // as we do not want transactions to fail because of the minting.\n if (chi_fee > 0 && beneficiary != address(0x0)) {\n // chi.mint needs tokens as a unit\n chi.mint(chi_fee / 10**18);\n chi.transfer(beneficiary, chi.balanceOf(address(this)));\n }\n }\n\n function calc_fee_ratio_discrete(\n uint256 ema1_vt,\n uint256 ema2_vt,\n uint256 tx_size,\n uint256 total_supply,\n uint256 _gov_fee_factor\n ) internal pure returns (uint256) {\n uint256 tx_discount_factor = ema2_vt;\n\n uint256 tx_fee_ratio = 10 * 10**18;\n\n if(tx_size <= total_supply / 596) {\n tx_fee_ratio = 6;\n } else if(tx_size <= total_supply / 369) {\n tx_fee_ratio = 9;\n } else if(tx_size <= total_supply / 228) {\n tx_fee_ratio = 15;\n } else if(tx_size <= total_supply / 141) {\n tx_fee_ratio = 23;\n } else if(tx_size <= total_supply / 87) {\n tx_fee_ratio = 37;\n } else if(tx_size <= total_supply / 54) {\n tx_fee_ratio = 55;\n } else if(tx_size <= total_supply / 33) {\n tx_fee_ratio = 76;\n } else if(tx_size <= total_supply / 21) {\n tx_fee_ratio = 92;\n } else if(tx_size <= total_supply / 13) {\n tx_fee_ratio = 98;\n } else if(tx_size <= total_supply / 6) {\n tx_fee_ratio = 99;\n } else {\n tx_fee_ratio = 100;\n }\n\n return ((tx_fee_ratio * tx_discount_factor / 100) * _gov_fee_factor)\n / 10**18;\n }\n\n // NOTE: we return and unscaled integer between roughly\n // 8 and 135 to approximate the gas fee for the\n // velocity transaction\n function calc_fee_gas(\n uint256 max_gas_block,\n uint256 min_gas_tx,\n uint256 ema_long,\n uint256 tx_size,\n uint256 total_supply,\n uint256 _gov_fee_factor\n ) public pure returns (uint256) {\n uint256 max_gas_chi_per_block = max_gas_block;\n uint256 min_gas_chi_fee_per_tx = min_gas_tx;\n\n uint256 tx_fee_ratio_disc =\n calc_fee_ratio_discrete(0, ema_long, tx_size, total_supply, _gov_fee_factor);\n\n uint256 tx_fee_chi_disc =\n max_gas_chi_per_block * tx_fee_ratio_disc / 100 / 10**18;\n\n if ( tx_fee_chi_disc < min_gas_chi_fee_per_tx ) {\n tx_fee_chi_disc = min_gas_chi_fee_per_tx;\n }\n\n return tx_fee_chi_disc;\n }\n}\n" | |
}, | |
"contracts/lib/ICHI.sol": { | |
"content": "pragma solidity ^0.5.17;\n\ninterface ICHI {\n function mint(uint256 value) external;\n function transfer(address, uint256) external returns(bool);\n function balanceOf(address) external view returns(uint256);\n}\n" | |
}, | |
"contracts/token/VELOTokenInterface.sol": { | |
"content": "pragma solidity 0.5.17;\n\nimport \"./VELOTokenStorage.sol\";\nimport \"./VELOGovernanceStorage.sol\";\n\ncontract VELOTokenInterface is VELOTokenStorage, VELOGovernanceStorage {\n\n /// @notice An event thats emitted when an account changes its delegate\n event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);\n\n /// @notice An event thats emitted when a delegate account's vote balance changes\n event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);\n\n /**\n * @notice Event emitted when tokens are rebased\n */\n event Rebase(uint256 prevVelosScalingFactor, uint256 newVelosScalingFactor);\n\n /*** Gov Events ***/\n\n /**\n * @notice Event emitted when pendingGov is changed\n */\n event NewPendingGov(address oldPendingGov, address newPendingGov);\n\n /**\n * @notice Event emitted when gov is changed\n */\n event NewGov(address oldGov, address newGov);\n\n /**\n * @notice Sets the rebaser contract\n */\n event NewRebaser(address oldRebaser, address newRebaser);\n\n /**\n * @notice Sets the incentivizer contract\n */\n event NewIncentivizer(address oldIncentivizer, address newIncentivizer);\n\n /* - ERC20 Events - */\n\n /**\n * @notice EIP20 Transfer event\n */\n event Transfer(address indexed from, address indexed to, uint amount);\n\n /**\n * @notice EIP20 Approval event\n */\n event Approval(address indexed owner, address indexed spender, uint amount);\n\n /* - Extra Events - */\n /**\n * @notice Tokens minted event\n */\n event Mint(address to, uint256 amount);\n\n // Public functions\n function transfer(address to, uint256 value) external returns(bool);\n function transferFrom(address from, address to, uint256 value) external returns(bool);\n function balanceOf(address who) external view returns(uint256);\n function balanceOfUnderlying(address who) external view returns(uint256);\n function allowance(address owner_, address spender) external view returns(uint256);\n function approve(address spender, uint256 value) external returns (bool);\n function increaseAllowance(address spender, uint256 addedValue) external returns (bool);\n function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);\n function maxScalingFactor() external view returns (uint256);\n\n /* - Governance Functions - */\n function getPriorVotes(address account, uint blockNumber) external view returns (uint256);\n function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;\n function delegate(address delegatee) external;\n function delegates(address delegator) external view returns (address);\n function getCurrentVotes(address account) external view returns (uint256);\n\n /* - Permissioned/Governance functions - */\n function mint(address to, uint256 amount) external returns (bool);\n function _setPendingGov(address pendingGov_) external;\n function setGov(address gov_) external;\n function _acceptGov() external;\n\n\n /* - Custom rebaser implementation - */\n function setRebaser(address rebaser_) external;\n // FIXME: setFeeCharger??\n\n /* rebaser */\n function rebase(uint256 scaling_modifier) external;\n}\n" | |
}, | |
"contracts/token/VELOTokenStorage.sol": { | |
"content": "pragma solidity 0.5.17;\n\nimport \"../lib/SafeMath.sol\";\n\n// Storage for a VELO token\ncontract VELOTokenStorage {\n\n using SafeMath for uint256;\n\n /**\n * @dev Guard variable for re-entrancy checks. Not currently used\n */\n bool internal _notEntered;\n\n /**\n * @notice EIP-20 token name for this token\n */\n string public name;\n\n /**\n * @notice EIP-20 token symbol for this token\n */\n string public symbol;\n\n /**\n * @notice EIP-20 token decimals for this token\n */\n uint8 public decimals;\n\n /**\n * @notice Governor for this contract\n */\n address public gov;\n\n /**\n * @notice Pending governance for this contract\n */\n address public pendingGov;\n\n /**\n * @notice Approved rebaser for this contract\n */\n address public rebaser;\n\n /**\n * @notice Total supply of VELOs\n */\n uint256 public totalSupply;\n\n /**\n * @notice Internal decimals used to handle scaling factor\n */\n uint256 public constant internalDecimals = 10**18;\n\n /**\n * @notice Used for percentage maths\n */\n uint256 public constant BASE = 10**18;\n\n /**\n * @notice Scaling factor that adjusts everyone's balances\n */\n uint256 public velosScalingFactor;\n\n mapping (address => uint256) internal _veloBalances;\n\n mapping (address => mapping (address => uint256)) internal _allowedFragments;\n\n uint256 public initSupply;\n\n address public feeCharger;\n\n\n\n}\n" | |
}, | |
"contracts/token/VELOGovernanceStorage.sol": { | |
"content": "pragma solidity 0.5.17;\npragma experimental ABIEncoderV2;\n\ncontract VELOGovernanceStorage {\n /// @notice A record of each accounts delegate\n mapping (address => address) internal _delegates;\n\n /// @notice A checkpoint for marking number of votes from a given block\n struct Checkpoint {\n uint32 fromBlock;\n uint256 votes;\n }\n\n /// @notice A record of votes checkpoints for each account, by index\n mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;\n\n /// @notice The number of checkpoints for each account\n mapping (address => uint32) public numCheckpoints;\n\n /// @notice The EIP-712 typehash for the contract's domain\n bytes32 public constant DOMAIN_TYPEHASH = keccak256(\"EIP712Domain(string name,uint256 chainId,address verifyingContract)\");\n\n /// @notice The EIP-712 typehash for the delegation struct used by the contract\n bytes32 public constant DELEGATION_TYPEHASH = keccak256(\"Delegation(address delegatee,uint256 nonce,uint256 expiry)\");\n\n /// @notice A record of states for signing / validating signatures\n mapping (address => uint) public nonces;\n}\n" | |
}, | |
"contracts/lib/SafeMath.sol": { | |
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.5.17;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n uint256 c = a - b;\n\n return c;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n uint256 c = a / b;\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n return c;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return mod(a, b, \"SafeMath: modulo by zero\");\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts with custom message when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b != 0, errorMessage);\n return a % b;\n }\n}\n" | |
}, | |
"contracts/token/VELO.sol": { | |
"content": "pragma solidity 0.5.17;\n\n/* import \"./VELOTokenInterface.sol\"; */\nimport \"./VELOGovernance.sol\";\nimport \"../feeCharger/VELOFeeCharger.sol\";\nimport \"../lib/IRebaser.sol\";\n\n\nlibrary Math {\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a >= b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n}\n\n\ncontract VELOToken is VELOGovernanceToken {\n // Modifiers\n modifier onlyGov() {\n require(msg.sender == gov);\n _;\n }\n\n modifier onlyRebaser() {\n require(msg.sender == rebaser);\n _;\n }\n\n modifier onlyMinter() {\n require(msg.sender == rebaser || msg.sender == gov, \"not minter\");\n _;\n }\n\n modifier validRecipient(address to) {\n require(to != address(0x0));\n require(to != address(this));\n _;\n }\n\n function initialize(\n string memory name_,\n string memory symbol_,\n uint8 decimals_\n )\n public\n {\n require(velosScalingFactor == 0, \"already initialized\");\n name = name_;\n symbol = symbol_;\n decimals = decimals_;\n }\n\n\n /**\n * @notice Computes the current max scaling factor\n */\n function maxScalingFactor()\n external\n view\n returns (uint256)\n {\n return _maxScalingFactor();\n }\n\n function _maxScalingFactor()\n internal\n view\n returns (uint256)\n {\n // scaling factor can only go up to 2**256-1 = initSupply * velosScalingFactor\n // this is used to check if velosScalingFactor will be too high to compute balances when rebasing.\n return uint256(-1) / initSupply;\n }\n\n /**\n * @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.\n * @dev Limited to onlyMinter modifier\n */\n function mint(address to, uint256 amount)\n external\n onlyMinter\n returns (bool)\n {\n _mint(to, amount);\n return true;\n }\n\n function _mint(address to, uint256 amount)\n internal\n {\n // increase totalSupply\n totalSupply = totalSupply.add(amount);\n\n // get underlying value\n uint256 veloValue = amount.mul(internalDecimals).div(velosScalingFactor);\n\n // increase initSupply\n initSupply = initSupply.add(veloValue);\n\n // make sure the mint didnt push maxScalingFactor too low\n require(velosScalingFactor <= _maxScalingFactor(), \"max scaling factor too low\");\n\n // add balance\n _veloBalances[to] = _veloBalances[to].add(veloValue);\n\n // add delegates to the minter\n _moveDelegates(address(0), _delegates[to], veloValue);\n emit Mint(to, amount);\n }\n\n /* - ERC20 functionality - */\n\n /**\n * @dev Transfer tokens to a specified address.\n * @param to The address to transfer to.\n * @param value The amount to be transferred.\n * @return True on success, false otherwise.\n */\n function transfer(address to, uint256 value)\n external\n validRecipient(to)\n returns (bool)\n {\n // underlying balance is stored in velos, so divide by current scaling factor\n\n // note, this means as scaling factor grows, dust will be untransferrable.\n // minimum transfer value == velosScalingFactor / 1e24;\n\n // get amount in underlying\n uint256 veloValue = value.mul(internalDecimals).div(velosScalingFactor);\n\n // sub from balance of sender\n _veloBalances[msg.sender] = _veloBalances[msg.sender].sub(veloValue);\n\n // add to balance of receiver\n _veloBalances[to] = _veloBalances[to].add(veloValue);\n emit Transfer(msg.sender, to, value);\n\n _moveDelegates(_delegates[msg.sender], _delegates[to], veloValue);\n\n\t// this avoids building up velocity\n\t// when deployting the contract\n if(msg.sender != gov) {\n IRebaser rb = IRebaser(rebaser);\n rb.registerVelocity(value);\n VELOFeeCharger(feeCharger).chargeFee(rb.fEMA(), rb.sEMA(), totalSupply, value);\n } \n\n return true;\n }\n\n /**\n * @dev Transfer tokens from one address to another.\n * @param from The address you want to send tokens from.\n * @param to The address you want to transfer to.\n * @param value The amount of tokens to be transferred.\n */\n function transferFrom(address from, address to, uint256 value)\n external\n validRecipient(to)\n returns (bool)\n {\n // decrease allowance, boundaries are enforced by SafeMath and the usage\n\t// of uint256\n _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender]\n\t\t\t\t\t\t.sub(value);\n\n // get value in velos\n uint256 veloValue = value.mul(internalDecimals).div(velosScalingFactor);\n\n // sub from from\n _veloBalances[from] = _veloBalances[from].sub(veloValue);\n _veloBalances[to] = _veloBalances[to].add(veloValue);\n emit Transfer(from, to, value);\n\n _moveDelegates(_delegates[from], _delegates[to], veloValue);\n\n\t// we do not want to count velocity on initial\n\t// distribution, or when gov is moving tokens\n if(msg.sender != gov) {\n IRebaser rb = IRebaser(rebaser);\n rb.registerVelocity(value);\n VELOFeeCharger(feeCharger).chargeFee(rb.fEMA(), rb.sEMA(), totalSupply, value);\n }\n\n return true;\n }\n\n /**\n * @param who The address to query.\n * @return The balance of the specified address.\n */\n function balanceOf(address who)\n external\n view\n returns (uint256)\n {\n return _veloBalances[who].mul(velosScalingFactor).div(internalDecimals);\n }\n\n /** @notice Currently returns the internal storage amount\n * @param who The address to query.\n * @return The underlying balance of the specified address.\n */\n function balanceOfUnderlying(address who)\n external\n view\n returns (uint256)\n {\n return _veloBalances[who];\n }\n\n /**\n * @dev Function to check the amount of tokens that an owner has allowed to a spender.\n * @param owner_ The address which owns the funds.\n * @param spender The address which will spend the funds.\n * @return The number of tokens still available for the spender.\n */\n function allowance(address owner_, address spender)\n external\n view\n returns (uint256)\n {\n return _allowedFragments[owner_][spender];\n }\n\n /**\n * @dev Approve the passed address to spend the specified amount of tokens on behalf of\n * msg.sender. This method is included for ERC20 compatibility.\n * increaseAllowance and decreaseAllowance should be used instead.\n * Changing an allowance with this method brings the risk that someone may transfer both\n * the old and the new allowance - if they are both greater than zero - if a transfer\n * transaction is mined before the later approve() call is mined.\n *\n * @param spender The address which will spend the funds.\n * @param value The amount of tokens to be spent.\n */\n function approve(address spender, uint256 value)\n external\n returns (bool)\n {\n _allowedFragments[msg.sender][spender] = value;\n emit Approval(msg.sender, spender, value);\n return true;\n }\n\n /**\n * @dev Increase the amount of tokens that an owner has allowed to a spender.\n * This method should be used instead of approve() to avoid the double approval vulnerability\n * described above.\n * @param spender The address which will spend the funds.\n * @param addedValue The amount of tokens to increase the allowance by.\n */\n function increaseAllowance(address spender, uint256 addedValue)\n external\n returns (bool)\n {\n _allowedFragments[msg.sender][spender] =\n _allowedFragments[msg.sender][spender].add(addedValue);\n emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);\n return true;\n }\n\n /**\n * @dev Decrease the amount of tokens that an owner has allowed to a spender.\n *\n * @param spender The address which will spend the funds.\n * @param subtractedValue The amount of tokens to decrease the allowance by.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue)\n external\n returns (bool)\n {\n uint256 oldValue = _allowedFragments[msg.sender][spender];\n if (subtractedValue >= oldValue) {\n _allowedFragments[msg.sender][spender] = 0;\n } else {\n _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);\n }\n emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);\n return true;\n }\n\n /* - Governance Functions - */\n\n /** @notice sets the rebaser\n * @param rebaser_ The address of the rebaser contract to use for authentication.\n */\n function setRebaser(address rebaser_)\n external\n onlyGov\n {\n address oldRebaser = rebaser;\n rebaser = rebaser_;\n emit NewRebaser(oldRebaser, rebaser_);\n }\n\n // FIXME: normalize the underscore usage\n function setFeeCharger(address feeCharger_)\n external\n onlyGov\n {\n feeCharger = feeCharger_;\n }\n\n /** @notice sets the pendingGov\n * @param pendingGov_ The address of the rebaser contract to use for authentication.\n */\n function _setPendingGov(address pendingGov_)\n external\n onlyGov\n {\n address oldPendingGov = pendingGov;\n pendingGov = pendingGov_;\n emit NewPendingGov(oldPendingGov, pendingGov_);\n }\n\n function setGov(address gov_) external onlyGov {\n gov = gov_;\n }\n\n /** @notice lets msg.sender accept governance\n *\n */\n function _acceptGov()\n external\n {\n require(msg.sender == pendingGov, \"!pending\");\n address oldGov = gov;\n gov = pendingGov;\n pendingGov = address(0);\n emit NewGov(oldGov, gov);\n }\n\n /* - Rebase function - */\n function rebase(uint256 scaling_modifier)\n external\n\tonlyRebaser\n { \n\t\n uint256 prevVelosScalingFactor = velosScalingFactor;\n\n\t// velosScalingFactor is in precision 24\n velosScalingFactor = velosScalingFactor\n\t .mul(scaling_modifier)\n\t\t\t\t.div(internalDecimals);\n\n\tvelosScalingFactor = Math.min(velosScalingFactor, 1 * internalDecimals);\n\n\ttotalSupply = initSupply.mul(velosScalingFactor).div(internalDecimals);\n\n emit Rebase(prevVelosScalingFactor, velosScalingFactor);\n }\n\n}\n\ncontract VELO is VELOToken {\n /**\n * @notice Initialize the new money market\n * @param name_ ERC-20 name of this token\n * @param symbol_ ERC-20 symbol of this token\n * @param decimals_ ERC-20 decimal precision of this token\n */\n function initialize(\n string memory name_,\n string memory symbol_,\n uint8 decimals_,\n address initial_owner,\n uint256 initSupply_\n )\n public\n {\n require(initSupply_ > 0, \"0 init supply\");\n\n super.initialize(name_, symbol_, decimals_);\n\n initSupply = initSupply_; //.mul(10**24 / (BASE));\n totalSupply = initSupply_;\n velosScalingFactor = BASE;\n _veloBalances[initial_owner] = initSupply_; //.mul(10**24 / (BASE));\n\n emit Transfer(address(0), msg.sender, initSupply_);\n\n // owner renounces ownership after deployment as they need to set\n // rebaser and incentivizer\n // gov = gov_;\n }\n}\n" | |
}, | |
"contracts/token/VELOGovernance.sol": { | |
"content": "pragma solidity 0.5.17;\npragma experimental ABIEncoderV2;\n\nimport \"./VELOGovernanceStorage.sol\";\nimport \"./VELOTokenInterface.sol\";\n\ncontract VELOGovernanceToken is VELOTokenInterface {\n\n /// @notice An event thats emitted when an account changes its delegate\n event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);\n\n /// @notice An event thats emitted when a delegate account's vote balance changes\n event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);\n\n /**\n * @notice Delegate votes from `msg.sender` to `delegatee`\n * @param delegator The address to get delegatee for\n */\n function delegates(address delegator)\n external\n view\n returns (address)\n {\n return _delegates[delegator];\n }\n\n /**\n * @notice Delegate votes from `msg.sender` to `delegatee`\n * @param delegatee The address to delegate votes to\n */\n function delegate(address delegatee) external {\n return _delegate(msg.sender, delegatee);\n }\n\n /**\n * @notice Delegates votes from signatory to `delegatee`\n * @param delegatee The address to delegate votes to\n * @param nonce The contract state required to match the signature\n * @param expiry The time at which to expire the signature\n * @param v The recovery byte of the signature\n * @param r Half of the ECDSA signature pair\n * @param s Half of the ECDSA signature pair\n */\n function delegateBySig(\n address delegatee,\n uint nonce,\n uint expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\n )\n external\n {\n bytes32 domainSeparator = keccak256(\n abi.encode(\n DOMAIN_TYPEHASH,\n keccak256(bytes(name)),\n getChainId(),\n address(this)\n )\n );\n\n bytes32 structHash = keccak256(\n abi.encode(\n DELEGATION_TYPEHASH,\n delegatee,\n nonce,\n expiry\n )\n );\n\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n domainSeparator,\n structHash\n )\n );\n\n address signatory = ecrecover(digest, v, r, s);\n require(signatory != address(0), \"VELO::delegateBySig: invalid signature\");\n require(nonce == nonces[signatory]++, \"VELO::delegateBySig: invalid nonce\");\n require(now <= expiry, \"VELO::delegateBySig: signature expired\");\n return _delegate(signatory, delegatee);\n }\n\n /**\n * @notice Gets the current votes balance for `account`\n * @param account The address to get votes balance\n * @return The number of current votes for `account`\n */\n function getCurrentVotes(address account)\n external\n view\n returns (uint256)\n {\n uint32 nCheckpoints = numCheckpoints[account];\n return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;\n }\n\n /**\n * @notice Determine the prior number of votes for an account as of a block number\n * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.\n * @param account The address of the account to check\n * @param blockNumber The block number to get the vote balance at\n * @return The number of votes the account had as of the given block\n */\n function getPriorVotes(address account, uint blockNumber)\n external\n view\n returns (uint256)\n {\n require(blockNumber < block.number, \"VELO::getPriorVotes: not yet determined\");\n\n uint32 nCheckpoints = numCheckpoints[account];\n if (nCheckpoints == 0) {\n return 0;\n }\n\n // First check most recent balance\n if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {\n return checkpoints[account][nCheckpoints - 1].votes;\n }\n\n // Next check implicit zero balance\n if (checkpoints[account][0].fromBlock > blockNumber) {\n return 0;\n }\n\n uint32 lower = 0;\n uint32 upper = nCheckpoints - 1;\n while (upper > lower) {\n uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow\n Checkpoint memory cp = checkpoints[account][center];\n if (cp.fromBlock == blockNumber) {\n return cp.votes;\n } else if (cp.fromBlock < blockNumber) {\n lower = center;\n } else {\n upper = center - 1;\n }\n }\n return checkpoints[account][lower].votes;\n }\n\n function _delegate(address delegator, address delegatee)\n internal\n {\n address currentDelegate = _delegates[delegator];\n uint256 delegatorBalance = _veloBalances[delegator]; // balance of underlying VELOs (not scaled);\n _delegates[delegator] = delegatee;\n\n emit DelegateChanged(delegator, currentDelegate, delegatee);\n\n _moveDelegates(currentDelegate, delegatee, delegatorBalance);\n }\n\n function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {\n if (srcRep != dstRep && amount > 0) {\n if (srcRep != address(0)) {\n // decrease old representative\n uint32 srcRepNum = numCheckpoints[srcRep];\n uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;\n uint256 srcRepNew = srcRepOld.sub(amount);\n _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);\n }\n\n if (dstRep != address(0)) {\n // increase new representative\n uint32 dstRepNum = numCheckpoints[dstRep];\n uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;\n uint256 dstRepNew = dstRepOld.add(amount);\n _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);\n }\n }\n }\n\n function _writeCheckpoint(\n address delegatee,\n uint32 nCheckpoints,\n uint256 oldVotes,\n uint256 newVotes\n )\n internal\n {\n uint32 blockNumber = safe32(block.number, \"VELO::_writeCheckpoint: block number exceeds 32 bits\");\n\n if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {\n checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;\n } else {\n checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);\n numCheckpoints[delegatee] = nCheckpoints + 1;\n }\n\n emit DelegateVotesChanged(delegatee, oldVotes, newVotes);\n }\n\n function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {\n require(n < 2**32, errorMessage);\n return uint32(n);\n }\n\n function getChainId() internal pure returns (uint) {\n uint256 chainId;\n assembly { chainId := chainid() }\n return chainId;\n }\n}\n" | |
}, | |
"contracts/lib/IRebaser.sol": { | |
"content": "pragma solidity 0.5.17;\n\ninterface IRebaser {\n function registerVelocity(uint256 amount) external;\n function sEMA() external view returns (uint256); \n function fEMA() external view returns (uint256); \n}\n" | |
}, | |
"contracts/token/VELODelegate.sol": { | |
"content": "pragma solidity 0.5.17;\n\nimport \"./VELO.sol\";\n\ncontract VELODelegationStorage {\n /**\n * @notice Implementation address for this contract\n */\n address public implementation;\n}\n\ncontract VELODelegatorInterface is VELODelegationStorage {\n /**\n * @notice Emitted when implementation is changed\n */\n event NewImplementation(address oldImplementation, address newImplementation);\n\n /**\n * @notice Called by the gov to update the implementation of the delegator\n * @param implementation_ The address of the new implementation for delegation\n * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation\n * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation\n */\n function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;\n}\n\ncontract VELODelegateInterface is VELODelegationStorage {\n /**\n * @notice Called by the delegator on a delegate to initialize it for duty\n * @dev Should revert if any issues arise which make it unfit for delegation\n * @param data The encoded bytes data for any initialization\n */\n function _becomeImplementation(bytes memory data) public;\n\n /**\n * @notice Called by the delegator on a delegate to forfeit its responsibility\n */\n function _resignImplementation() public;\n}\n\n\ncontract VELODelegate is VELO, VELODelegateInterface {\n /**\n * @notice Construct an empty delegate\n */\n constructor() public {}\n\n /**\n * @notice Called by the delegator on a delegate to initialize it for duty\n * @param data The encoded bytes data for any initialization\n */\n function _becomeImplementation(bytes memory data) public {\n // Shh -- currently unused\n data;\n\n // Shh -- we don't ever want this hook to be marked pure\n if (false) {\n implementation = address(0);\n }\n\n require(msg.sender == gov, \"only the gov may call _becomeImplementation\");\n }\n\n /**\n * @notice Called by the delegator on a delegate to forfeit its responsibility\n */\n function _resignImplementation() public {\n // Shh -- we don't ever want this hook to be marked pure\n if (false) {\n implementation = address(0);\n }\n\n require(msg.sender == gov, \"only the gov may call _resignImplementation\");\n }\n}\n" | |
}, | |
"contracts/token/VELODelegator.sol": { | |
"content": "pragma solidity 0.5.17;\n\nimport \"./VELOTokenInterface.sol\";\nimport \"./VELODelegate.sol\";\n\ncontract VELODelegator is VELOTokenInterface, VELODelegatorInterface {\n /**\n * @notice Construct a new VELO\n * @param name_ ERC-20 name of this token\n * @param symbol_ ERC-20 symbol of this token\n * @param decimals_ ERC-20 decimal precision of this token\n * @param initSupply_ Initial token amount\n * @param implementation_ The address of the implementation the contract delegates to\n * @param becomeImplementationData The encoded args for becomeImplementation\n */\n constructor(\n string memory name_,\n string memory symbol_,\n uint8 decimals_,\n uint256 initSupply_,\n address implementation_,\n bytes memory becomeImplementationData\n )\n public\n {\n\n\n // Creator of the contract is gov during initialization\n gov = msg.sender;\n\n // First delegate gets to initialize the delegator (i.e. storage contract)\n delegateTo(\n implementation_,\n abi.encodeWithSignature(\n \"initialize(string,string,uint8,address,uint256)\",\n name_,\n symbol_,\n decimals_,\n msg.sender,\n initSupply_\n )\n );\n\n // New implementations always get set via the settor (post-initialize)\n _setImplementation(implementation_, false, becomeImplementationData);\n\n }\n\n /**\n * @notice Called by the gov to update the implementation of the delegator\n * @param implementation_ The address of the new implementation for delegation\n * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation\n * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation\n */\n function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {\n require(msg.sender == gov, \"VELODelegator::_setImplementation: Caller must be gov\");\n\n if (allowResign) {\n delegateToImplementation(abi.encodeWithSignature(\"_resignImplementation()\"));\n }\n\n address oldImplementation = implementation;\n implementation = implementation_;\n\n delegateToImplementation(abi.encodeWithSignature(\"_becomeImplementation(bytes)\", becomeImplementationData));\n\n emit NewImplementation(oldImplementation, implementation);\n }\n\n /**\n * @notice Sender supplies assets into the market and receives cTokens in exchange\n * @dev Accrues interest whether or not the operation succeeds, unless reverted\n * @param mintAmount The amount of the underlying asset to supply\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function mint(address to, uint256 mintAmount)\n external\n returns (bool)\n {\n to; mintAmount; // Shh\n delegateAndReturn();\n }\n\n /**\n * @notice Transfer `amount` tokens from `msg.sender` to `dst`\n * @param dst The address of the destination account\n * @param amount The number of tokens to transfer\n * @return Whether or not the transfer succeeded\n */\n function transfer(address dst, uint256 amount)\n external\n returns (bool)\n {\n dst; amount; // Shh\n delegateAndReturn();\n }\n\n /**\n * @notice Transfer `amount` tokens from `src` to `dst`\n * @param src The address of the source account\n * @param dst The address of the destination account\n * @param amount The number of tokens to transfer\n * @return Whether or not the transfer succeeded\n */\n function transferFrom(\n address src,\n address dst,\n uint256 amount\n )\n external\n returns (bool)\n {\n src; dst; amount; // Shh\n delegateAndReturn();\n }\n\n /**\n * @notice Approve `spender` to transfer up to `amount` from `src`\n * @dev This will overwrite the approval amount for `spender`\n * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\n * @param spender The address of the account which may transfer tokens\n * @param amount The number of tokens that are approved (-1 means infinite)\n * @return Whether or not the approval succeeded\n */\n function approve(\n address spender,\n uint256 amount\n )\n external\n returns (bool)\n {\n spender; amount; // Shh\n delegateAndReturn();\n }\n\n /**\n * @dev Increase the amount of tokens that an owner has allowed to a spender.\n * This method should be used instead of approve() to avoid the double approval vulnerability\n * described above.\n * @param spender The address which will spend the funds.\n * @param addedValue The amount of tokens to increase the allowance by.\n */\n function increaseAllowance(\n address spender,\n uint256 addedValue\n )\n external\n returns (bool)\n {\n spender; addedValue; // Shh\n delegateAndReturn();\n }\n\n function maxScalingFactor()\n external\n view\n returns (uint256)\n {\n delegateToViewAndReturn();\n }\n\n /**\n * @dev Decrease the amount of tokens that an owner has allowed to a spender.\n *\n * @param spender The address which will spend the funds.\n * @param subtractedValue The amount of tokens to decrease the allowance by.\n */\n function decreaseAllowance(\n address spender,\n uint256 subtractedValue\n )\n external\n returns (bool)\n {\n spender; subtractedValue; // Shh\n delegateAndReturn();\n }\n\n /**\n * @notice Get the current allowance from `owner` for `spender`\n * @param owner The address of the account which owns the tokens to be spent\n * @param spender The address of the account which may transfer tokens\n * @return The number of tokens allowed to be spent (-1 means infinite)\n */\n function allowance(\n address owner,\n address spender\n )\n external\n view\n returns (uint256)\n {\n owner; spender; // Shh\n delegateToViewAndReturn();\n }\n\n /**\n * @notice Get the current allowance from `owner` for `spender`\n * @param delegator The address of the account which has designated a delegate\n * @return Address of delegatee\n */\n function delegates(\n address delegator\n )\n external\n view\n returns (address)\n {\n delegator; // Shh\n delegateToViewAndReturn();\n }\n\n /**\n * @notice Get the token balance of the `owner`\n * @param owner The address of the account to query\n * @return The number of tokens owned by `owner`\n */\n function balanceOf(address owner)\n external\n view\n returns (uint256)\n {\n owner; // Shh\n delegateToViewAndReturn();\n }\n\n /**\n * @notice Currently unused. For future compatability\n * @param owner The address of the account to query\n * @return The number of underlying tokens owned by `owner`\n */\n function balanceOfUnderlying(address owner)\n external\n view\n returns (uint256)\n {\n owner; // Shh\n delegateToViewAndReturn();\n }\n\n /*** Gov Functions ***/\n\n /**\n * @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.\n * @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.\n * @param newPendingGov New pending gov.\n */\n function _setPendingGov(address newPendingGov)\n external\n {\n newPendingGov; // Shh\n delegateAndReturn();\n }\n\n function setRebaser(address rebaser_)\n external\n {\n rebaser_; // Shh\n delegateAndReturn();\n }\n\n function _setIncentivizer(address incentivizer_)\n external\n {\n incentivizer_; // Shh\n delegateAndReturn();\n }\n\n /**\n * @notice Accepts transfer of gov rights. msg.sender must be pendingGov\n * @dev Gov function for pending gov to accept role and update gov\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function _acceptGov()\n external\n {\n delegateAndReturn();\n }\n\n function setGov(address gov_) external {\n gov_;\n delegateAndReturn();\n }\n\n function rebase(uint256 scaling_modifier) external {\n delegateAndReturn();\n }\n\n function setFeeCharger(\n address feeCharger_\n ) external {\n feeCharger_;\n delegateAndReturn();\n }\n\n\n function getPriorVotes(address account, uint blockNumber)\n external\n view\n returns (uint256)\n {\n account; blockNumber;\n delegateToViewAndReturn();\n }\n\n function delegateBySig(\n address delegatee,\n uint nonce,\n uint expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\n )\n external\n {\n delegatee; nonce; expiry; v; r; s;\n delegateAndReturn();\n }\n\n function delegate(address delegatee)\n external\n {\n delegatee;\n delegateAndReturn();\n }\n\n function getCurrentVotes(address account)\n external\n view\n returns (uint256)\n {\n account;\n delegateToViewAndReturn();\n }\n\n /**\n * @notice Internal method to delegate execution to another contract\n * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n * @param callee The contract to delegatecall\n * @param data The raw data to delegatecall\n * @return The returned bytes from the delegatecall\n */\n function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returnData) = callee.delegatecall(data);\n assembly {\n if eq(success, 0) {\n revert(add(returnData, 0x20), returndatasize)\n }\n }\n return returnData;\n }\n\n /**\n * @notice Delegates execution to the implementation contract\n * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n * @param data The raw data to delegatecall\n * @return The returned bytes from the delegatecall\n */\n function delegateToImplementation(bytes memory data) public returns (bytes memory) {\n return delegateTo(implementation, data);\n }\n\n /**\n * @notice Delegates execution to an implementation contract\n * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.\n * @param data The raw data to delegatecall\n * @return The returned bytes from the delegatecall\n */\n function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {\n (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature(\"delegateToImplementation(bytes)\", data));\n assembly {\n if eq(success, 0) {\n revert(add(returnData, 0x20), returndatasize)\n }\n }\n return abi.decode(returnData, (bytes));\n }\n\n function delegateToViewAndReturn() private view returns (bytes memory) {\n (bool success, ) = address(this).staticcall(abi.encodeWithSignature(\"delegateToImplementation(bytes)\", msg.data));\n\n assembly {\n let free_mem_ptr := mload(0x40)\n returndatacopy(free_mem_ptr, 0, returndatasize)\n\n switch success\n case 0 { revert(free_mem_ptr, returndatasize) }\n default { return(add(free_mem_ptr, 0x40), returndatasize) }\n }\n }\n\n function delegateAndReturn() private returns (bytes memory) {\n (bool success, ) = implementation.delegatecall(msg.data);\n\n assembly {\n let free_mem_ptr := mload(0x40)\n returndatacopy(free_mem_ptr, 0, returndatasize)\n\n switch success\n case 0 { revert(free_mem_ptr, returndatasize) }\n default { return(free_mem_ptr, returndatasize) }\n }\n }\n\n /**\n * @notice Delegates execution to an implementation contract\n * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n */\n function () external payable {\n require(msg.value == 0,\"VELODelegator:fallback: cannot send value to fallback\");\n\n // delegate all other functions to current implementation\n delegateAndReturn();\n }\n}\n" | |
}, | |
"contracts/rebaser/VELORebaser.sol": { | |
"content": "pragma solidity 0.5.17;\npragma experimental ABIEncoderV2;\n\nimport \"../lib/SafeERC20.sol\";\nimport \"../lib/SafeMath.sol\";\nimport {VELOTokenInterface as IVELO} from \"../token/VELOTokenInterface.sol\";\nimport { ABDKMath64x64 as fp } from \"../lib/ABDKMath64x64.sol\";\n\ncontract VELORebaser {\n using SafeMath for uint256;\n using fp for int128;\n\n uint256 public lastRebase;\n\n uint256 public REBASE_INTERVAL;\n uint256 public START_REBASE_AT;\n\n uint256 public constant C = 1618033988700000000;\n uint256 public constant K = 15000000000000000000;\n\n uint256 public constant Ls = 64410000000000000; // 0.07613 Slow EMA\n uint256 public constant Lf = 76130000000000000; // 0.06441 Fast EMA\n\n uint256 public sEMA;\n uint256 public fEMA;\n\n uint256 public velocity;\n\n uint256 public constant PRECISION = 10**18;\n\n address public VELO;\n\n /// @notice Governance address\n address public gov;\n\n // Stable ordering is not guaranteed.\n Transaction[] public transactions;\n\n // TODO rebase events\n\n struct Transaction {\n address destination;\n bytes data;\n }\n\n modifier onlyGov() {\n require(msg.sender == gov, \"!gov\");\n _;\n }\n\n modifier onlyVELO() {\n require(msg.sender == VELO, \"!velo\");\n _;\n }\n\n constructor(\n address _VELO,\n uint256 _rebase_interval,\n uint256 _start_rebase_at\n ) public {\n VELO = _VELO;\n gov = msg.sender;\n REBASE_INTERVAL = _rebase_interval;\n START_REBASE_AT = _start_rebase_at;\n }\n\n function setGov(address newGov) external onlyGov {\n gov = newGov;\n }\n\n function addTransaction(address destination, bytes memory data) public onlyGov {\n transactions.push(Transaction({\n destination: destination,\n data: data\n }));\n }\n\n function removeTransaction(uint256 index) external onlyGov {\n transactions[index] = transactions[transactions.length];\n transactions.pop();\n }\n\n function registerVelocity(uint256 amount) external onlyVELO {\n velocity = velocity.add(amount);\n }\n\n // returns velocity in scaled units\n function getVelocity() external view returns (uint256) {\n return velocity;\n }\n\n function getRelativeVelocity() external view returns (uint256) {\n IVELO velo_token = IVELO(VELO);\n\n // calculate the Vt, an limit the ranges\n uint256 Vt = velocity.mul(100 * PRECISION).div(velo_token.totalSupply());\n if(Vt > 100 * PRECISION ) {\n Vt = 100 * PRECISION;\n }\n\n return Vt;\n }\n\n\n function calcEMA(uint256 Vt_1, uint256 Vt, uint256 L) private pure returns(uint256) {\n return (Vt * L) / PRECISION + ((PRECISION - L) * Vt_1) / PRECISION;\n }\n\n function rebase() public {\n require(block.timestamp >= START_REBASE_AT, \"Rebase not allowed yet\");\n require(block.timestamp - lastRebase >= REBASE_INTERVAL, \"Rebase interval not exceeded\");\n\n // NOTE: why do we need this to be an actiual person?\n require(msg.sender == tx.origin, \"!eoa\");\n\n IVELO velo_token = IVELO(VELO);\n\n // calculate the Vt, an limit the ranges\n uint256 Vt = this.getRelativeVelocity();\n\n fEMA = calcEMA(fEMA, Vt, Lf);\n sEMA = calcEMA(sEMA, Vt, Ls);\n\n uint256 scaling_modifier = calcFTFixed(fEMA, sEMA, C, K);\n\n scaling_modifier = PRECISION.mul(PRECISION).div(scaling_modifier);\n\n // scale our supply according to formula\n velo_token.rebase(scaling_modifier);\n\n lastRebase = block.timestamp;\n\n // reset the velocity so we can track\n // the velocity for the next epoch\n velocity = 0;\n\n _afterRebase();\n }\n\n function _afterRebase() internal {\n for(uint256 i = 0; i < transactions.length; i ++) {\n Transaction memory transaction = transactions[i]; \n // Failed transactions should be ignored\n transaction.destination.call(transaction.data);\n }\n }\n\n function toFP(int256 _value) public pure returns (int128) {\n return fp.fromInt(_value);\n }\n\n function toInt(int128 _value) public pure returns (int256) {\n return fp.muli(_value, int256(PRECISION));\n }\n\n function op_nv1t_plus_v2t_v(uint256 _v1t, uint256 _v2t) public pure returns (int128) {\n require(_v1t < 2**255 - 1, \"_v1t must be smaller than max int256\");\n require(_v2t < 2**255 - 1, \"_v2t must be smaller than max int256\");\n\n int128 MINUS_ONE = fp.fromInt(-1);\n\n int128 v1t = fp.divu(_v1t, PRECISION);\n int128 v2t = fp.divu(_v2t, PRECISION);\n\n return v1t.mul(MINUS_ONE).add(v2t);\n }\n\n function op_div_k_v(int128 _op_nv1t_plus_v2t_v, uint256 _k) public pure returns(int128) {\n require(_k < 2**255 - 1, \"_k must be smaller than int256\");\n\n int128 k = fp.divu(_k, PRECISION);\n\n return fp.div(_op_nv1t_plus_v2t_v, k);\n }\n\n function op_e_pow_v(int128 _op_div_k_v) public pure returns(int128) {\n return fp.exp(_op_div_k_v);\n }\n\n function op_one_plus_v(int128 _op_e_pow_v) public pure returns(int128) {\n return fp.fromUInt(1).add(_op_e_pow_v);\n }\n\n function op_div_v(int128 _op_one_plus_v) public pure returns(int128) {\n return fp.fromUInt(1).div(_op_one_plus_v);\n }\n\n // let op_n_plus_v = -0.5_f64 + op_div_v;\n function op_n_plus_v(int128 _op_div_v) public pure returns(int128) {\n return fp.divi(1, -2).add(_op_div_v);\n }\n\n\n // let op_c_mul_v = c * op_n_plus_v;\n function op_c_mul_v(uint256 _c, int128 _op_n_plus_v) public pure returns(int128) {\n require(_c < 2**255 - 1, \"_c must be smaller than max int256\");\n int128 c = fp.divu(_c, PRECISION);\n\n return fp.mul(c, _op_n_plus_v);\n }\n\n // let op_rt_v = 1_f64 + op_c_mul_v;\n function op_rt_v(int128 _op_c_mul_v) public pure returns(int128) {\n return fp.fromUInt(1).add(_op_c_mul_v);\n }\n\n\n function calcFTFixed(uint256 _v1t, uint256 _v2t, uint256 _c, uint256 _k) public pure returns (uint256) {\n int128 op_nv1t_plus_v2t_v_ = op_nv1t_plus_v2t_v(_v1t, _v2t);\n int128 op_div_k_v_ = op_div_k_v(op_nv1t_plus_v2t_v_, _k);\n int128 op_e_pow_v_ = op_e_pow_v(op_div_k_v_);\n int128 op_one_plus_v_ = op_one_plus_v(op_e_pow_v_);\n int128 op_div_v_ = op_div_v(op_one_plus_v_);\n int128 op_n_plus_v_ = op_n_plus_v(op_div_v_);\n int128 op_c_mul_v_ = op_c_mul_v(_c, op_n_plus_v_);\n int128 op_rt_v_ = op_rt_v(op_c_mul_v_);\n\n return fp.mulu(op_rt_v_, PRECISION);\n }\n\n}\n" | |
}, | |
"contracts/lib/SafeERC20.sol": { | |
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.5.17;\n\nimport \"./IERC20.sol\";\nimport \"./SafeMath.sol\";\nimport \"./Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using SafeMath for uint256;\n using Address for address;\n\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(IERC20 token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n // solhint-disable-next-line max-line-length\n require((value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).add(value);\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).sub(value, \"SafeERC20: decreased allowance below zero\");\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) { // Return data is optional\n // solhint-disable-next-line max-line-length\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" | |
}, | |
"contracts/lib/ABDKMath64x64.sol": { | |
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <[email protected]>\n */\npragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n return int64 (x >> 64);\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n require (x >= 0);\n return uint64 (x >> 64);\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n return int256 (x) << 64;\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (x) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n require (x != MIN_64x64);\n return -x;\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n uint256 absoluteResult;\n bool negativeResult = false;\n if (x >= 0) {\n absoluteResult = powu (uint256 (x) << 63, y);\n } else {\n // We rely on overflow behavior here\n absoluteResult = powu (uint256 (uint128 (-x)) << 63, y);\n negativeResult = y & 1 > 0;\n }\n\n absoluteResult >>= 63;\n\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n require (x >= 0);\n return int128 (sqrtu (uint256 (x) << 64));\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (x) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n require (x > 0);\n\n return int128 (\n uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (63 - (x >> 64));\n require (result <= uint256 (MAX_64x64));\n\n return int128 (result);\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point\n * number and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x unsigned 129.127-bit fixed point number\n * @param y uint256 value\n * @return unsigned 129.127-bit fixed point number\n */\n function powu (uint256 x, uint256 y) private pure returns (uint256) {\n if (y == 0) return 0x80000000000000000000000000000000;\n else if (x == 0) return 0;\n else {\n int256 msb = 0;\n uint256 xc = x;\n if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; }\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 xe = msb - 127;\n if (xe > 0) x >>= uint256 (xe);\n else x <<= uint256 (-xe);\n\n uint256 result = 0x80000000000000000000000000000000;\n int256 re = 0;\n\n while (y > 0) {\n if (y & 1 > 0) {\n result = result * x;\n y -= 1;\n re += xe;\n if (result >=\n 0x8000000000000000000000000000000000000000000000000000000000000000) {\n result >>= 128;\n re += 1;\n } else result >>= 127;\n if (re < -127) return 0; // Underflow\n require (re < 128); // Overflow\n } else {\n x = x * x;\n y >>= 1;\n xe <<= 1;\n if (x >=\n 0x8000000000000000000000000000000000000000000000000000000000000000) {\n x >>= 128;\n xe += 1;\n } else x >>= 127;\n if (xe < -127) return 0; // Underflow\n require (xe < 128); // Overflow\n }\n }\n\n if (re > 0) result <<= uint256 (re);\n else if (re < 0) result >>= uint256 (-re);\n\n return result;\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x8) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n}" | |
}, | |
"contracts/lib/IERC20.sol": { | |
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.5.17;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n" | |
}, | |
"contracts/lib/Address.sol": { | |
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.5.17;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies in extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call.value(amount)(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return _functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n return _functionCallWithValue(target, data, value, errorMessage);\n }\n\n function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call.value(weiValue)(data);\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" | |
}, | |
"contracts/governance/VELOGovernorAlpha.sol": { | |
"content": "pragma solidity ^0.5.17;\npragma experimental ABIEncoderV2;\n\n// Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol\n// Modified to work in the VELO system\n\n// all votes work on underlying _veloBalances[address], not balanceOf(address)\n\n// Original audit: https://blog.openzeppelin.com/compound-alpha-governance-system-audit/\n// Overview:\n// No Critical\n// High:\n// Issue:\n// Approved proposal may be impossible to queue, cancel or execute\n// Fixed with `proposalMaxOperations`\n// Issue:\n// Queued proposal with repeated actions cannot be executed\n// Fixed by explicitly disallow proposals with repeated actions to be queued in the Timelock contract.\n//\n// Changes made by VELO after audit:\n// Formatting, naming, & uint256 instead of uint\n// Since VELO supply changes, updated quorum & proposal requirements\n// If any uint96, changed to uint256 to match VELO as opposed to comp\n\n\nimport \"../lib/SafeMath.sol\";\n\ncontract GovernorAlpha {\n /// @notice The name of this contract\n string public constant name = \"VELO Governor Alpha\";\n\n /// @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\n function quorumVotes() public view returns (uint256) { return SafeMath.div(SafeMath.mul(velo.initSupply(), 4), 100); } // 4% of VELO\n\n /// @notice The number of votes required in order for a voter to become a proposer\n function proposalThreshold() public view returns (uint256) { return SafeMath.div(velo.initSupply(), 100); } // 1% of VELO\n\n /// @notice The maximum number of actions that can be included in a proposal\n function proposalMaxOperations() public pure returns (uint256) { return 10; } // 10 actions\n\n /// @notice The delay before voting on a proposal may take place, once proposed\n function votingDelay() public pure returns (uint256) { return 1; } // 1 block\n\n /// @notice The duration of voting on a proposal, in blocks\n function votingPeriod() public pure returns (uint256) { return 17280; } // ~3 days in blocks (assuming 15s blocks)\n\n /// @notice The address of the Compound Protocol Timelock\n TimelockInterface public timelock;\n\n /// @notice The address of the Compound governance token\n VELOInterface public velo;\n\n /// @notice The address of the Governor Guardian\n address public guardian;\n\n /// @notice The total number of proposals\n uint256 public proposalCount;\n\n struct Proposal {\n /// @notice Unique id for looking up a proposal\n uint256 id;\n\n /// @notice Creator of the proposal\n address proposer;\n\n /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds\n uint256 eta;\n\n /// @notice the ordered list of target addresses for calls to be made\n address[] targets;\n\n /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made\n uint[] values;\n\n /// @notice The ordered list of function signatures to be called\n string[] signatures;\n\n /// @notice The ordered list of calldata to be passed to each call\n bytes[] calldatas;\n\n /// @notice The block at which voting begins: holders must delegate their votes prior to this block\n uint256 startBlock;\n\n /// @notice The block at which voting ends: votes must be cast prior to this block\n uint256 endBlock;\n\n /// @notice Current number of votes in favor of this proposal\n uint256 forVotes;\n\n /// @notice Current number of votes in opposition to this proposal\n uint256 againstVotes;\n\n /// @notice Flag marking whether the proposal has been canceled\n bool canceled;\n\n /// @notice Flag marking whether the proposal has been executed\n bool executed;\n\n /// @notice Receipts of ballots for the entire set of voters\n mapping (address => Receipt) receipts;\n }\n\n /// @notice Ballot receipt record for a voter\n struct Receipt {\n /// @notice Whether or not a vote has been cast\n bool hasVoted;\n\n /// @notice Whether or not the voter supports the proposal\n bool support;\n\n /// @notice The number of votes the voter had, which were cast\n uint256 votes;\n }\n\n /// @notice Possible states that a proposal may be in\n enum ProposalState {\n Pending,\n Active,\n Canceled,\n Defeated,\n Succeeded,\n Queued,\n Expired,\n Executed\n }\n\n /// @notice The official record of all proposals ever proposed\n mapping (uint256 => Proposal) public proposals;\n\n /// @notice The latest proposal for each proposer\n mapping (address => uint256) public latestProposalIds;\n\n /// @notice The EIP-712 typehash for the contract's domain\n bytes32 public constant DOMAIN_TYPEHASH = keccak256(\"EIP712Domain(string name,uint256 chainId,address verifyingContract)\");\n\n /// @notice The EIP-712 typehash for the ballot struct used by the contract\n bytes32 public constant BALLOT_TYPEHASH = keccak256(\"Ballot(uint256 proposalId,bool support)\");\n\n /// @notice An event emitted when a new proposal is created\n event ProposalCreated(uint256 id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description);\n\n /// @notice An event emitted when a vote has been cast on a proposal\n event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes);\n\n /// @notice An event emitted when a proposal has been canceled\n event ProposalCanceled(uint256 id);\n\n /// @notice An event emitted when a proposal has been queued in the Timelock\n event ProposalQueued(uint256 id, uint256 eta);\n\n /// @notice An event emitted when a proposal has been executed in the Timelock\n event ProposalExecuted(uint256 id);\n\n constructor(address timelock_, address velo_) public {\n timelock = TimelockInterface(timelock_);\n velo = VELOInterface(velo_);\n guardian = msg.sender;\n }\n\n function propose(\n address[] memory targets,\n uint[] memory values,\n string[] memory signatures,\n bytes[] memory calldatas,\n string memory description\n )\n public\n returns (uint256)\n {\n require(velo.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), \"GovernorAlpha::propose: proposer votes below proposal threshold\");\n require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, \"GovernorAlpha::propose: proposal function information arity mismatch\");\n require(targets.length != 0, \"GovernorAlpha::propose: must provide actions\");\n require(targets.length <= proposalMaxOperations(), \"GovernorAlpha::propose: too many actions\");\n\n uint256 latestProposalId = latestProposalIds[msg.sender];\n if (latestProposalId != 0) {\n ProposalState proposersLatestProposalState = state(latestProposalId);\n require(proposersLatestProposalState != ProposalState.Active, \"GovernorAlpha::propose: one live proposal per proposer, found an already active proposal\");\n require(proposersLatestProposalState != ProposalState.Pending, \"GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal\");\n }\n\n uint256 startBlock = add256(block.number, votingDelay());\n uint256 endBlock = add256(startBlock, votingPeriod());\n\n proposalCount++;\n Proposal memory newProposal = Proposal({\n id: proposalCount,\n proposer: msg.sender,\n eta: 0,\n targets: targets,\n values: values,\n signatures: signatures,\n calldatas: calldatas,\n startBlock: startBlock,\n endBlock: endBlock,\n forVotes: 0,\n againstVotes: 0,\n canceled: false,\n executed: false\n });\n\n proposals[newProposal.id] = newProposal;\n latestProposalIds[newProposal.proposer] = newProposal.id;\n\n emit ProposalCreated(\n newProposal.id,\n msg.sender,\n targets,\n values,\n signatures,\n calldatas,\n startBlock,\n endBlock,\n description\n );\n return newProposal.id;\n }\n\n function queue(uint256 proposalId)\n public\n {\n require(state(proposalId) == ProposalState.Succeeded, \"GovernorAlpha::queue: proposal can only be queued if it is succeeded\");\n Proposal storage proposal = proposals[proposalId];\n uint256 eta = add256(block.timestamp, timelock.delay());\n for (uint256 i = 0; i < proposal.targets.length; i++) {\n _queueOrRevert(\n proposal.targets[i],\n proposal.values[i],\n proposal.signatures[i],\n proposal.calldatas[i],\n eta\n );\n }\n proposal.eta = eta;\n emit ProposalQueued(proposalId, eta);\n }\n\n function _queueOrRevert(\n address target,\n uint256 value,\n string memory signature,\n bytes memory data,\n uint256 eta\n )\n internal\n {\n require(!timelock.queuedTransactions(\n keccak256(\n abi.encode(\n target,\n value,\n signature,\n data,\n eta\n )\n )\n ),\n \"GovernorAlpha::_queueOrRevert: proposal action already queued at eta\"\n );\n\n timelock.queueTransaction(target, value, signature, data, eta);\n }\n\n function execute(uint256 proposalId)\n public\n payable\n {\n require(state(proposalId) == ProposalState.Queued, \"GovernorAlpha::execute: proposal can only be executed if it is queued\");\n Proposal storage proposal = proposals[proposalId];\n proposal.executed = true;\n for (uint256 i = 0; i < proposal.targets.length; i++) {\n timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);\n }\n emit ProposalExecuted(proposalId);\n }\n\n function cancel(uint256 proposalId)\n public\n {\n ProposalState state = state(proposalId);\n require(state != ProposalState.Executed, \"GovernorAlpha::cancel: cannot cancel executed proposal\");\n\n Proposal storage proposal = proposals[proposalId];\n require(msg.sender == guardian || velo.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), \"GovernorAlpha::cancel: proposer above threshold\");\n\n proposal.canceled = true;\n for (uint256 i = 0; i < proposal.targets.length; i++) {\n timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);\n }\n\n emit ProposalCanceled(proposalId);\n }\n\n function getActions(uint256 proposalId)\n public\n view\n returns (\n address[] memory targets,\n uint[] memory values,\n string[] memory signatures,\n bytes[] memory calldatas\n )\n {\n Proposal storage p = proposals[proposalId];\n return (p.targets, p.values, p.signatures, p.calldatas);\n }\n\n function getReceipt(uint256 proposalId, address voter)\n public\n view\n returns (Receipt memory)\n {\n return proposals[proposalId].receipts[voter];\n }\n\n function state(uint256 proposalId)\n public\n view\n returns (ProposalState)\n {\n require(proposalCount >= proposalId && proposalId > 0, \"GovernorAlpha::state: invalid proposal id\");\n Proposal storage proposal = proposals[proposalId];\n if (proposal.canceled) {\n return ProposalState.Canceled;\n } else if (block.number <= proposal.startBlock) {\n return ProposalState.Pending;\n } else if (block.number <= proposal.endBlock) {\n return ProposalState.Active;\n } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) {\n return ProposalState.Defeated;\n } else if (proposal.eta == 0) {\n return ProposalState.Succeeded;\n } else if (proposal.executed) {\n return ProposalState.Executed;\n } else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) {\n return ProposalState.Expired;\n } else {\n return ProposalState.Queued;\n }\n }\n\n function castVote(uint256 proposalId, bool support)\n public\n {\n return _castVote(msg.sender, proposalId, support);\n }\n\n function castVoteBySig(\n uint256 proposalId,\n bool support,\n uint8 v,\n bytes32 r,\n bytes32 s\n )\n public\n {\n bytes32 domainSeparator = keccak256(\n abi.encode(\n DOMAIN_TYPEHASH,\n keccak256(bytes(name)),\n getChainId(),\n address(this)\n )\n );\n\n bytes32 structHash = keccak256(\n abi.encode(\n BALLOT_TYPEHASH,\n proposalId,\n support\n )\n );\n\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n domainSeparator,\n structHash\n )\n );\n\n address signatory = ecrecover(digest, v, r, s);\n require(signatory != address(0), \"GovernorAlpha::castVoteBySig: invalid signature\");\n return _castVote(signatory, proposalId, support);\n }\n\n function _castVote(\n address voter,\n uint256 proposalId,\n bool support\n )\n internal\n {\n require(state(proposalId) == ProposalState.Active, \"GovernorAlpha::_castVote: voting is closed\");\n Proposal storage proposal = proposals[proposalId];\n Receipt storage receipt = proposal.receipts[voter];\n require(receipt.hasVoted == false, \"GovernorAlpha::_castVote: voter already voted\");\n uint256 votes = velo.getPriorVotes(voter, proposal.startBlock);\n\n if (support) {\n proposal.forVotes = add256(proposal.forVotes, votes);\n } else {\n proposal.againstVotes = add256(proposal.againstVotes, votes);\n }\n\n receipt.hasVoted = true;\n receipt.support = support;\n receipt.votes = votes;\n\n emit VoteCast(voter, proposalId, support, votes);\n }\n\n function __acceptAdmin()\n public\n {\n require(msg.sender == guardian, \"GovernorAlpha::__acceptAdmin: sender must be gov guardian\");\n timelock.acceptAdmin();\n }\n\n function __abdicate()\n public\n {\n require(msg.sender == guardian, \"GovernorAlpha::__abdicate: sender must be gov guardian\");\n guardian = address(0);\n }\n\n function __queueSetTimelockPendingAdmin(\n address newPendingAdmin,\n uint256 eta\n )\n public\n {\n require(msg.sender == guardian, \"GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian\");\n timelock.queueTransaction(address(timelock), 0, \"setPendingAdmin(address)\", abi.encode(newPendingAdmin), eta);\n }\n\n function __executeSetTimelockPendingAdmin(\n address newPendingAdmin,\n uint256 eta\n )\n public\n {\n require(msg.sender == guardian, \"GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian\");\n timelock.executeTransaction(address(timelock), 0, \"setPendingAdmin(address)\", abi.encode(newPendingAdmin), eta);\n }\n\n function add256(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"addition overflow\");\n return c;\n }\n\n function sub256(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b <= a, \"subtraction underflow\");\n return a - b;\n }\n\n function getChainId() internal pure returns (uint256) {\n uint256 chainId;\n assembly { chainId := chainid() }\n return chainId;\n }\n}\n\ninterface TimelockInterface {\n function delay() external view returns (uint256);\n function GRACE_PERIOD() external view returns (uint256);\n function acceptAdmin() external;\n function queuedTransactions(bytes32 hash) external view returns (bool);\n function queueTransaction(address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta) external returns (bytes32);\n function cancelTransaction(address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta) external;\n function executeTransaction(address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta) external payable returns (bytes memory);\n}\n\ninterface VELOInterface {\n function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256);\n function initSupply() external view returns (uint256);\n function _acceptGov() external;\n}\n" | |
}, | |
"contracts/governance/TimeLock.sol": { | |
"content": "pragma solidity ^0.5.17;\n\n// Original file came from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol\n\n\n// Original audit: https://blog.openzeppelin.com/compound-finance-patch-audit/\n// Overview:\n// No Critical\n// No High\n//\n// Changes made by VELO after audit:\n// Formatting, naming, & uint256 instead of uint\n\nimport \"../lib/SafeMath.sol\";\n\ncontract Timelock {\n using SafeMath for uint256;\n\n /// @notice An event emitted when the timelock admin changes\n event NewAdmin(address indexed newAdmin);\n /// @notice An event emitted when a new admin is staged in the timelock\n event NewPendingAdmin(address indexed newPendingAdmin);\n event NewDelay(uint indexed newDelay);\n /// @notice An event emitted when a queued transaction is cancelled\n event CancelTransaction(bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta);\n /// @notice An event emitted when a queued transaction is executed\n event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta);\n /// @notice An event emitted when a new transaction is queued\n event QueueTransaction(bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta);\n\n /// @notice the length of time after the delay has passed that a transaction can be executed\n uint256 public constant GRACE_PERIOD = 14 days;\n /// @notice the minimum length of the timelock delay\n uint256 public constant MINIMUM_DELAY = 12 hours + 2*60*15; // have to be present for 2 rebases\n /// @notice the maximum length of the timelock delay\n uint256 public constant MAXIMUM_DELAY = 30 days;\n\n address public admin;\n address public pendingAdmin;\n uint256 public delay;\n bool public admin_initialized;\n\n mapping (bytes32 => bool) public queuedTransactions;\n\n\n constructor()\n public\n {\n /* require(delay_ >= MINIMUM_DELAY, \"Timelock::constructor: Delay must exceed minimum delay.\");\n require(delay_ <= MAXIMUM_DELAY, \"Timelock::setDelay: Delay must not exceed maximum delay.\"); */\n\n admin = msg.sender;\n delay = MINIMUM_DELAY;\n admin_initialized = false;\n }\n\n function() external payable { }\n\n\n /**\n @notice sets the delay\n @param delay_ the new delay\n */\n function setDelay(uint256 delay_)\n public\n {\n require(msg.sender == address(this), \"Timelock::setDelay: Call must come from Timelock.\");\n require(delay_ >= MINIMUM_DELAY, \"Timelock::setDelay: Delay must exceed minimum delay.\");\n require(delay_ <= MAXIMUM_DELAY, \"Timelock::setDelay: Delay must not exceed maximum delay.\");\n delay = delay_;\n\n emit NewDelay(delay);\n }\n\n\n /// @notice sets the new admin address\n function acceptAdmin()\n public\n {\n require(msg.sender == pendingAdmin, \"Timelock::acceptAdmin: Call must come from pendingAdmin.\");\n admin = msg.sender;\n pendingAdmin = address(0);\n\n emit NewAdmin(admin);\n }\n\n /**\n @notice queues a new pendingAdmin\n @param pendingAdmin_ the new pendingAdmin address\n */\n function setPendingAdmin(address pendingAdmin_)\n public\n {\n // allows one time setting of admin for deployment purposes\n if (admin_initialized) {\n require(msg.sender == address(this), \"Timelock::setPendingAdmin: Call must come from Timelock.\");\n } else {\n admin_initialized = true;\n }\n pendingAdmin = pendingAdmin_;\n\n emit NewPendingAdmin(pendingAdmin);\n }\n\n\n function queueTransaction(\n address target,\n uint256 value,\n string memory signature,\n bytes memory data,\n uint256 eta\n )\n public\n returns (bytes32)\n {\n require(msg.sender == admin, \"Timelock::queueTransaction: Call must come from admin.\");\n require(eta >= getBlockTimestamp().add(delay), \"Timelock::queueTransaction: Estimated execution block must satisfy delay.\");\n\n bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n queuedTransactions[txHash] = true;\n\n emit QueueTransaction(txHash, target, value, signature, data, eta);\n return txHash;\n }\n\n function cancelTransaction(\n address target,\n uint256 value,\n string memory signature,\n bytes memory data,\n uint256 eta\n )\n public\n {\n require(msg.sender == admin, \"Timelock::cancelTransaction: Call must come from admin.\");\n\n bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n queuedTransactions[txHash] = false;\n\n emit CancelTransaction(txHash, target, value, signature, data, eta);\n }\n\n function executeTransaction(\n address target,\n uint256 value,\n string memory signature,\n bytes memory data,\n uint256 eta\n )\n public\n payable\n returns (bytes memory)\n {\n require(msg.sender == admin, \"Timelock::executeTransaction: Call must come from admin.\");\n\n // timelock not enforced prior to updating the admin. This should occur on\n // deployment.\n bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n if (admin_initialized) {\n require(queuedTransactions[txHash], \"Timelock::executeTransaction: Transaction hasn't been queued.\");\n require(getBlockTimestamp() >= eta, \"Timelock::executeTransaction: Transaction hasn't surpassed time lock.\");\n require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), \"Timelock::executeTransaction: Transaction is stale.\");\n\n queuedTransactions[txHash] = false;\n }\n\n\n bytes memory callData;\n\n if (bytes(signature).length == 0) {\n callData = data;\n } else {\n callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);\n }\n\n // solium-disable-next-line security/no-call-value\n (bool success, bytes memory returnData) = target.call.value(value)(callData);\n require(success, \"Timelock::executeTransaction: Transaction execution reverted.\");\n\n emit ExecuteTransaction(txHash, target, value, signature, data, eta);\n\n return returnData;\n }\n\n function getBlockTimestamp() internal view returns (uint256) {\n // solium-disable-next-line security/no-block-members\n return block.timestamp;\n }\n}\n" | |
}, | |
"contracts/lib/Babylonian.sol": { | |
"content": "// SPDX-License-Identifier: GPL-3.0-or-later\n\npragma solidity >=0.4.0;\n\n// computes square roots using the babylonian method\n// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method\nlibrary Babylonian {\n function sqrt(uint y) internal pure returns (uint z) {\n if (y > 3) {\n z = y;\n uint x = y / 2 + 1;\n while (x < z) {\n z = x;\n x = (y / x + x) / 2;\n }\n } else if (y != 0) {\n z = 1;\n }\n // else z = 0\n }\n}\n" | |
}, | |
"contracts/lib/FixedPoint.sol": { | |
"content": "// SPDX-License-Identifier: GPL-3.0-or-later\n\npragma solidity >=0.4.0;\n\nimport './Babylonian.sol';\n\n// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))\nlibrary FixedPoint {\n // range: [0, 2**112 - 1]\n // resolution: 1 / 2**112\n struct uq112x112 {\n uint224 _x;\n }\n\n // range: [0, 2**144 - 1]\n // resolution: 1 / 2**112\n struct uq144x112 {\n uint _x;\n }\n\n uint8 private constant RESOLUTION = 112;\n uint private constant Q112 = uint(1) << RESOLUTION;\n uint private constant Q224 = Q112 << RESOLUTION;\n\n // encode a uint112 as a UQ112x112\n function encode(uint112 x) internal pure returns (uq112x112 memory) {\n return uq112x112(uint224(x) << RESOLUTION);\n }\n\n // encodes a uint144 as a UQ144x112\n function encode144(uint144 x) internal pure returns (uq144x112 memory) {\n return uq144x112(uint256(x) << RESOLUTION);\n }\n\n // divide a UQ112x112 by a uint112, returning a UQ112x112\n function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {\n require(x != 0, 'FixedPoint: DIV_BY_ZERO');\n return uq112x112(self._x / uint224(x));\n }\n\n // multiply a UQ112x112 by a uint, returning a UQ144x112\n // reverts on overflow\n function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {\n uint z;\n require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), \"FixedPoint: MULTIPLICATION_OVERFLOW\");\n return uq144x112(z);\n }\n\n // returns a UQ112x112 which represents the ratio of the numerator to the denominator\n // equivalent to encode(numerator).div(denominator)\n function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {\n require(denominator > 0, \"FixedPoint: DIV_BY_ZERO\");\n return uq112x112((uint224(numerator) << RESOLUTION) / denominator);\n }\n\n // decode a UQ112x112 into a uint112 by truncating after the radix point\n function decode(uq112x112 memory self) internal pure returns (uint112) {\n return uint112(self._x >> RESOLUTION);\n }\n\n // decode a UQ144x112 into a uint144 by truncating after the radix point\n function decode144(uq144x112 memory self) internal pure returns (uint144) {\n return uint144(self._x >> RESOLUTION);\n }\n\n // take the reciprocal of a UQ112x112\n function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {\n require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL');\n return uq112x112(uint224(Q224 / self._x));\n }\n\n // square root of a UQ112x112\n function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {\n return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56));\n }\n}\n" | |
}, | |
"contracts/lib/UniswapV2OracleLibrary.sol": { | |
"content": "pragma solidity >=0.5.0;\n\nimport './IUniswapV2Pair.sol';\nimport './FixedPoint.sol';\n\n// library with helper methods for oracles that are concerned with computing average prices\nlibrary UniswapV2OracleLibrary {\n using FixedPoint for *;\n\n // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]\n function currentBlockTimestamp() internal view returns (uint32) {\n return uint32(block.timestamp % 2 ** 32);\n }\n\n // produces the cumulative price using counterfactuals to save gas and avoid a call to sync.\n function currentCumulativePrices(\n address pair,\n bool isToken0\n ) internal view returns (uint priceCumulative, uint32 blockTimestamp) {\n blockTimestamp = currentBlockTimestamp();\n (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = UniswapPair(pair).getReserves();\n if (isToken0) {\n priceCumulative = UniswapPair(pair).price0CumulativeLast();\n\n // if time has elapsed since the last update on the pair, mock the accumulated price values\n if (blockTimestampLast != blockTimestamp) {\n // subtraction overflow is desired\n uint32 timeElapsed = blockTimestamp - blockTimestampLast;\n // addition overflow is desired\n // counterfactual\n priceCumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;\n }\n } else {\n priceCumulative = UniswapPair(pair).price1CumulativeLast();\n // if time has elapsed since the last update on the pair, mock the accumulated price values\n if (blockTimestampLast != blockTimestamp) {\n // subtraction overflow is desired\n uint32 timeElapsed = blockTimestamp - blockTimestampLast;\n // addition overflow is desired\n // counterfactual\n priceCumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;\n }\n }\n\n }\n}\n" | |
}, | |
"contracts/lib/IUniswapV2Pair.sol": { | |
"content": "pragma solidity >=0.5.0;\n\ninterface UniswapPair {\n event Approval(address indexed owner, address indexed spender, uint value);\n event Transfer(address indexed from, address indexed to, uint value);\n\n function name() external pure returns (string memory);\n function symbol() external pure returns (string memory);\n function decimals() external pure returns (uint8);\n function totalSupply() external view returns (uint);\n function balanceOf(address owner) external view returns (uint);\n function allowance(address owner, address spender) external view returns (uint);\n\n function approve(address spender, uint value) external returns (bool);\n function transfer(address to, uint value) external returns (bool);\n function transferFrom(address from, address to, uint value) external returns (bool);\n\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n function PERMIT_TYPEHASH() external pure returns (bytes32);\n function nonces(address owner) external view returns (uint);\n\n function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;\n\n event Mint(address indexed sender, uint amount0, uint amount1);\n event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);\n event Swap(\n address indexed sender,\n uint amount0In,\n uint amount1In,\n uint amount0Out,\n uint amount1Out,\n address indexed to\n );\n event Sync(uint112 reserve0, uint112 reserve1);\n\n function MINIMUM_LIQUIDITY() external pure returns (uint);\n function factory() external view returns (address);\n function token0() external view returns (address);\n function token1() external view returns (address);\n function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);\n function price0CumulativeLast() external view returns (uint);\n function price1CumulativeLast() external view returns (uint);\n function kLast() external view returns (uint);\n\n function mint(address to) external returns (uint liquidity);\n function burn(address to) external returns (uint amount0, uint amount1);\n function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;\n function skim(address to) external;\n function sync() external;\n\n function initialize(address, address) external;\n}\n" | |
}, | |
"contracts/mock/Token.sol": { | |
"content": "pragma solidity 0.5.17;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\n\ncontract Token is ERC20 {\n string public name = \"Test\";\n string public symbol = \"TST\";\n uint256 public decimals = 18;\n\n constructor(\n string memory _name,\n string memory _symbol,\n uint256 _decimals\n ) public {\n name = _name;\n symbol = _symbol;\n decimals = _decimals;\n _mint(msg.sender, 10**(50 + 18));\n }\n}\n" | |
}, | |
"@openzeppelin/contracts/token/ERC20/ERC20.sol": { | |
"content": "pragma solidity ^0.5.0;\n\nimport \"../../GSN/Context.sol\";\nimport \"./IERC20.sol\";\nimport \"../../math/SafeMath.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20Mintable}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20 {\n using SafeMath for uint256;\n\n mapping (address => uint256) private _balances;\n\n mapping (address => mapping (address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `recipient` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address recipient, uint256 amount) public returns (bool) {\n _transfer(_msgSender(), recipient, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public returns (bool) {\n _approve(_msgSender(), spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20};\n *\n * Requirements:\n * - `sender` and `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n * - the caller must have allowance for `sender`'s tokens of at least\n * `amount`.\n */\n function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {\n _transfer(sender, recipient, amount);\n _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n return true;\n }\n\n /**\n * @dev Moves tokens `amount` from `sender` to `recipient`.\n *\n * This is internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `sender` cannot be the zero address.\n * - `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n */\n function _transfer(address sender, address recipient, uint256 amount) internal {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n _balances[recipient] = _balances[recipient].add(amount);\n emit Transfer(sender, recipient, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements\n *\n * - `to` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _totalSupply = _totalSupply.add(amount);\n _balances[account] = _balances[account].add(amount);\n emit Transfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n _totalSupply = _totalSupply.sub(amount);\n emit Transfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.\n *\n * This is internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(address owner, address spender, uint256 amount) internal {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`.`amount` is then deducted\n * from the caller's allowance.\n *\n * See {_burn} and {_approve}.\n */\n function _burnFrom(address account, uint256 amount) internal {\n _burn(account, amount);\n _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, \"ERC20: burn amount exceeds allowance\"));\n }\n}\n" | |
}, | |
"@openzeppelin/contracts/GSN/Context.sol": { | |
"content": "pragma solidity ^0.5.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\ncontract Context {\n // Empty internal constructor, to prevent people from mistakenly deploying\n // an instance of this contract, which should be used via inheritance.\n constructor () internal { }\n // solhint-disable-previous-line no-empty-blocks\n\n function _msgSender() internal view returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n}\n" | |
}, | |
"@openzeppelin/contracts/token/ERC20/IERC20.sol": { | |
"content": "pragma solidity ^0.5.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP. Does not include\n * the optional functions; to access them see {ERC20Detailed}.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n" | |
}, | |
"@openzeppelin/contracts/math/SafeMath.sol": { | |
"content": "pragma solidity ^0.5.0;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n * - Subtraction cannot overflow.\n *\n * _Available since v2.4.0._\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n uint256 c = a - b;\n\n return c;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n *\n * _Available since v2.4.0._\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n // Solidity only automatically asserts when dividing by 0\n require(b > 0, errorMessage);\n uint256 c = a / b;\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n return c;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return mod(a, b, \"SafeMath: modulo by zero\");\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts with custom message when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n *\n * _Available since v2.4.0._\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b != 0, errorMessage);\n return a % b;\n }\n}\n" | |
}, | |
"contracts/mock/WETH9.sol": { | |
"content": "// Copyright (C) 2015, 2016, 2017 Dapphub\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity 0.5.17;\n\ncontract WETH9 {\n string public name = \"Wrapped Ether\";\n string public symbol = \"WETH\";\n uint8 public decimals = 18;\n\n event Approval(address indexed src, address indexed guy, uint wad);\n event Transfer(address indexed src, address indexed dst, uint wad);\n event Deposit(address indexed dst, uint wad);\n event Withdrawal(address indexed src, uint wad);\n\n mapping (address => uint) public balanceOf;\n mapping (address => mapping (address => uint)) public allowance;\n\n function() external payable {\n deposit();\n }\n function deposit() public payable {\n balanceOf[msg.sender] += msg.value;\n emit Deposit(msg.sender, msg.value);\n }\n function withdraw(uint wad) public {\n require(balanceOf[msg.sender] >= wad);\n balanceOf[msg.sender] -= wad;\n msg.sender.transfer(wad);\n emit Withdrawal(msg.sender, wad);\n }\n\n function totalSupply() public view returns (uint) {\n return address(this).balance;\n }\n\n function approve(address guy, uint wad) public returns (bool) {\n allowance[msg.sender][guy] = wad;\n emit Approval(msg.sender, guy, wad);\n return true;\n }\n\n function transfer(address dst, uint wad) public returns (bool) {\n return transferFrom(msg.sender, dst, wad);\n }\n\n function transferFrom(address src, address dst, uint wad)\n public\n returns (bool)\n {\n require(balanceOf[src] >= wad);\n\n if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {\n require(allowance[src][msg.sender] >= wad);\n allowance[src][msg.sender] -= wad;\n }\n\n balanceOf[src] -= wad;\n balanceOf[dst] += wad;\n\n emit Transfer(src, dst, wad);\n\n return true;\n }\n}\n\n" | |
} | |
}, | |
"settings": { | |
"optimizer": { | |
"enabled": false, | |
"runs": 200 | |
}, | |
"outputSelection": { | |
"*": { | |
"*": [ | |
"abi", | |
"evm.bytecode", | |
"evm.deployedBytecode", | |
"evm.methodIdentifiers" | |
], | |
"": [ | |
"ast" | |
] | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment