file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/* Copyright (c) 2019 WhaleChat Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.4.25; /// @title TokencraticMultiSigWallet contract /// @dev This contract is inspired by the Ethereum Multisignature Wallet contract /// (https://github.com/gnosis/MultiSigWallet). The code has been changed to allow the holders /// of an ERC20-compliant token to vote on the execution of submitted transaction, proportionally /// to the ratio of token's total supply they hold. This contract is intended to be the core of /// a DAO, allowing the token holders to control other contracts. In the context of WhaleChat, /// this contract is the `owner` address of the Cashier contract. import "./WcToken.sol"; contract TokencraticMultiSigWallet { using SafeMath for uint256; event Confirmation(address sender, uint256 transactionId); event Revocation(address indexed sender, uint256 indexed transactionId); event Submission(uint256 indexed transactionId); event Execution(uint256 indexed transactionId); event ExecutionFailure(uint256 indexed transactionId); event Deposit(address indexed sender, uint256 value); event ThresholdChange(uint256 indexed newThreshold); event TokenChange(); mapping (uint256 => Transaction) public transactions; mapping (uint256 => mapping (address => bool)) public confirmations; uint256 public required; uint256 public transactionCount; WcToken public token; uint256 public threshold; struct Transaction { address destination; uint256 value; bytes data; bool executed; } modifier onlyMyself() { require(msg.sender == address(this), "Only the contract itself can call this function"); _; } modifier transactionExists(uint256 _transactionId) { require(transactions[_transactionId].destination != 0, "Unknown transaction"); _; } modifier confirmed(uint256 _transactionId, address _owner) { require(confirmations[_transactionId][_owner], "Transaction is not confirmed"); _; } modifier notConfirmed(uint256 _transactionId, address _owner) { require(!confirmations[_transactionId][_owner], "Transaction was already confirmed"); _; } modifier notExecuted(uint256 _transactionId) { require(!transactions[_transactionId].executed, "Transaction was already executed"); _; } modifier notNull(address _address) { require(_address != 0, "Invalid address"); _; } /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } /// @dev Contract constructor sets the token contract and required confirmation threshold. constructor(WcToken _token, uint256 _threshold) public { token = _token; threshold = _threshold; } /// @dev Change the token contract address. It cannot be a null address (0x0), the current token /// address or the address of this very contract itself /// @param _newToken The address of the new token contract function setToken(WcToken _newToken) external onlyMyself { token = _newToken; emit TokenChange(); } /// @dev Change the confirmation threshold. Valid ranges are >= 0 and <= 100. Only the token holders /// themselves can change the threshold. /// @param _threshold The ratio of tokens needed to confirm a submitted transaction. function setThreshold(uint256 _threshold) external onlyMyself { threshold = _threshold; emit ThresholdChange(threshold); } /// @dev Allows token holders to submit a transaction. /// @param _destination Transaction target address. If must be non-null. /// @param _value Transaction ether value. /// @param _data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address _destination, uint256 _value, bytes _data) external notNull(_destination) returns (uint256 transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: _destination, value: _value, data: _data, executed: false }); transactionCount += 1; emit Submission(transactionId); return transactionId; } /// @dev Allows token holders to confirm a transaction. The transaction must have been submitted and /// not yet confirmed by the sender. /// @param _transactionId Transaction ID. function confirmTransaction(uint256 _transactionId) external transactionExists(_transactionId) notConfirmed(_transactionId, msg.sender) { confirmations[_transactionId][msg.sender] = true; emit Confirmation(msg.sender, _transactionId); } /// @dev Allows a token holder to revoke a confirmation for a transaction. The transaction must have /// been submitted, confirmed by the user and not yet executed. /// @param _transactionId Transaction ID. function revokeConfirmation(uint256 _transactionId) external confirmed(_transactionId, msg.sender) notExecuted(_transactionId) { confirmations[_transactionId][msg.sender] = false; emit Revocation(msg.sender, _transactionId); } /// @dev Allows anyone to execute a confirmed transaction. The transactions must not yet have been /// executed. /// @param _transactionId Transaction ID. function executeTransaction(uint256 _transactionId) public notExecuted(_transactionId) { require(isConfirmed(_transactionId), "Transaction is not confirmed"); Transaction storage txn = transactions[_transactionId]; txn.executed = true; if (txn.destination.call.value(txn.value)(txn.data)) emit Execution(_transactionId); else { emit ExecutionFailure(_transactionId); txn.executed = false; } } /// @dev Returns the confirmation status of a transaction. /// @param _transactionId Transaction ID. /// @return The transaction's confirmation status. function isConfirmed(uint256 _transactionId) public view returns (bool) { uint256 ratioConfirmed = 0; uint256 tokenTotalSupply = token.totalSupply(); address[] memory tokenHolders = token.holders(); for (uint256 i = 0; i < tokenHolders.length; i++) { address tokenHolder = tokenHolders[i]; if (confirmations[_transactionId][tokenHolder]) { ratioConfirmed = ratioConfirmed.add( token.balanceOf(tokenHolder).mul(100).div(tokenTotalSupply) ); } if (ratioConfirmed >= threshold) { return true; } } return false; } /// @dev Returns the total number of transactions after filters are applied. /// @param _pending Include pending transactions. /// @param _executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool _pending, bool _executed) public view returns (uint256 count) { for (uint256 i = 0; i < transactionCount; i++) if ( _pending && !transactions[i].executed || _executed && transactions[i].executed) { count += 1; } } /// @dev Returns list of transaction IDs in defined range. /// @param _from Index start position of transaction array. /// @param _to Index end position of transaction array. /// @param _pending Include pending transactions. /// @param _executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint256 _from, uint256 _to, bool _pending, bool _executed) public view returns (uint256[] transactionIds) { uint256[] memory transactionIdsTemp = new uint256[](transactionCount); uint256 count = 0; uint256 i; for (i = 0; i < transactionCount; i++) if ( _pending && !transactions[i].executed || _executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } transactionIds = new uint256[](_to - _from); for (i = _from; i < _to; i++) transactionIds[i - _from] = transactionIdsTemp[i]; } }
Returns the total number of transactions after filters are applied. _pending Include pending transactions. _executed Include executed transactions. return Total number of transactions after filters are applied.
function getTransactionCount(bool _pending, bool _executed) public view returns (uint256 count) { for (uint256 i = 0; i < transactionCount; i++) if ( _pending && !transactions[i].executed || _executed && transactions[i].executed) { count += 1; } }
1,037,109
pragma solidity 0.8.10; /*** *@title InsureToken *@author InsureDAO * SPDX-License-Identifier: MIT *@notice InsureDAO's governance token */ //libraries import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/pool/IOwnership.sol"; contract InsureToken is IERC20 { event UpdateMiningParameters( uint256 time, uint256 rate, uint256 supply, int256 miningepoch ); event SetMinter(address minter); event SetAdmin(address admin); event SetRate(uint256 rate); string public name; string public symbol; uint256 public constant decimals = 18; mapping(address => uint256) public override balanceOf; mapping(address => mapping(address => uint256)) allowances; uint256 public total_supply; address public minter; IOwnership public immutable ownership; //General constants uint256 constant YEAR = 86400 * 365; // Allocation within 5years: // ========== // * Team & Development: 24% // * Liquidity Mining: 40% // * Investors: 10% // * Foundation Treasury: 14% // * Community Treasury: 10% // ========== // // After 5years: // ========== // * Liquidity Mining: 40%~ (Mint fixed amount every year) // // Mint 2_800_000 INSURE every year. // 6th year: 1.32% inflation rate // 7th year: 1.30% inflation rate // 8th year: 1.28% infration rate // so on // ========== // Supply parameters uint256 constant INITIAL_SUPPLY = 126_000_000; //will be vested uint256 constant RATE_REDUCTION_TIME = YEAR; uint256[6] public RATES = [ (28_000_000 * 10**18) / YEAR, //epoch 0 (22_400_000 * 10**18) / YEAR, //epoch 1 (16_800_000 * 10**18) / YEAR, //epoch 2 (11_200_000 * 10**18) / YEAR, //epoch 3 (5_600_000 * 10**18) / YEAR, //epoch 4 (2_800_000 * 10**18) / YEAR //epoch 5~ ]; uint256 constant RATE_DENOMINATOR = 10**18; uint256 constant INFLATION_DELAY = 86400; // Supply variables int256 public mining_epoch; uint256 public start_epoch_time; uint256 public rate; uint256 public start_epoch_supply; uint256 public emergency_minted; modifier onlyOwner() { require( ownership.owner() == msg.sender, "Caller is not allowed to operate" ); _; } /*** * @notice Contract constructor * @param _name Token full name * @param _symbol Token symbol */ constructor( string memory _name, string memory _symbol, address _ownership ) { uint256 _init_supply = INITIAL_SUPPLY * RATE_DENOMINATOR; name = _name; symbol = _symbol; balanceOf[msg.sender] = _init_supply; total_supply = _init_supply; ownership = IOwnership(_ownership); emit Transfer(address(0), msg.sender, _init_supply); unchecked { start_epoch_time = block.timestamp + INFLATION_DELAY - RATE_REDUCTION_TIME; mining_epoch = -1; } rate = 0; start_epoch_supply = _init_supply; } /*** *@dev Update mining rate and supply at the start of the epoch * Any modifying mining call must also call this */ function _update_mining_parameters() internal { uint256 _rate = rate; uint256 _start_epoch_supply = start_epoch_supply; start_epoch_time += RATE_REDUCTION_TIME; unchecked { mining_epoch += 1; } if (mining_epoch == 0) { _rate = RATES[uint256(mining_epoch)]; } else if (mining_epoch < int256(6)) { _start_epoch_supply += RATES[uint256(mining_epoch) - 1] * YEAR; start_epoch_supply = _start_epoch_supply; _rate = RATES[uint256(mining_epoch)]; } else { _start_epoch_supply += RATES[5] * YEAR; start_epoch_supply = _start_epoch_supply; _rate = RATES[5]; } rate = _rate; emit UpdateMiningParameters( block.timestamp, _rate, _start_epoch_supply, mining_epoch ); } /*** * @notice Update mining rate and supply at the start of the epoch * @dev Callable by any address, but only once per epoch * Total supply becomes slightly larger if this function is called late */ function update_mining_parameters() external { require( block.timestamp >= start_epoch_time + RATE_REDUCTION_TIME, "dev: too soon!" ); _update_mining_parameters(); } /*** *@notice Get timestamp of the current mining epoch start * while simultaneously updating mining parameters *@return Timestamp of the epoch */ function start_epoch_time_write() external returns (uint256) { uint256 _start_epoch_time = start_epoch_time; if (block.timestamp >= _start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); return start_epoch_time; } else { return _start_epoch_time; } } /*** *@notice Get timestamp of the next mining epoch start * while simultaneously updating mining parameters *@return Timestamp of the next epoch */ function future_epoch_time_write() external returns (uint256) { uint256 _start_epoch_time = start_epoch_time; if (block.timestamp >= _start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); return start_epoch_time + RATE_REDUCTION_TIME; } else { return _start_epoch_time + RATE_REDUCTION_TIME; } } function _available_supply() internal view returns (uint256) { return start_epoch_supply + ((block.timestamp - start_epoch_time) * rate) + emergency_minted; } /*** *@notice Current number of tokens in existence (claimed or unclaimed) */ function available_supply() external view returns (uint256) { return _available_supply(); } /*** *@notice How much supply is mintable from start timestamp till end timestamp *@param start Start of the time interval (timestamp) *@param end End of the time interval (timestamp) *@return Tokens mintable from `start` till `end` */ function mintable_in_timeframe(uint256 start, uint256 end) external view returns (uint256) { require(start <= end, "dev: start > end"); uint256 _to_mint = 0; uint256 _current_epoch_time = start_epoch_time; uint256 _current_rate = rate; int256 _current_epoch = mining_epoch; // Special case if end is in future (not yet minted) epoch if (end > _current_epoch_time + RATE_REDUCTION_TIME) { _current_epoch_time += RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_epoch += 1; _current_rate = RATES[uint256(_current_epoch)]; } else { _current_epoch += 1; _current_rate = RATES[5]; } } require( end <= _current_epoch_time + RATE_REDUCTION_TIME, "dev: too far in future" ); for (uint256 i; i < 999; ) { // InsureDAO will not work in 1000 years. if (end >= _current_epoch_time) { uint256 current_end = end; if (current_end > _current_epoch_time + RATE_REDUCTION_TIME) { current_end = _current_epoch_time + RATE_REDUCTION_TIME; } uint256 current_start = start; if ( current_start >= _current_epoch_time + RATE_REDUCTION_TIME ) { break; // We should never get here but what if... } else if (current_start < _current_epoch_time) { current_start = _current_epoch_time; } _to_mint += (_current_rate * (current_end - current_start)); if (start >= _current_epoch_time) { break; } } _current_epoch_time -= RATE_REDUCTION_TIME; if (_current_epoch == 0) { _current_rate = 0; } else { _current_rate = _current_epoch < 5 ? RATES[uint256(_current_epoch) - 1] : RATES[5]; } _current_epoch -= 1; assert(_current_rate <= RATES[0]); // This should never happen unchecked { ++i; } } return _to_mint; } /*** *@notice Total number of tokens in existence. */ function totalSupply() external view override returns (uint256) { return total_supply; } /*** *@notice Check the amount of tokens that an owner allowed to a spender *@param _owner The address which owns the funds *@param _spender The address which will spend the funds *@return uint256 specifying the amount of tokens still available for the spender */ function allowance(address _owner, address _spender) external view override returns (uint256) { return allowances[_owner][_spender]; } /*** *@notice Transfer `_value` tokens from `msg.sender` to `_to` *@dev Vyper does not allow underflows, so the subtraction in * this function will revert on an insufficient balance *@param _to The address to transfer to *@param _value The amount to be transferred *@return bool success */ function transfer(address _to, uint256 _value) external override returns (bool) { require(_to != address(0), "transfers to 0x0 are not allowed"); uint256 _fromBalance = balanceOf[msg.sender]; require(_fromBalance >= _value, "transfer amount exceeds balance"); unchecked { balanceOf[msg.sender] = _fromBalance - _value; } balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } /*** * @notice Transfer `_value` tokens from `_from` to `_to` * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred * @return bool success */ function transferFrom( address _from, address _to, uint256 _value ) external override returns (bool) { require(_from != address(0), "transfer from the zero address"); require(_to != address(0), "transfer to the zero address"); uint256 currentAllowance = allowances[_from][msg.sender]; require(currentAllowance >= _value, "transfer amount exceeds allow"); unchecked { allowances[_from][msg.sender] -= _value; } uint256 _fromBalance = balanceOf[_from]; require(_fromBalance >= _value, "transfer amount exceeds balance"); unchecked { balanceOf[_from] -= _value; } balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), "approve from the zero address"); require(spender != address(0), "approve to the zero address"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** *@notice Approve `_spender` to transfer `_value` tokens on behalf of `msg.sender` *@param _spender The address which will spend the funds *@param _value The amount of tokens to be spent *@return bool success */ function approve(address _spender, uint256 _value) external override returns (bool) { _approve(msg.sender, _spender, _value); return true; } function increaseAllowance(address _spender, uint256 addedValue) external returns (bool) { _approve( msg.sender, _spender, allowances[msg.sender][_spender] + addedValue ); return true; } function decreaseAllowance(address _spender, uint256 subtractedValue) external returns (bool) { uint256 currentAllowance = allowances[msg.sender][_spender]; require( currentAllowance >= subtractedValue, "decreased allowance below zero" ); unchecked { _approve(msg.sender, _spender, currentAllowance - subtractedValue); } return true; } /*** *@notice Mint `_value` tokens and assign them to `_to` *@dev Emits a Transfer event originating from 0x00 *@param _to The account that will receive the created tokens *@param _value The amount that will be created *@return bool success */ function mint(address _to, uint256 _value) external returns (bool) { require(msg.sender == minter, "dev: minter only"); require(_to != address(0), "dev: zero address"); _mint(_to, _value); return true; } function _mint(address _to, uint256 _value) internal { uint256 _total_supply = total_supply + _value; require( _total_supply <= _available_supply(), "exceeds allowable mint amount" ); if (block.timestamp >= start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); } total_supply = _total_supply; balanceOf[_to] += _value; emit Transfer(address(0), _to, _value); } /** *@notice Burn `_value` tokens belonging to `msg.sender` *@dev Emits a Transfer event with a destination of 0x00 *@param _value The amount that will be burned *@return bool success */ function burn(uint256 _value) external returns (bool) { require( balanceOf[msg.sender] >= _value, "_value > balanceOf[msg.sender]" ); unchecked { balanceOf[msg.sender] -= _value; } total_supply -= _value; emit Transfer(msg.sender, address(0), _value); return true; } /*** *@notice Change the token name and symbol to `_name` and `_symbol` *@dev Only callable by the admin account *@param _name New token name *@param _symbol New token symbol */ function set_name(string memory _name, string memory _symbol) external onlyOwner { name = _name; symbol = _symbol; } /*** *@notice Set the minter address *@dev Only callable once, when minter has not yet been set *@param _minter Address of the minter */ function set_minter(address _minter) external onlyOwner { require(minter == address(0), "can set the minter at creation"); minter = _minter; emit SetMinter(_minter); } /*** *@notice Set the new rate for the infration after 5 years. *@dev input must be the number of INSURE to be minted per second. *@param _rate mint amount per second */ function set_rate(uint256 _rate) external onlyOwner { require(_rate < RATES[5], "Decrease Only"); RATES[5] = _rate; emit SetRate(_rate); } /*** * @notice Emergency minting only when CDS couldn't afford the insolvency. * @dev * @param _amountOut token amount needed. token is defiend whithin converter. * @param _to CDS address */ function emergency_mint(uint256 _amount, address _to) external returns (bool) { require(msg.sender == minter, "dev: minter only"); //mint emergency_minted += _amount; _mint(_to, _amount); return true; } }
Check the amount of tokens that an owner allowed to a spender _owner The address which owns the funds _spender The address which will spend the fundsreturn uint256 specifying the amount of tokens still available for the spender/
function allowance(address _owner, address _spender) external view override returns (uint256) { return allowances[_owner][_spender]; }
14,114,018
./full_match/1284/0xb89279DEd0AD7cD573D164b03424E1E2BbE1e2Be/sources/contracts/tgev5.sol
Active Apes get rewarded with free unlock Deployer Required _playerWallet: real EOW of user _amount: amount of free Shakes to give/
function addShakes(address[] memory _playerWallet, uint16[] memory _amount) public payable onlyOwner { for (uint256 i = 0; i < _playerWallet.length; i++) { players[_playerWallet[i]].shakesAvailable += _amount[i]; } }
16,368,410
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPosition Contract /// @author Enzyme Council <[email protected]> interface IExternalPosition { function getDebtAssets() external returns (address[] memory, uint256[] memory); function getManagedAssets() external returns (address[] memory, uint256[] memory); function init(bytes memory) external; function receiveCallFromVault(bytes memory) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { function getOwner() external view returns (address); function hasReconfigurationRequest(address) external view returns (bool); function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool); function isAllowedVaultCall( address, bytes4, bytes32 ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPositionParser Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all external position parsers interface IExternalPositionParser { function parseAssetsForAction( address _externalPosition, uint256 _actionId, bytes memory _encodedActionArgs ) external returns ( address[] memory assetsToTransfer_, uint256[] memory amountsToTransfer_, address[] memory assetsToReceive_ ); function parseInitArgs(address _vaultProxy, bytes memory _initializationData) external returns (bytes memory initArgs_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AaveDebtPositionDataDecoder Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract contract containing data decodings for AaveDebtPosition payloads abstract contract AaveDebtPositionDataDecoder { /// @dev Helper to decode args used during the AddCollateral action function __decodeAddCollateralActionArgs(bytes memory _actionArgs) internal pure returns (address[] memory aTokens_, uint256[] memory amounts_) { return abi.decode(_actionArgs, (address[], uint256[])); } /// @dev Helper to decode args used during the Borrow action function __decodeBorrowActionArgs(bytes memory _actionArgs) internal pure returns (address[] memory tokens_, uint256[] memory amounts_) { return abi.decode(_actionArgs, (address[], uint256[])); } /// @dev Helper to decode args used during the ClaimRewards action function __decodeClaimRewardsActionArgs(bytes memory _actionArgs) internal pure returns (address[] memory assets_) { return abi.decode(_actionArgs, (address[])); } /// @dev Helper to decode args used during the RemoveCollateral action function __decodeRemoveCollateralActionArgs(bytes memory _actionArgs) internal pure returns (address[] memory aTokens_, uint256[] memory amounts_) { return abi.decode(_actionArgs, (address[], uint256[])); } /// @dev Helper to decode args used during the RepayBorrow action function __decodeRepayBorrowActionArgs(bytes memory _actionArgs) internal pure returns (address[] memory tokens_, uint256[] memory amounts_) { return abi.decode(_actionArgs, (address[], uint256[])); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol"; import "../IExternalPositionParser.sol"; import "./AaveDebtPositionDataDecoder.sol"; import "./IAaveDebtPosition.sol"; pragma solidity 0.6.12; /// @title AaveDebtPositionParser /// @author Enzyme Council <[email protected]> /// @notice Parser for Aave Debt Positions contract AaveDebtPositionParser is IExternalPositionParser, AaveDebtPositionDataDecoder { address private immutable VALUE_INTERPRETER; constructor(address _valueInterpreter) public { VALUE_INTERPRETER = _valueInterpreter; } /// @notice Parses the assets to send and receive for the callOnExternalPosition /// @param _externalPosition The _externalPosition to be called /// @param _actionId The _actionId for the callOnExternalPosition /// @param _encodedActionArgs The encoded parameters for the callOnExternalPosition /// @return assetsToTransfer_ The assets to be transferred from the Vault /// @return amountsToTransfer_ The amounts to be transferred from the Vault /// @return assetsToReceive_ The assets to be received at the Vault function parseAssetsForAction( address _externalPosition, uint256 _actionId, bytes memory _encodedActionArgs ) external override returns ( address[] memory assetsToTransfer_, uint256[] memory amountsToTransfer_, address[] memory assetsToReceive_ ) { if (_actionId == uint256(IAaveDebtPosition.Actions.AddCollateral)) { // No need to validate aTokens, as the worst case would be that this function is used // to indirectly add and track a misc supported asset (assetsToTransfer_, amountsToTransfer_) = __decodeAddCollateralActionArgs( _encodedActionArgs ); __validateSupportedAssets(assetsToTransfer_); } else if (_actionId == uint256(IAaveDebtPosition.Actions.Borrow)) { // No need to validate tokens, as `borrow()` call to Aave will fail for invalid tokens, // and even if Aave logic changes to fail silently, the worst case would be that // this function is used to indirectly add and track a misc supported asset (assetsToReceive_, ) = __decodeBorrowActionArgs(_encodedActionArgs); __validateSupportedAssets(assetsToReceive_); } else if (_actionId == uint256(IAaveDebtPosition.Actions.RemoveCollateral)) { // Lib validates that each is a valid collateral asset (assetsToReceive_, ) = __decodeRemoveCollateralActionArgs(_encodedActionArgs); } else if (_actionId == uint256(IAaveDebtPosition.Actions.RepayBorrow)) { // Lib validates that each is a valid borrowed asset (assetsToTransfer_, amountsToTransfer_) = __decodeRepayBorrowActionArgs( _encodedActionArgs ); for (uint256 i; i < assetsToTransfer_.length; i++) { if (amountsToTransfer_[i] == type(uint256).max) { // Transfers the full repay amount to the external position, // which will still call `repay()` on the lending pool with max uint. // This is fine, because `repay()` only uses up to the full repay amount. address debtToken = IAaveDebtPosition(_externalPosition) .getDebtTokenForBorrowedAsset(assetsToTransfer_[i]); amountsToTransfer_[i] = ERC20(debtToken).balanceOf(_externalPosition); } } } // No validations or transferred assets passed for Actions.ClaimRewards return (assetsToTransfer_, amountsToTransfer_, assetsToReceive_); } /// @notice Parse and validate input arguments to be used when initializing a newly-deployed ExternalPositionProxy /// @dev Empty for this external position type function parseInitArgs(address, bytes memory) external override returns (bytes memory) {} /// @dev Helper to validate that assets are supported within the protocol function __validateSupportedAssets(address[] memory _assets) private view { for (uint256 i; i < _assets.length; i++) { require( IValueInterpreter(VALUE_INTERPRETER).isSupportedAsset(_assets[i]), "__validateSupportedAssets: Unsupported asset" ); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "../../../../../persistent/external-positions/IExternalPosition.sol"; pragma solidity 0.6.12; /// @title IAaveDebtPosition Interface /// @author Enzyme Council <[email protected]> interface IAaveDebtPosition is IExternalPosition { enum Actions {AddCollateral, RemoveCollateral, Borrow, RepayBorrow, ClaimRewards} function getDebtTokenForBorrowedAsset(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IDerivativePriceFeed.sol"; /// @title AggregatedDerivativePriceFeedMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches /// rate requests to the appropriate feed abstract contract AggregatedDerivativePriceFeedMixin { event DerivativeAdded(address indexed derivative, address priceFeed); event DerivativeRemoved(address indexed derivative); mapping(address => address) private derivativeToPriceFeed; /// @notice Gets the rates for 1 unit of the derivative to its underlying assets /// @param _derivative The derivative for which to get the rates /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The rates for the _derivative to the underlyings_ function __calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) internal returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address derivativePriceFeed = getPriceFeedForDerivative(_derivative); require( derivativePriceFeed != address(0), "calcUnderlyingValues: _derivative is not supported" ); return IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues( _derivative, _derivativeAmount ); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds) internal { require( _derivatives.length == _priceFeeds.length, "__addDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { require( getPriceFeedForDerivative(_derivatives[i]) == address(0), "__addDerivatives: Already added" ); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeAdded(_derivatives[i], _priceFeeds[i]); } } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function __removeDerivatives(address[] memory _derivatives) internal { for (uint256 i = 0; i < _derivatives.length; i++) { require( getPriceFeedForDerivative(_derivatives[i]) != address(0), "removeDerivatives: Derivative not yet added" ); delete derivativeToPriceFeed[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } // PRIVATE FUNCTIONS /// @dev Helper to validate a derivative price feed function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view { require( IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative), "__validateDerivativePriceFeed: Unsupported derivative" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the registered price feed for a given derivative /// @return priceFeed_ The price feed contract address function getPriceFeedForDerivative(address _derivative) public view returns (address priceFeed_) { return derivativeToPriceFeed[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Simple interface for derivative price source oracle implementations interface IDerivativePriceFeed { function calcUnderlyingValues(address, uint256) external returns (address[] memory, uint256[] memory); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../interfaces/IChainlinkAggregator.sol"; /// @title ChainlinkPriceFeedMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Chainlink oracles as price sources abstract contract ChainlinkPriceFeedMixin { using SafeMath for uint256; event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator); event PrimitiveAdded( address indexed primitive, address aggregator, RateAsset rateAsset, uint256 unit ); event PrimitiveRemoved(address indexed primitive); enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } uint256 private constant ETH_UNIT = 10**18; uint256 private immutable STALE_RATE_THRESHOLD; address private immutable WETH_TOKEN; address private ethUsdAggregator; mapping(address => AggregatorInfo) private primitiveToAggregatorInfo; mapping(address => uint256) private primitiveToUnit; constructor(address _wethToken, uint256 _staleRateThreshold) public { STALE_RATE_THRESHOLD = _staleRateThreshold; WETH_TOKEN = _wethToken; } // INTERNAL FUNCTIONS /// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount function __calcCanonicalValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) internal view returns (uint256 quoteAssetAmount_) { // Case where _baseAsset == _quoteAsset is handled by ValueInterpreter int256 baseAssetRate = __getLatestRateData(_baseAsset); require(baseAssetRate > 0, "__calcCanonicalValue: Invalid base asset rate"); int256 quoteAssetRate = __getLatestRateData(_quoteAsset); require(quoteAssetRate > 0, "__calcCanonicalValue: Invalid quote asset rate"); return __calcConversionAmount( _baseAsset, _baseAssetAmount, uint256(baseAssetRate), _quoteAsset, uint256(quoteAssetRate) ); } /// @dev Helper to set the `ethUsdAggregator` value function __setEthUsdAggregator(address _nextEthUsdAggregator) internal { address prevEthUsdAggregator = getEthUsdAggregator(); require( _nextEthUsdAggregator != prevEthUsdAggregator, "__setEthUsdAggregator: Value already set" ); __validateAggregator(_nextEthUsdAggregator); ethUsdAggregator = _nextEthUsdAggregator; emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator); } // PRIVATE FUNCTIONS /// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset function __calcConversionAmount( address _baseAsset, uint256 _baseAssetAmount, uint256 _baseAssetRate, address _quoteAsset, uint256 _quoteAssetRate ) private view returns (uint256 quoteAssetAmount_) { RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset); RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset); uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset); uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset); // If rates are both in ETH or both in USD if (baseAssetRateAsset == quoteAssetRateAsset) { return __calcConversionAmountSameRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate ); } (, int256 ethPerUsdRate, , uint256 ethPerUsdRateLastUpdatedAt, ) = IChainlinkAggregator( getEthUsdAggregator() ) .latestRoundData(); require(ethPerUsdRate > 0, "__calcConversionAmount: Bad ethUsd rate"); __validateRateIsNotStale(ethPerUsdRateLastUpdatedAt); // If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD if (baseAssetRateAsset == RateAsset.ETH) { return __calcConversionAmountEthRateAssetToUsdRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ); } // If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH return __calcConversionAmountUsdRateAssetToEthRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ); } /// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate function __calcConversionAmountEthRateAssetToUsdRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow. // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div( ETH_UNIT ); return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates function __calcConversionAmountSameRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow return _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _baseAssetUnit.mul(_quoteAssetRate) ); } /// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate function __calcConversionAmountUsdRateAssetToEthRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _ethPerUsdRate ); return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to get the latest rate for a given primitive function __getLatestRateData(address _primitive) private view returns (int256 rate_) { if (_primitive == getWethToken()) { return int256(ETH_UNIT); } address aggregator = getAggregatorForPrimitive(_primitive); require(aggregator != address(0), "__getLatestRateData: Primitive does not exist"); uint256 rateUpdatedAt; (, rate_, , rateUpdatedAt, ) = IChainlinkAggregator(aggregator).latestRoundData(); __validateRateIsNotStale(rateUpdatedAt); return rate_; } /// @dev Helper to validate that a rate is not from a round considered to be stale function __validateRateIsNotStale(uint256 _latestUpdatedAt) private view { require( _latestUpdatedAt >= block.timestamp.sub(getStaleRateThreshold()), "__validateRateIsNotStale: Stale rate detected" ); } ///////////////////////// // PRIMITIVES REGISTRY // ///////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function __addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) internal { require( _primitives.length == _aggregators.length, "__addPrimitives: Unequal _primitives and _aggregators array lengths" ); require( _primitives.length == _rateAssets.length, "__addPrimitives: Unequal _primitives and _rateAssets array lengths" ); for (uint256 i; i < _primitives.length; i++) { require( getAggregatorForPrimitive(_primitives[i]) == address(0), "__addPrimitives: Value already set" ); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); // Store the amount that makes up 1 unit given the asset's decimals uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals()); primitiveToUnit[_primitives[i]] = unit; emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit); } } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function __removePrimitives(address[] calldata _primitives) internal { for (uint256 i; i < _primitives.length; i++) { require( getAggregatorForPrimitive(_primitives[i]) != address(0), "__removePrimitives: Primitive not yet added" ); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit PrimitiveRemoved(_primitives[i]); } } // PRIVATE FUNCTIONS /// @dev Helper to validate an aggregator by checking its return values for the expected interface function __validateAggregator(address _aggregator) private view { (, int256 answer, , uint256 updatedAt, ) = IChainlinkAggregator(_aggregator) .latestRoundData(); require(answer > 0, "__validateAggregator: No rate detected"); __validateRateIsNotStale(updatedAt); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the aggregator for a primitive /// @param _primitive The primitive asset for which to get the aggregator value /// @return aggregator_ The aggregator address function getAggregatorForPrimitive(address _primitive) public view returns (address aggregator_) { return primitiveToAggregatorInfo[_primitive].aggregator; } /// @notice Gets the `ethUsdAggregator` variable value /// @return ethUsdAggregator_ The `ethUsdAggregator` variable value function getEthUsdAggregator() public view returns (address ethUsdAggregator_) { return ethUsdAggregator; } /// @notice Gets the rateAsset variable value for a primitive /// @return rateAsset_ The rateAsset variable value /// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus /// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the /// behavior more explicit function getRateAssetForPrimitive(address _primitive) public view returns (RateAsset rateAsset_) { if (_primitive == getWethToken()) { return RateAsset.ETH; } return primitiveToAggregatorInfo[_primitive].rateAsset; } /// @notice Gets the `STALE_RATE_THRESHOLD` variable value /// @return staleRateThreshold_ The `STALE_RATE_THRESHOLD` value function getStaleRateThreshold() public view returns (uint256 staleRateThreshold_) { return STALE_RATE_THRESHOLD; } /// @notice Gets the unit variable value for a primitive /// @return unit_ The unit variable value function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) { if (_primitive == getWethToken()) { return ETH_UNIT; } return primitiveToUnit[_primitive]; } /// @notice Gets the `WETH_TOKEN` variable value /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() public view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256); function isSupportedAsset(address) external view returns (bool); function isSupportedDerivativeAsset(address) external view returns (bool); function isSupportedPrimitiveAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../utils/FundDeployerOwnerMixin.sol"; import "../../utils/MathHelpers.sol"; import "../price-feeds/derivatives/AggregatedDerivativePriceFeedMixin.sol"; import "../price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../price-feeds/primitives/ChainlinkPriceFeedMixin.sol"; import "./IValueInterpreter.sol"; /// @title ValueInterpreter Contract /// @author Enzyme Council <[email protected]> /// @notice Interprets price feeds to provide covert value between asset pairs contract ValueInterpreter is IValueInterpreter, FundDeployerOwnerMixin, AggregatedDerivativePriceFeedMixin, ChainlinkPriceFeedMixin, MathHelpers { using SafeMath for uint256; // Used to only tolerate a max rounding discrepancy of 0.01% // when converting values via an inverse rate uint256 private constant MIN_INVERSE_RATE_AMOUNT = 10000; constructor( address _fundDeployer, address _wethToken, uint256 _chainlinkStaleRateThreshold ) public FundDeployerOwnerMixin(_fundDeployer) ChainlinkPriceFeedMixin(_wethToken, _chainlinkStaleRateThreshold) {} // EXTERNAL FUNCTIONS /// @notice Calculates the total value of given amounts of assets in a single quote asset /// @param _baseAssets The assets to convert /// @param _amounts The amounts of the _baseAssets to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state. /// Does not handle a derivative quote asset. function calcCanonicalAssetsTotalValue( address[] memory _baseAssets, uint256[] memory _amounts, address _quoteAsset ) external override returns (uint256 value_) { require( _baseAssets.length == _amounts.length, "calcCanonicalAssetsTotalValue: Arrays unequal lengths" ); require( isSupportedPrimitiveAsset(_quoteAsset), "calcCanonicalAssetsTotalValue: Unsupported _quoteAsset" ); for (uint256 i; i < _baseAssets.length; i++) { uint256 assetValue = __calcAssetValue(_baseAssets[i], _amounts[i], _quoteAsset); value_ = value_.add(assetValue); } return value_; } // PUBLIC FUNCTIONS /// @notice Calculates the value of a given amount of one asset in terms of another asset /// @param _baseAsset The asset from which to convert /// @param _amount The amount of the _baseAsset to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The equivalent quantity in the _quoteAsset /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state. /// See also __calcPrimitiveToDerivativeValue() for important notes regarding a derivative _quoteAsset. function calcCanonicalAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) external override returns (uint256 value_) { if (_baseAsset == _quoteAsset || _amount == 0) { return _amount; } if (isSupportedPrimitiveAsset(_quoteAsset)) { return __calcAssetValue(_baseAsset, _amount, _quoteAsset); } else if ( isSupportedDerivativeAsset(_quoteAsset) && isSupportedPrimitiveAsset(_baseAsset) ) { return __calcPrimitiveToDerivativeValue(_baseAsset, _amount, _quoteAsset); } revert("calcCanonicalAssetValue: Unsupported conversion"); } /// @notice Checks whether an asset is a supported asset /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported asset function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return isSupportedPrimitiveAsset(_asset) || isSupportedDerivativeAsset(_asset); } // PRIVATE FUNCTIONS /// @dev Helper to differentially calculate an asset value /// based on if it is a primitive or derivative asset. function __calcAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) private returns (uint256 value_) { if (_baseAsset == _quoteAsset || _amount == 0) { return _amount; } // Handle case that asset is a primitive if (isSupportedPrimitiveAsset(_baseAsset)) { return __calcCanonicalValue(_baseAsset, _amount, _quoteAsset); } // Handle case that asset is a derivative address derivativePriceFeed = getPriceFeedForDerivative(_baseAsset); if (derivativePriceFeed != address(0)) { return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset); } revert("__calcAssetValue: Unsupported _baseAsset"); } /// @dev Helper to calculate the value of a derivative in an arbitrary asset. /// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens). /// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP) function __calcDerivativeValue( address _derivativePriceFeed, address _derivative, uint256 _amount, address _quoteAsset ) private returns (uint256 value_) { (address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed( _derivativePriceFeed ) .calcUnderlyingValues(_derivative, _amount); require(underlyings.length > 0, "__calcDerivativeValue: No underlyings"); require( underlyings.length == underlyingAmounts.length, "__calcDerivativeValue: Arrays unequal lengths" ); for (uint256 i = 0; i < underlyings.length; i++) { uint256 underlyingValue = __calcAssetValue( underlyings[i], underlyingAmounts[i], _quoteAsset ); value_ = value_.add(underlyingValue); } } /// @dev Helper to calculate the value of a primitive base asset in a derivative quote asset. /// Assumes that the _primitiveBaseAsset and _derivativeQuoteAsset have been validated as supported. /// Callers of this function should be aware of the following points, and take precautions as-needed, /// such as prohibiting a derivative quote asset: /// - The returned value will be slightly less the actual canonical value due to the conversion formula's /// handling of the intermediate inverse rate (see comments below). /// - If the assets involved have an extreme rate and/or have a low ERC20.decimals() value, /// the inverse rate might not be considered "sufficient", and will revert. function __calcPrimitiveToDerivativeValue( address _primitiveBaseAsset, uint256 _primitiveBaseAssetAmount, address _derivativeQuoteAsset ) private returns (uint256 value_) { uint256 derivativeUnit = 10**uint256(ERC20(_derivativeQuoteAsset).decimals()); address derivativePriceFeed = getPriceFeedForDerivative(_derivativeQuoteAsset); uint256 primitiveAmountForDerivativeUnit = __calcDerivativeValue( derivativePriceFeed, _derivativeQuoteAsset, derivativeUnit, _primitiveBaseAsset ); // Only tolerate a max rounding discrepancy require( primitiveAmountForDerivativeUnit > MIN_INVERSE_RATE_AMOUNT, "__calcPrimitiveToDerivativeValue: Insufficient rate" ); // Adds `1` to primitiveAmountForDerivativeUnit so that the final return value is // slightly less than the actual value, which is congruent with how all other // asset conversions are floored in the protocol. return __calcRelativeQuantity( primitiveAmountForDerivativeUnit.add(1), derivativeUnit, _primitiveBaseAssetAmount ); } //////////////////////////// // PRIMITIVES (CHAINLINK) // //////////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyFundDeployerOwner { __addPrimitives(_primitives, _aggregators, _rateAssets); } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function removePrimitives(address[] calldata _primitives) external onlyFundDeployerOwner { __removePrimitives(_primitives); } /// @notice Sets the `ehUsdAggregator` variable value /// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyFundDeployerOwner { __setEthUsdAggregator(_nextEthUsdAggregator); } /// @notice Updates a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to update /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function updatePrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyFundDeployerOwner { __removePrimitives(_primitives); __addPrimitives(_primitives, _aggregators, _rateAssets); } // PUBLIC FUNCTIONS /// @notice Checks whether an asset is a supported primitive /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedPrimitiveAsset(address _asset) public view override returns (bool isSupported_) { return _asset == getWethToken() || getAggregatorForPrimitive(_asset) != address(0); } //////////////////////////////////// // DERIVATIVE PRICE FEED REGISTRY // //////////////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyFundDeployerOwner { __addDerivatives(_derivatives, _priceFeeds); } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function removeDerivatives(address[] calldata _derivatives) external onlyFundDeployerOwner { __removeDerivatives(_derivatives); } /// @notice Updates a list of derivatives with the given price feed values /// @param _derivatives The derivatives to update /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyFundDeployerOwner { __removeDerivatives(_derivatives); __addDerivatives(_derivatives, _priceFeeds); } // PUBLIC FUNCTIONS /// @notice Checks whether an asset is a supported derivative /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported derivative function isSupportedDerivativeAsset(address _asset) public view override returns (bool isSupported_) { return getPriceFeedForDerivative(_asset) != address(0); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IChainlinkAggregator Interface /// @author Enzyme Council <[email protected]> interface IChainlinkAggregator { function latestRoundData() external view returns ( uint80, int256, uint256, uint256, uint80 ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() public view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @title MathHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for common math operations abstract contract MathHelpers { using SafeMath for uint256; /// @dev Calculates a proportional value relative to a known ratio. /// Caller is responsible as-necessary for: /// 1. validating _quantity1 to be non-zero /// 2. validating relativeQuantity2_ to be non-zero function __calcRelativeQuantity( uint256 _quantity1, uint256 _quantity2, uint256 _relativeQuantity1 ) internal pure returns (uint256 relativeQuantity2_) { return _relativeQuantity1.mul(_quantity2).div(_quantity1); } }
Adds a list of derivatives with the given price feed values _derivatives The derivatives to add _priceFeeds The ordered price feeds corresponding to the list of _derivatives
function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyFundDeployerOwner { __addDerivatives(_derivatives, _priceFeeds); }
1,406,601
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "../../SinglePlus.sol"; import "../../interfaces/IConverter.sol"; import "../../interfaces/curve/ICurveFi.sol"; import "../../interfaces/badger/IBadgerSett.sol"; import "../../interfaces/badger/IBadgerTree.sol"; import "../../interfaces/uniswap/IUniswapRouter.sol"; /** * @dev Single plus for Badger renCrv. */ contract BadgerRenCrvPlus is SinglePlus { using SafeERC20Upgradeable for IERC20Upgradeable; address public constant BADGER_RENCRV = address(0x6dEf55d2e18486B9dDfaA075bc4e4EE0B28c1545); address public constant BADGER_TREE = address(0x660802Fc641b154aBA66a62137e71f331B6d787A); address public constant WBTC = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public constant BADGER = address(0x3472A5A71965499acd81997a54BBA8D852C6E53d); address public constant DIGG = address(0x798D1bE841a82a273720CE31c822C61a67a601C3); address public constant RENCRV = address(0x49849C98ae39Fff122806C06791Fa73784FB3675); address public constant UNISWAP = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Uniswap RouterV2 address public constant SUSHISWAP = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Sushiswap RouterV2 address public constant REN_SWAP = address(0x93054188d876f558f4a66B2EF1d97d16eDf0895B); // REN swap /** * We use a converter to convert renCrv --> brenCrv because brenCrv has a whitelist. * Therefore, we use a converter to facilitate testing brenCrv+. * Once brenCrv+ is whitelisted, we will upgrade the contract to replace the converter. */ address public converter; /** * @dev Initializes brenCrv+. */ function initialize(address _converter) public initializer { SinglePlus.initialize(BADGER_RENCRV, "", ""); converter = _converter; } /** * @dev Harvest additional yield from the investment. * Only governance or strategist can call this function. */ function harvest(address[] calldata _tokens, uint256[] calldata _cumulativeAmounts, uint256 _index, uint256 _cycle, bytes32[] calldata _merkleProof, uint256[] calldata _amountsToClaim) public virtual onlyStrategist { // 1. Harvest from Badger Tree IBadgerTree(BADGER_TREE).claim(_tokens, _cumulativeAmounts, _index, _cycle, _merkleProof, _amountsToClaim); // 2. Sushi: Badger --> WBTC uint256 _badger = IERC20Upgradeable(BADGER).balanceOf(address(this)); if (_badger > 0) { IERC20Upgradeable(BADGER).approve(SUSHISWAP, _badger); address[] memory _path = new address[](2); _path[0] = BADGER; _path[1] = WBTC; IUniswapRouter(SUSHISWAP).swapExactTokensForTokens(_badger, uint256(0), _path, address(this), block.timestamp); } // 3: Uniswap: Digg --> WBTC uint256 _digg = IERC20Upgradeable(DIGG).balanceOf(address(this)); if (_digg > 0) { IERC20Upgradeable(DIGG).approve(UNISWAP, _digg); address[] memory _path = new address[](2); _path[0] = DIGG; _path[1] = WBTC; IUniswapRouter(UNISWAP).swapExactTokensForTokens(_digg, uint256(0), _path, address(this), block.timestamp); } // 4: WBTC --> renCrv uint256 _wbtc = IERC20Upgradeable(WBTC).balanceOf(address(this)); if (_wbtc == 0) return; // If there is performance fee, charged in WBTC uint256 _fee = 0; if (performanceFee > 0) { _fee = _wbtc * performanceFee / PERCENT_MAX; IERC20Upgradeable(WBTC).safeTransfer(treasury, _fee); _wbtc -= _fee; } IERC20Upgradeable(WBTC).approve(REN_SWAP, _wbtc); ICurveFi(REN_SWAP).add_liquidity([0, _wbtc], 0); // 5: renCrv --> brenCrv address _converter = converter; uint256 _renCrv = IERC20Upgradeable(RENCRV).balanceOf(address(this)); IERC20Upgradeable(RENCRV).approve(_converter, _renCrv); uint256 _before = IERC20Upgradeable(BADGER_RENCRV).balanceOf(address(this)); uint256 _target = _renCrv * WAD / IBadgerSett(BADGER_RENCRV).getPricePerFullShare(); IConverter(_converter).convert(RENCRV, BADGER_RENCRV, _renCrv, _target); uint256 _after = IERC20Upgradeable(BADGER_RENCRV).balanceOf(address(this)); require(_after >= _before + _target, "convert fail"); // Also it's a good time to rebase! rebase(); emit Harvested(BADGER_RENCRV, _wbtc, _fee); } /** * @dev Returns the amount of single plus token is worth for one underlying token, expressed in WAD. */ function _conversionRate() internal view virtual override returns (uint256) { // Both Badger's share price and Curve's virtual price are in WAD return IBadgerSett(BADGER_RENCRV).getPricePerFullShare() * ICurveFi(REN_SWAP).get_virtual_price() / WAD; } }
We use a converter to convert renCrv --> brenCrv because brenCrv has a whitelist. Therefore, we use a converter to facilitate testing brenCrv+. Once brenCrv+ is whitelisted, we will upgrade the contract to replace the converter./ Initializes brenCrv+./
function initialize(address _converter) public initializer { SinglePlus.initialize(BADGER_RENCRV, "", ""); converter = _converter; }
5,412,282
pragma solidity ^0.6.7; import "https://github.com/smartcontractkit/chainlink/blob/master/evm-contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; contract DiamondHands { AggregatorV3Interface internal priceFeed; /** * Network: Kovan * Aggregator: ETH/USD * Address: 0x9326BFA02ADD2366b30bacB125260Af641031331 */ //Stored amount of ETH - This is the same amount to be returned later uint public storedTokens; //Address of investor, tokens will be returned to this address when price condition is met address payable public investor; //Value of token which acts as unlock condition uint public moonValue; //State of contract enum State { Created, Locked, Inactive } State public state; constructor() public { priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); } /** * Returns the latest price */ function getLatestPrice() private view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); return price; } function deposit(uint256 amount) payable public { require(msg.value == amount); investor = msg.sender; } function getBalance() public view returns (uint256) { return address(this).balance; } function withdraw() public { investor.transfer(address(this).balance); } function onTheMoon() public returns (bool) { if (getLatestPrice() > 1){ withdraw(); return true; } else{ return false; } } }
Returns the latest price/
function getLatestPrice() private view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); return price; }
896,036
./full_match/1/0x74E08090Ad84d037A9E870Ad0d458963CD5050Eb/sources/contracts/Traits.sol
administrative to upload the names and images associated with each trait traitType the trait type to upload the traits for (see traitTypes for a mapping) traits the names and base64 encoded PNGs for each trait traitIds the ids for traits/
function uploadTraits(uint8 traitType, uint8[] calldata traitIds, Trait[] calldata traits) external onlyOwner { require(traitIds.length == traits.length, "Mismatched inputs"); for (uint i = 0; i < traits.length; i++) { traitData[traitType][traitIds[i]] = Trait( traits[i].name, traits[i].png ); } }
16,576,562
// SPDX-License-Identifier: No License pragma solidity ^0.8.0; import "./interfaces/IProtocol.sol"; import "./interfaces/IFlashBorrower.sol"; import "./interfaces/IERC3156FlashLender.sol"; import "./interfaces/ICover.sol"; import "./interfaces/IBPool.sol"; import "./ERC20/IERC20.sol"; import "./ERC20/IYERC20.sol"; import "./ERC20/SafeERC20.sol"; import "./utils/Ownable.sol"; /** * @title Cover FlashBorrower * @author alan */ contract CoverFlashBorrower is Ownable, IFlashBorrower { using SafeERC20 for IERC20; IERC3156FlashLender public flashLender; IERC20 public constant dai = IERC20(0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa); IYERC20 public constant ydai = IYERC20(0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01); modifier onlySupportedCollaterals(address _collateral) { require(_collateral == address(dai) || _collateral == address(ydai), "only supports DAI and yDAI collaterals"); _; } constructor (IERC3156FlashLender _flashLender) { flashLender = _flashLender; } /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external override returns(bytes32) { require(msg.sender == address(flashLender), "CoverFlashBorrower: Untrusted lender"); require(initiator == address(this), "CoverFlashBorrower: Untrusted loan initiator"); require(token == address(dai), "!dai"); // For v1, can only flashloan DAI uint256 amountOwed = amount + fee; FlashLoanData memory flashLoanData = abi.decode(data, (FlashLoanData)); if (flashLoanData.isBuy) { _onFlashLoanBuyClaim(flashLoanData, amount, amountOwed); } else { _onFlashLoanSellClaim(flashLoanData, amount, amountOwed); } return keccak256("ERC3156FlashBorrower.onFlashLoan"); } /** * @dev Flash loan the amount of collateral needed to mint `_amountCovTokens` covTokens * - If collateral is yDAI, `_amountCovTokens` is scaled by current price of yDAI to flash borrow enough DAI */ function flashBuyClaim( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToBuy, uint256 _maxAmountToSpend ) external override onlySupportedCollaterals(_collateral) { bytes memory data = abi.encode(FlashLoanData({ isBuy: true, bpool: _bpool, protocol: _protocol, caller: msg.sender, collateral: _collateral, timestamp: _timestamp, amount: _amountToBuy, limit: _maxAmountToSpend })); uint256 amountDaiNeeded; if (_collateral == address(dai)) { amountDaiNeeded = _amountToBuy; } else if (_collateral == address(ydai)) { amountDaiNeeded = _amountToBuy * ydai.getPricePerFullShare(); } require(amountDaiNeeded <= flashLender.maxFlashAmount(address(dai)), "_amount > lender reserves"); uint256 _allowance = dai.allowance(address(this), address(flashLender)); uint256 _fee = flashLender.flashFee(address(dai), amountDaiNeeded); uint256 _repayment = amountDaiNeeded + _fee; dai.approve(address(flashLender), _allowance + _repayment); flashLender.flashLoan(address(this), address(dai), amountDaiNeeded, data); } /** * @dev Flash loan the amount of DAI needed to buy enough NOCLAIM to redeem with CLAIM tokens */ function flashSellClaim( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToSell, uint256 _minAmountToReturn ) external override onlySupportedCollaterals(_collateral) { bytes memory data = abi.encode(FlashLoanData({ isBuy: false, bpool: _bpool, protocol: _protocol, caller: msg.sender, collateral: _collateral, timestamp: _timestamp, amount: _amountToSell, limit: _minAmountToReturn })); (, IERC20 noclaimToken) = _getCovTokenAddresses(_protocol, _collateral, _timestamp); uint256 amountDaiNeeded = _calcInGivenOut(_bpool, address(dai), address(noclaimToken), _amountToSell); require(amountDaiNeeded <= flashLender.maxFlashAmount(address(dai)), "_amount > lender reserves"); uint256 _allowance = dai.allowance(address(this), address(flashLender)); uint256 _fee = flashLender.flashFee(address(dai), amountDaiNeeded); uint256 _repayment = amountDaiNeeded + _fee; dai.approve(address(flashLender), _allowance + _repayment); flashLender.flashLoan(address(this), address(dai), amountDaiNeeded, data); } function setFlashLender(address _flashLender) external override onlyOwner { require(_flashLender != address(0), "_flashLender is 0"); flashLender = IERC3156FlashLender(_flashLender); } /// @notice Tokens that are accidentally sent to this contract can be recovered function collect(IERC20 _token) external override onlyOwner { uint256 balance = _token.balanceOf(address(this)); require(balance > 0, "_token balance is 0"); _token.transfer(msg.sender, balance); } function getBuyClaimCost( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToBuy ) external override view onlySupportedCollaterals(_collateral) returns (uint256 totalCost) { uint256 amountDaiNeeded = _amountToBuy; if (_collateral == address(ydai)) { amountDaiNeeded = amountDaiNeeded * ydai.getPricePerFullShare(); } uint256 flashFee = flashLender.flashFee(address(dai), amountDaiNeeded); uint256 daiReceivedFromSwap; { (, IERC20 noclaimToken) = _getCovTokenAddresses(_protocol, _collateral, _timestamp); daiReceivedFromSwap = _calcOutGivenIn(_bpool, address(noclaimToken), _amountToBuy, address(dai)); } totalCost = amountDaiNeeded - daiReceivedFromSwap + flashFee; } function getSellClaimReturn( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToSell, uint256 _redeemFeeNumerator ) external override view onlySupportedCollaterals(_collateral) returns (uint256 totalReturn) { (, IERC20 noclaimToken) = _getCovTokenAddresses(_protocol, _collateral, _timestamp); uint256 amountDaiNeeded = _calcInGivenOut(_bpool, address(dai), address(noclaimToken), _amountToSell); uint256 flashFee = flashLender.flashFee(address(dai), amountDaiNeeded); uint256 daiReceivedFromRedeem; if (_collateral == address(dai)) { daiReceivedFromRedeem = _amountToSell; } else if (_collateral == address(ydai)) { // Adjust for price of yDAI daiReceivedFromRedeem = _amountToSell * ydai.getPricePerFullShare(); } // Adjust for redemption fee daiReceivedFromRedeem = daiReceivedFromRedeem * (10000 - _redeemFeeNumerator) / 10000; totalReturn = daiReceivedFromRedeem - amountDaiNeeded - flashFee; } /** * - If collateral is yDAI, wrap borrowed DAI * - Deposit collateral for covTokens * - Sell NOCLAIM tokens on Balancer to receive DAI * - Calculate amount user needs to pay to repay loan + slippage + fee * - Send minted CLAIM tokens to user */ function _onFlashLoanBuyClaim(FlashLoanData memory data, uint256 amount, uint256 amountOwed) internal { uint256 mintAmount; // Wrap DAI to yDAI if necessary if (data.collateral == address(dai)) { mintAmount = amount; _approve(dai, address(data.protocol), mintAmount); } else if (data.collateral == address(ydai)) { _approve(dai, address(ydai), amount); uint256 ydaiBalBefore = ydai.balanceOf(address(this)); ydai.deposit(amount); mintAmount = ydai.balanceOf(address(this)) - ydaiBalBefore; _approve(ydai, address(data.protocol), mintAmount); } // Mint claim and NOCLAIM tokens using collateral data.protocol.addCover(data.collateral, data.timestamp, mintAmount); (IERC20 claimToken, IERC20 noclaimToken) = _getCovTokenAddresses( data.protocol, data.collateral, data.timestamp ); // Swap exact number of NOCLAIM tokens for DAI on Balancer _approve(noclaimToken, address(data.bpool), mintAmount); (uint256 daiReceived, ) = data.bpool.swapExactAmountIn( address(noclaimToken), mintAmount, address(dai), 0, type(uint256).max ); // Make sure cost is not greater than limit require(amountOwed - daiReceived <= data.limit, "cost exceeds limit"); // User pays for slippage + flash loan fee dai.transferFrom(data.caller, address(this), amountOwed - daiReceived); // Resolve the flash loan dai.transfer(msg.sender, amountOwed); // Transfer claim tokens to caller claimToken.transfer(data.caller, mintAmount); } /** * - Sell DAI for NOCLAIM tokens * - Transfer CLAIM tokens from user to this contract * - Redeem CLAIM and NOCLAIM tokens for collateral * - If collateral is yDAI, unwrap to DAI * - Calculate amount user needs to repay loan + slippage + fee * - Send leftover DAI to user */ function _onFlashLoanSellClaim(FlashLoanData memory data, uint256 amount, uint256 amountOwed) internal { uint256 daiAvailable = amount; _approve(dai, address(data.bpool), amount); (IERC20 claimToken, IERC20 noclaimToken) = _getCovTokenAddresses( data.protocol, data.collateral, data.timestamp ); // Swap DAI for exact number of NOCLAIM tokens (uint256 daiSpent, ) = data.bpool.swapExactAmountOut( address(dai), amount, address(noclaimToken), data.amount, type(uint256).max ); daiAvailable = daiAvailable - daiSpent; // Need an equal number of CLAIM and NOCLAIM tokens claimToken.transferFrom(data.caller, address(this), data.amount); // Redeem CLAIM and NOCLAIM tokens for collateral uint256 collateralBalBefore = IERC20(data.collateral).balanceOf(address(this)); address cover = data.protocol.coverMap(data.collateral, data.timestamp); ICover(cover).redeemCollateral(data.amount); uint256 collateralReceived = IERC20(data.collateral).balanceOf(address(this)) - collateralBalBefore; // Unwrap yDAI to DAI if necessary if (data.collateral == address(dai)) { daiAvailable = daiAvailable + collateralReceived; } else if (data.collateral == address(ydai)) { _approve(ydai, address(ydai), collateralReceived); uint256 daiBalBefore = dai.balanceOf(address(this)); ydai.withdraw(collateralReceived); uint256 daiReceived = dai.balanceOf(address(this)) - daiBalBefore; daiAvailable = daiAvailable + daiReceived; } // Make sure return is not less than limit require(daiAvailable - amountOwed >= data.limit, "returns are less than limit"); // Resolve the flash loan dai.transfer(msg.sender, amountOwed); // Transfer leftover DAI to caller dai.transfer(data.caller, daiAvailable - amountOwed); } function _calcInGivenOut(IBPool _bpool, address _tokenIn, address _tokenOut, uint256 _tokenAmountOut) internal view returns (uint256 tokenAmountIn) { uint256 tokenBalanceIn = _bpool.getBalance(_tokenIn); uint256 tokenWeightIn = _bpool.getNormalizedWeight(_tokenIn); uint256 tokenBalanceOut = _bpool.getBalance(_tokenOut); uint256 tokenWeightOut = _bpool.getNormalizedWeight(_tokenOut); uint256 swapFee = _bpool.getSwapFee(); tokenAmountIn = _bpool.calcInGivenOut( tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeightOut, _tokenAmountOut, swapFee ); } function _calcOutGivenIn(IBPool _bpool, address _tokenIn, uint256 _tokenAmountIn, address _tokenOut) internal view returns (uint256 tokenAmountOut) { uint256 tokenBalanceIn = _bpool.getBalance(_tokenIn); uint256 tokenWeightIn = _bpool.getNormalizedWeight(_tokenIn); uint256 tokenBalanceOut = _bpool.getBalance(_tokenOut); uint256 tokenWeightOut = _bpool.getNormalizedWeight(_tokenOut); uint256 swapFee = _bpool.getSwapFee(); tokenAmountOut = _bpool.calcOutGivenIn( tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeightOut, _tokenAmountIn, swapFee ); } function _getCovTokenAddresses( IProtocol _protocol, address _collateral, uint48 _timestamp ) internal view returns (IERC20 claimToken, IERC20 noclaimToken) { address cover = _protocol.coverMap(_collateral, _timestamp); claimToken = ICover(cover).claimCovToken(); noclaimToken = ICover(cover).noclaimCovToken(); } function _approve(IERC20 _token, address _spender, uint256 _amount) internal { if (_token.allowance(address(this), _spender) < _amount) { _token.approve(_spender, type(uint256).max); } } } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; interface IProtocol { function coverMap(address _collateral, uint48 _expirationTimestamp) external view returns (address); function addCover(address _collateral, uint48 _timestamp, uint256 _amount) external returns (bool); } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; import "./IERC3156FlashBorrower.sol"; import "./IProtocol.sol"; import "./ICover.sol"; import "./IBPool.sol"; import "../ERC20/IERC20.sol"; interface IFlashBorrower is IERC3156FlashBorrower { struct FlashLoanData { bool isBuy; IBPool bpool; IProtocol protocol; address caller; address collateral; uint48 timestamp; uint256 amount; uint256 limit; } function flashBuyClaim( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToBuy, uint256 _maxAmountToSpend ) external; function flashSellClaim( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToSell, uint256 _minAmountToReturn ) external; function getBuyClaimCost( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToBuy ) external view returns (uint256 totalCost); function getSellClaimReturn( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToSell, uint256 _redeemFeeNumerator ) external view returns (uint256 totalReturn); function setFlashLender(address _flashLender) external; function collect(IERC20 _token) external; } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; interface IERC3156FlashLender { /** * @dev The amount of currency available to be lended. * @param token The loan currency. * @return The amount of `token` that can be borrowed. */ function maxFlashAmount( address token ) external view returns (uint256); /** * @dev The fee to be charged for a given loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee( address token, uint256 amount ) external view returns (uint256); /** * @dev Initiate a flash loan. * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. * @param token The loan currency. * @param amount The amount of tokens lent. * @param data Arbitrary data structure, intended to contain user-defined parameters. */ function flashLoan( address receiver, address token, uint256 amount, bytes calldata data ) external; } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; import "../ERC20/IERC20.sol"; interface ICover { function claimCovToken() external view returns (IERC20); function noclaimCovToken() external view returns (IERC20); function redeemCollateral(uint256 _amount) external; } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; interface IBPool { function swapExactAmountIn( address tokenIn, uint256 tokenAmountIn, address tokenOut, uint256 minAmountOut, uint256 maxPrice ) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter); function swapExactAmountOut( address tokenIn, uint256 maxAmountIn, address tokenOut, uint256 tokenAmountOut, uint256 maxPrice ) external returns (uint256 tokenAmountIn, uint256 spotPriceAfter); function calcOutGivenIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountIn, uint256 swapFee ) external view returns (uint256 tokenAmountOut); function calcInGivenOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountOut, uint256 swapFee ) external view returns (uint256 tokenAmountIn); function getNormalizedWeight(address token) external view returns (uint256); function getBalance(address token) external view returns (uint256); function getSwapFee() external view returns (uint256); } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; /** * @title Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; import "./IERC20.sol"; interface IYERC20 is IERC20 { function deposit(uint256 _amount) external; function withdraw(uint256 _shares) external; function getPricePerFullShare() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; interface IERC3156FlashBorrower { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
SPDX-License-Identifier: No License Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); }
297,557
// SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract DevTreasury is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; /// @dev Developer wallet address payable public devWallet; /// @dev SDVD contract address address public sdvd; /// @dev Uniswap router IUniswapV2Router02 uniswapRouter; /// @dev Uniswap factory IUniswapV2Factory uniswapFactory; /// @dev WETH address address weth; /// @dev Uniswap LP address address public pairAddress; /// @notice Release balance every 1 hour to dev wallet uint256 public releaseThreshold = 1 hours; /// @dev Last release timestamp uint256 public releaseTime; constructor (address _uniswapRouter, address _sdvd) public { // Set dev wallet devWallet = msg.sender; // Set uniswap router uniswapRouter = IUniswapV2Router02(_uniswapRouter); // Set uniswap factory uniswapFactory = IUniswapV2Factory(uniswapRouter.factory()); // Get weth address weth = uniswapRouter.WETH(); // Set SDVD address sdvd = _sdvd; // Approve uniswap router to spend sdvd IERC20(sdvd).approve(_uniswapRouter, uint256(- 1)); // Set initial release time releaseTime = block.timestamp; } /* ========== Owner Only ========== */ function init() external onlyOwner { // Get pair address after init because we wait until pair created in lord of coin pairAddress = uniswapFactory.getPair(sdvd, weth); // Renounce ownership immediately after init renounceOwnership(); } /* ========== Mutative ========== */ /// @notice Release SDVD to market regardless the price so dev doesn't own any SDVD from 0.5% fee. /// This is to protect SDVD holders. function release() external { _release(); } /* ========== Internal ========== */ function _release() internal { if (releaseTime.add(releaseThreshold) <= block.timestamp) { // Update release time releaseTime = block.timestamp; // Get SDVD balance uint256 sdvdBalance = IERC20(sdvd).balanceOf(address(this)); // If there is SDVD in this contract // and there is enough liquidity to swap if (sdvdBalance > 0 && IERC20(sdvd).balanceOf(pairAddress) >= sdvdBalance) { address[] memory path = new address[](2); path[0] = sdvd; path[1] = weth; // Swap SDVD to ETH on uniswap // uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( sdvdBalance, 0, path, devWallet, block.timestamp.add(30 minutes) ); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: Unlicensed pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } // SPDX-License-Identifier: Unlicensed pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: Unlicensed pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; import "./uniswapv2/interfaces/IWETH.sol"; import "./interfaces/ILordOfCoin.sol"; import "./interfaces/IBPool.sol"; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract TradingTreasury is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; event Received(address indexed from, uint256 amount); /// @dev Lord of coin address address public controller; /// @dev Uniswap router IUniswapV2Router02 uniswapRouter; /// @dev Uniswap factory IUniswapV2Factory uniswapFactory; /// @dev Balancer pool WETH-MUSD address balancerPool; /// @dev WETH address address weth; /// @dev mUSD contract address address musd; /// @dev SDVD contract address address public sdvd; /// @dev Uniswap LP address address public pairAddress; /// @notice Release balance as sharing pool profit every 1 hour uint256 public releaseThreshold = 1 hours; /// @dev Last release timestamp uint256 public releaseTime; constructor (address _uniswapRouter, address _balancerPool, address _sdvd, address _musd) public { // Set uniswap router uniswapRouter = IUniswapV2Router02(_uniswapRouter); // Set uniswap factory uniswapFactory = IUniswapV2Factory(uniswapRouter.factory()); // Get weth address weth = uniswapRouter.WETH(); // Set balancer pool balancerPool = _balancerPool; // Set SDVD address sdvd = _sdvd; // Set mUSD address musd = _musd; // Approve uniswap to spend SDVD IERC20(sdvd).approve(_uniswapRouter, uint256(- 1)); // Approve balancer to spend WETH IERC20(weth).approve(balancerPool, uint256(- 1)); // Set initial release time releaseTime = block.timestamp; } receive() external payable { emit Received(msg.sender, msg.value); } /* ========== Owner Only ========== */ function init(address _controller) external onlyOwner { // Set Lord of coin address controller = _controller; // Get pair address pairAddress = ILordOfCoin(controller).sdvdEthPairAddress(); // Renounce ownership immediately after init renounceOwnership(); } /* ========== Mutative ========== */ /// @notice Release SDVD to be added as profit function release() external { _release(); } /* ========== Internal ========== */ function _release() internal { if (releaseTime.add(releaseThreshold) <= block.timestamp) { // Update release time releaseTime = block.timestamp; // Get SDVD balance uint256 sdvdBalance = IERC20(sdvd).balanceOf(address(this)); // If there is SDVD in this contract // and there is enough liquidity to swap if (sdvdBalance > 0 && IERC20(sdvd).balanceOf(pairAddress) >= sdvdBalance) { // Use uniswap since this contract is registered as no fee address for swapping SDVD to ETH // Swap path address[] memory path = new address[](2); path[0] = sdvd; path[1] = weth; // Swap SDVD to ETH on uniswap // uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( sdvdBalance, 0, path, address(this), block.timestamp.add(30 minutes) ); // Get all ETH in this contract uint256 ethAmount = address(this).balance; // Convert ETH to WETH IWETH(weth).deposit{ value: ethAmount }(); // Swap WETH to mUSD (uint256 musdAmount,) = IBPool(balancerPool).swapExactAmountIn(weth, ethAmount, musd, 0, uint256(-1)); // Send it to Lord of Coin IERC20(musd).safeTransfer(controller, musdAmount); // Deposit profit ILordOfCoin(controller).depositTradingProfit(musdAmount); } } } } // SPDX-License-Identifier: Unlicensed pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface ILordOfCoin { function marketOpenTime() external view returns (uint256); function dvd() external view returns (address); function sdvd() external view returns (address); function sdvdEthPairAddress() external view returns (address); function buy(uint256 musdAmount) external returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function buyTo(address recipient, uint256 musdAmount) external returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function buyFromETH() payable external returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function sell(uint256 dvdAmount) external returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function sellTo(address recipient, uint256 dvdAmount) external returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function sellToETH(uint256 dvdAmount) external returns (uint256 returnedETH, uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function claimDividend() external returns (uint256 net, uint256 fee); function claimDividendTo(address recipient) external returns (uint256 net, uint256 fee); function claimDividendETH() external returns (uint256 net, uint256 fee, uint256 receivedETH); function checkSnapshot() external; function releaseTreasury() external; function depositTradingProfit(uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IBPool { function isPublicSwap() external view returns (bool); function isFinalized() external view returns (bool); function isBound(address t) external view returns (bool); function getNumTokens() external view returns (uint); function getCurrentTokens() external view returns (address[] memory tokens); function getFinalTokens() external view returns (address[] memory tokens); function getDenormalizedWeight(address token) external view returns (uint); function getTotalDenormalizedWeight() external view returns (uint); function getNormalizedWeight(address token) external view returns (uint); function getBalance(address token) external view returns (uint); function getSwapFee() external view returns (uint); function getController() external view returns (address); function setSwapFee(uint swapFee) external; function setController(address manager) external; function setPublicSwap(bool public_) external; function finalize() external; function bind(address token, uint balance, uint denorm) external; function rebind(address token, uint balance, uint denorm) external; function unbind(address token) external; function gulp(address token) external; function getSpotPrice(address tokenIn, address tokenOut) external view returns (uint spotPrice); function getSpotPriceSansFee(address tokenIn, address tokenOut) external view returns (uint spotPrice); function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external; function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external; function swapExactAmountIn( address tokenIn, uint tokenAmountIn, address tokenOut, uint minAmountOut, uint maxPrice ) external returns (uint tokenAmountOut, uint spotPriceAfter); function swapExactAmountOut( address tokenIn, uint maxAmountIn, address tokenOut, uint tokenAmountOut, uint maxPrice ) external returns (uint tokenAmountIn, uint spotPriceAfter); function joinswapExternAmountIn( address tokenIn, uint tokenAmountIn, uint minPoolAmountOut ) external returns (uint poolAmountOut); function joinswapPoolAmountOut( address tokenIn, uint poolAmountOut, uint maxAmountIn ) external returns (uint tokenAmountIn); function exitswapPoolAmountIn( address tokenOut, uint poolAmountIn, uint minAmountOut ) external returns (uint tokenAmountOut); function exitswapExternAmountOut( address tokenOut, uint tokenAmountOut, uint maxPoolAmountIn ) external returns (uint poolAmountIn); function totalSupply() external view returns (uint); function balanceOf(address whom) external view returns (uint); function allowance(address src, address dst) external view returns (uint); function approve(address dst, uint amt) external returns (bool); function transfer(address dst, uint amt) external returns (bool); function transferFrom( address src, address dst, uint amt ) external returns (bool); function calcSpotPrice( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint swapFee ) external returns (uint spotPrice); function calcOutGivenIn( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountIn, uint swapFee ) external returns (uint tokenAmountOut); function calcInGivenOut( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountOut, uint swapFee ) external returns (uint tokenAmountIn); function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee ) external returns (uint poolAmountOut); function calcSingleInGivenPoolOut( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint poolAmountOut, uint swapFee ) external returns (uint tokenAmountIn); function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee ) external returns (uint tokenAmountOut); function calcPoolInGivenSingleOut( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint tokenAmountOut, uint swapFee ) external returns (uint poolAmountIn); } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; import "./uniswapv2/interfaces/IWETH.sol"; import './interfaces/IERC20Snapshot.sol'; import './interfaces/ITreasury.sol'; import './interfaces/IVault.sol'; import './interfaces/IMasset.sol'; import './interfaces/IDvd.sol'; import './interfaces/ISDvd.sol'; import './interfaces/IPool.sol'; import './interfaces/IBPool.sol'; import './utils/MathUtils.sol'; /// @title Lord of Coin /// @notice Lord of Coin finds the money, for you - to spend it. /// @author Lord Nami // Special thanks to TRIB as inspiration. // Special thanks to Lord Nami mods @AspieJames, @defimoon, @tectumor, @downsin, @ghost, @LordFes, @converge, @cryptycreepy, @cryptpower, @jonsnow // and everyone else who support this project by spreading the words on social media. contract LordOfCoin is ReentrancyGuard { using SafeMath for uint256; using MathUtils for uint256; using SafeERC20 for IERC20; event Bought(address indexed sender, address indexed recipient, uint256 musdAmount, uint256 dvdReceived); event Sold(address indexed sender, address indexed recipient, uint256 dvdAmount, uint256 musdReceived); event SoldToETH(address indexed sender, address indexed recipient, uint256 dvdAmount, uint256 ethReceived); event DividendClaimed(address indexed recipient, uint256 musdReceived); event DividendClaimedETH(address indexed recipient, uint256 ethReceived); event Received(address indexed from, uint256 amount); /// @notice Applied to every buy or sale of DVD. /// @dev Tax denominator uint256 public constant CURVE_TAX_DENOMINATOR = 10; /// @notice Applied to every buy of DVD before bonding curve tax. /// @dev Tax denominator uint256 public constant BUY_TAX_DENOMINATOR = 20; /// @notice Applied to every sale of DVD after bonding curve tax. /// @dev Tax denominator uint256 public constant SELL_TAX_DENOMINATOR = 10; /// @notice The slope of the bonding curve. uint256 public constant DIVIDER = 1000000; // 1 / multiplier 0.000001 (so that we don't deal with decimals) /// @notice Address in which DVD are sent to be burned. /// These DVD can't be redeemed by the reserve. address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; /// @dev Uniswap router IUniswapV2Router02 uniswapRouter; /// @dev WETH token address address weth; /// @dev Balancer pool WETH-MUSD address balancerPool; /// @dev mUSD token mStable address. address musd; /// @notice Dvd token instance. address public dvd; /// @notice SDvd token instance. address public sdvd; /// @notice Pair address for SDVD-ETH on uniswap address public sdvdEthPairAddress; /// @notice SDVD-ETH farming pool. address public sdvdEthPool; /// @notice DVD farming pool. address public dvdPool; /// @notice Dev treasury. address public devTreasury; /// @notice Pool treasury. address public poolTreasury; /// @notice Trading treasury. address public tradingTreasury; /// @notice Total dividend earned since the contract deployment. uint256 public totalDividendClaimed; /// @notice Total reserve value that backs all DVD in circulation. /// @dev Area below the bonding curve. uint256 public totalReserve; /// @notice Interface for integration with mStable. address public vault; /// @notice Current state of the application. /// Either already open (true) or not yet (false). bool public isMarketOpen = false; /// @notice Market will be open on this timestamp uint256 public marketOpenTime; /// @notice Current snapshot id /// Can be thought as week index, since snapshot is increased per week uint256 public snapshotId; /// @notice Snapshot timestamp. uint256 public snapshotTime; /// @notice Snapshot duration. uint256 public SNAPSHOT_DURATION = 1 weeks; /// @dev Total profits on each snapshot id. mapping(uint256 => uint256) private _totalProfitSnapshots; /// @dev Dividend paying SDVD supply on each snapshot id. mapping(uint256 => uint256) private _dividendPayingSDVDSupplySnapshots; /// @dev Flag to determine if account has claim their dividend on each snapshot id. mapping(address => mapping(uint256 => bool)) private _isDividendClaimedSnapshots; receive() external payable { emit Received(msg.sender, msg.value); } constructor( address _vault, address _uniswapRouter, address _balancerPool, address _dvd, address _sdvd, address _sdvdEthPool, address _dvdPool, address _devTreasury, address _poolTreasury, address _tradingTreasury, uint256 _marketOpenTime ) public { // Set vault vault = _vault; // mUSD instance musd = IVault(vault).musd(); // Approve vault to manage mUSD in this contract _approveMax(musd, vault); // Set uniswap router uniswapRouter = IUniswapV2Router02(_uniswapRouter); // Set balancer pool balancerPool = _balancerPool; // Set weth address weth = uniswapRouter.WETH(); // Approve balancer pool to manage mUSD in this contract _approveMax(musd, balancerPool); // Approve balancer pool to manage WETH in this contract _approveMax(weth, balancerPool); // Approve self to spend mUSD in this contract (used to buy from ETH / sell to ETH) _approveMax(musd, address(this)); dvd = _dvd; sdvd = _sdvd; sdvdEthPool = _sdvdEthPool; dvdPool = _dvdPool; devTreasury = _devTreasury; poolTreasury = _poolTreasury; tradingTreasury = _tradingTreasury; // Create SDVD ETH pair sdvdEthPairAddress = IUniswapV2Factory(uniswapRouter.factory()).createPair(sdvd, weth); // Set open time marketOpenTime = _marketOpenTime; // Set initial snapshot timestamp snapshotTime = _marketOpenTime; } /* ========== Modifier ========== */ modifier marketOpen() { require(isMarketOpen, 'Market not open'); _; } modifier onlyTradingTreasury() { require(msg.sender == tradingTreasury, 'Only treasury'); _; } /* ========== Trading Treasury Only ========== */ /// @notice Deposit trading profit to vault function depositTradingProfit(uint256 amount) external onlyTradingTreasury { // Deposit mUSD to vault IVault(vault).deposit(amount); } /* ========== Mutative ========== */ /// @notice Exchanges mUSD to DVD. /// @dev mUSD to be exchanged needs to be approved first. /// @param musdAmount mUSD amount to be exchanged. function buy(uint256 musdAmount) external nonReentrant returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { return _buy(msg.sender, msg.sender, musdAmount); } /// @notice Exchanges mUSD to DVD. /// @dev mUSD to be exchanged needs to be approved first. /// @param recipient Recipient of DVD token. /// @param musdAmount mUSD amount to be exchanged. function buyTo(address recipient, uint256 musdAmount) external nonReentrant returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { return _buy(msg.sender, recipient, musdAmount); } /// @notice Exchanges ETH to DVD. function buyFromETH() payable external nonReentrant returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { return _buy(address(this), msg.sender, _swapETHToMUSD(address(this), msg.value)); } /// @notice Exchanges DVD to mUSD. /// @param dvdAmount DVD amount to be exchanged. function sell(uint256 dvdAmount) external nonReentrant marketOpen returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { return _sell(msg.sender, msg.sender, dvdAmount); } /// @notice Exchanges DVD to mUSD. /// @param recipient Recipient of mUSD. /// @param dvdAmount DVD amount to be exchanged. function sellTo(address recipient, uint256 dvdAmount) external nonReentrant marketOpen returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { return _sell(msg.sender, recipient, dvdAmount); } /// @notice Exchanges DVD to ETH. /// @param dvdAmount DVD amount to be exchanged. function sellToETH(uint256 dvdAmount) external nonReentrant marketOpen returns (uint256 returnedETH, uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { // Sell DVD and receive mUSD in this contract (returnedMUSD, marketTax, curveTax, taxedDVD) = _sell(msg.sender, address(this), dvdAmount); // Swap received mUSD dividend for ether and send it back to sender returnedETH = _swapMUSDToETH(msg.sender, returnedMUSD); emit SoldToETH(msg.sender, msg.sender, dvdAmount, returnedETH); } /// @notice Claim dividend in mUSD. function claimDividend() external nonReentrant marketOpen returns (uint256 dividend) { return _claimDividend(msg.sender, msg.sender); } /// @notice Claim dividend in mUSD. /// @param recipient Recipient of mUSD. function claimDividendTo(address recipient) external nonReentrant marketOpen returns (uint256 dividend) { return _claimDividend(msg.sender, recipient); } /// @notice Claim dividend in ETH. function claimDividendETH() external nonReentrant marketOpen returns (uint256 dividend, uint256 receivedETH) { // Claim dividend to this contract dividend = _claimDividend(msg.sender, address(this)); // Swap received mUSD dividend for ether and send it back to sender receivedETH = _swapMUSDToETH(msg.sender, dividend); emit DividendClaimedETH(msg.sender, receivedETH); } /// @notice Check if we need to create new snapshot. function checkSnapshot() public { if (isMarketOpen) { // If time has passed for 1 week since last snapshot // and market is open if (snapshotTime.add(SNAPSHOT_DURATION) <= block.timestamp) { // Update snapshot timestamp snapshotTime = block.timestamp; // Take new snapshot snapshotId = ISDvd(sdvd).snapshot(); // Save the interest _totalProfitSnapshots[snapshotId] = totalProfit(); // Save dividend paying supply _dividendPayingSDVDSupplySnapshots[snapshotId] = dividendPayingSDVDSupply(); } // If something wrong / there is no interest, lets try again. if (snapshotId > 0 && _totalProfitSnapshots[snapshotId] == 0) { _totalProfitSnapshots[snapshotId] = totalProfit(); } } } /// @notice Release treasury. function releaseTreasury() public { if (isMarketOpen) { ITreasury(devTreasury).release(); ITreasury(poolTreasury).release(); ITreasury(tradingTreasury).release(); } } /* ========== View ========== */ /// @notice Get claimable dividend for address. /// @param account Account address. /// @return dividend Dividend in mUSD. function claimableDividend(address account) public view returns (uint256 dividend) { // If there is no snapshot or already claimed if (snapshotId == 0 || isDividendClaimedAt(account, snapshotId)) { return 0; } // Get sdvd balance at snapshot uint256 sdvdBalance = IERC20Snapshot(sdvd).balanceOfAt(account, snapshotId); if (sdvdBalance == 0) { return 0; } // Get dividend in mUSD based on SDVD balance dividend = sdvdBalance .mul(claimableProfitAt(snapshotId)) .div(dividendPayingSDVDSupplyAt(snapshotId)); } /// @notice Total mUSD that is now forever locked in the protocol. function totalLockedReserve() external view returns (uint256) { return _calculateReserveFromSupply(dvdBurnedAmount()); } /// @notice Total claimable profit. /// @return Total claimable profit in mUSD. function claimableProfit() public view returns (uint256) { return totalProfit().div(2); } /// @notice Total claimable profit in snapshot. /// @return Total claimable profit in mUSD. function claimableProfitAt(uint256 _snapshotId) public view returns (uint256) { return totalProfitAt(_snapshotId).div(2); } /// @notice Total profit. /// @return Total profit in MUSD. function totalProfit() public view returns (uint256) { uint256 vaultBalance = IVault(vault).getBalance(); // Sometimes mStable returns a value lower than the // deposit because their exchange rate gets updated after the deposit. if (vaultBalance < totalReserve) { vaultBalance = totalReserve; } return vaultBalance.sub(totalReserve); } /// @notice Total profit in snapshot. /// @param _snapshotId Snapshot id. /// @return Total profit in MUSD. function totalProfitAt(uint256 _snapshotId) public view returns (uint256) { return _totalProfitSnapshots[_snapshotId]; } /// @notice Check if dividend already claimed by account. /// @return Is dividend claimed. function isDividendClaimedAt(address account, uint256 _snapshotId) public view returns (bool) { return _isDividendClaimedSnapshots[account][_snapshotId]; } /// @notice Total supply of DVD. This includes burned DVD. /// @return Total supply of DVD in wei. function dvdTotalSupply() public view returns (uint256) { return IERC20(dvd).totalSupply(); } /// @notice Total DVD that have been burned. /// @dev These DVD are still in circulation therefore they /// are still considered on the bonding curve formula. /// @return Total burned DVD in wei. function dvdBurnedAmount() public view returns (uint256) { return IERC20(dvd).balanceOf(BURN_ADDRESS); } /// @notice DVD price in wei according to the bonding curve formula. /// @return Current DVD price in wei. function dvdPrice() external view returns (uint256) { // price = supply * multiplier return dvdTotalSupply().roundedDiv(DIVIDER); } /// @notice DVD price floor in wei according to the bonding curve formula. /// @return Current DVD price floor in wei. function dvdPriceFloor() external view returns (uint256) { return dvdBurnedAmount().roundedDiv(DIVIDER); } /// @notice Total supply of Dividend-paying SDVD. /// @return Total supply of SDVD in wei. function dividendPayingSDVDSupply() public view returns (uint256) { // Get total supply return IERC20(sdvd).totalSupply() // Get sdvd in uniswap pair balance .sub(IERC20(sdvd).balanceOf(sdvdEthPairAddress)) // Get sdvd in SDVD-ETH pool .sub(IERC20(sdvd).balanceOf(sdvdEthPool)) // Get sdvd in DVD pool .sub(IERC20(sdvd).balanceOf(dvdPool)) // Get sdvd in pool treasury .sub(IERC20(sdvd).balanceOf(poolTreasury)) // Get sdvd in dev treasury .sub(IERC20(sdvd).balanceOf(devTreasury)) // Get sdvd in trading treasury .sub(IERC20(sdvd).balanceOf(tradingTreasury)); } /// @notice Total supply of Dividend-paying SDVD in snapshot. /// @return Total supply of SDVD in wei. function dividendPayingSDVDSupplyAt(uint256 _snapshotId) public view returns (uint256) { return _dividendPayingSDVDSupplySnapshots[_snapshotId]; } /// @notice Calculates the amount of DVD in exchange for reserve after applying bonding curve tax. /// @param reserveAmount Reserve value in wei to use in the conversion. /// @return Token amount in wei after the 10% tax has been applied. function reserveToDVDTaxed(uint256 reserveAmount) external view returns (uint256) { if (reserveAmount == 0) { return 0; } uint256 tax = reserveAmount.div(CURVE_TAX_DENOMINATOR); uint256 totalDVD = reserveToDVD(reserveAmount); uint256 taxedDVD = reserveToDVD(tax); return totalDVD.sub(taxedDVD); } /// @notice Calculates the amount of reserve in exchange for DVD after applying bonding curve tax. /// @param tokenAmount Token value in wei to use in the conversion. /// @return Reserve amount in wei after the 10% tax has been applied. function dvdToReserveTaxed(uint256 tokenAmount) external view returns (uint256) { if (tokenAmount == 0) { return 0; } uint256 reserveAmount = dvdToReserve(tokenAmount); uint256 tax = reserveAmount.div(CURVE_TAX_DENOMINATOR); return reserveAmount.sub(tax); } /// @notice Calculates the amount of DVD in exchange for reserve. /// @param reserveAmount Reserve value in wei to use in the conversion. /// @return Token amount in wei. function reserveToDVD(uint256 reserveAmount) public view returns (uint256) { return _calculateReserveToDVD(reserveAmount, totalReserve, dvdTotalSupply()); } /// @notice Calculates the amount of reserve in exchange for DVD. /// @param tokenAmount Token value in wei to use in the conversion. /// @return Reserve amount in wei. function dvdToReserve(uint256 tokenAmount) public view returns (uint256) { return _calculateDVDToReserve(tokenAmount, dvdTotalSupply(), totalReserve); } /* ========== Internal ========== */ /// @notice Check if market can be opened function _checkOpenMarket() internal { require(marketOpenTime <= block.timestamp, 'Market not open'); if (!isMarketOpen) { // Set flag isMarketOpen = true; } } /// @notice Exchanges mUSD to DVD. /// @dev mUSD to be exchanged needs to be approved first. /// @param sender Address that has mUSD token. /// @param recipient Address that will receive DVD token. /// @param musdAmount mUSD amount to be exchanged. function _buy(address sender, address recipient, uint256 musdAmount) internal returns (uint256 returnedDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { _checkOpenMarket(); checkSnapshot(); releaseTreasury(); require(musdAmount > 0, 'Cannot buy 0'); // Tax to be included as profit marketTax = musdAmount.div(BUY_TAX_DENOMINATOR); // Get amount after market tax uint256 inAmount = musdAmount.sub(marketTax); // Calculate bonding curve tax in mUSD curveTax = inAmount.div(CURVE_TAX_DENOMINATOR); // Convert mUSD amount to DVD amount uint256 totalDVD = reserveToDVD(inAmount); // Convert tax to DVD amount taxedDVD = reserveToDVD(curveTax); // Calculate DVD for recipient returnedDVD = totalDVD.sub(taxedDVD); // Transfer mUSD from sender to this contract IERC20(musd).safeTransferFrom(sender, address(this), musdAmount); // Deposit mUSD to vault IVault(vault).deposit(musdAmount); // Increase mUSD total reserve totalReserve = totalReserve.add(inAmount); // Send taxed DVD to burn address IDvd(dvd).mint(BURN_ADDRESS, taxedDVD); // Increase recipient DVD balance IDvd(dvd).mint(recipient, returnedDVD); // Increase user DVD Shareholder point IDvd(dvd).increaseShareholderPoint(recipient, returnedDVD); emit Bought(sender, recipient, musdAmount, returnedDVD); } /// @notice Exchanges DVD to mUSD. /// @param sender Address that has DVD token. /// @param recipient Address that will receive mUSD token. /// @param dvdAmount DVD amount to be exchanged. function _sell(address sender, address recipient, uint256 dvdAmount) internal returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { checkSnapshot(); releaseTreasury(); require(dvdAmount <= IERC20(dvd).balanceOf(sender), 'Insufficient balance'); require(dvdAmount > 0, 'Cannot sell 0'); require(IDvd(dvd).shareholderPointOf(sender) >= dvdAmount, 'Insufficient shareholder points'); // Convert number of DVD amount that user want to sell to mUSD amount uint256 reserveAmount = dvdToReserve(dvdAmount); // Calculate tax in mUSD curveTax = reserveAmount.div(CURVE_TAX_DENOMINATOR); // Make sure fee is enough require(curveTax >= 1, 'Insufficient tax'); // Get net amount uint256 net = reserveAmount.sub(curveTax); // Calculate taxed DVD taxedDVD = _calculateReserveToDVD( curveTax, totalReserve.sub(reserveAmount), dvdTotalSupply().sub(dvdAmount) ); // Tax to be included as profit marketTax = net.div(SELL_TAX_DENOMINATOR); // Get musd amount for recipient returnedMUSD = net.sub(marketTax); // Decrease total reserve totalReserve = totalReserve.sub(net); // Reduce user DVD balance IDvd(dvd).burn(sender, dvdAmount); // Send taxed DVD to burn address IDvd(dvd).mint(BURN_ADDRESS, taxedDVD); // Decrease sender DVD Shareholder point IDvd(dvd).decreaseShareholderPoint(sender, dvdAmount); // Redeem mUSD from vault IVault(vault).redeem(returnedMUSD); // Send mUSD to recipient IERC20(musd).safeTransfer(recipient, returnedMUSD); emit Sold(sender, recipient, dvdAmount, returnedMUSD); } /// @notice Claim dividend in mUSD. /// @param sender Address that has SDVD token. /// @param recipient Address that will receive mUSD dividend. function _claimDividend(address sender, address recipient) internal returns (uint256 dividend) { checkSnapshot(); releaseTreasury(); // Get dividend in mUSD based on SDVD balance dividend = claimableDividend(sender); require(dividend > 0, 'No dividend'); // Set dividend as claimed _isDividendClaimedSnapshots[sender][snapshotId] = true; // Redeem mUSD from vault IVault(vault).redeem(dividend); // Send dividend mUSD to user IERC20(musd).safeTransfer(recipient, dividend); emit DividendClaimed(recipient, dividend); } /// @notice Swap ETH to mUSD in this contract. /// @param amount ETH amount. /// @return musdAmount returned mUSD amount. function _swapETHToMUSD(address recipient, uint256 amount) internal returns (uint256 musdAmount) { // Convert ETH to WETH IWETH(weth).deposit{ value: amount }(); // Swap WETH to mUSD (musdAmount,) = IBPool(balancerPool).swapExactAmountIn(weth, amount, musd, 0, uint256(-1)); // Send mUSD if (recipient != address(this)) { IERC20(musd).safeTransfer(recipient, musdAmount); } } /// @notice Swap mUSD to ETH in this contract. /// @param amount mUSD Amount. /// @return ethAmount returned ETH amount. function _swapMUSDToETH(address recipient, uint256 amount) internal returns (uint256 ethAmount) { // Swap mUSD to WETH (ethAmount,) = IBPool(balancerPool).swapExactAmountIn(musd, amount, weth, 0, uint256(-1)); // Convert WETH to ETH IWETH(weth).withdraw(ethAmount); // Send ETH if (recipient != address(this)) { payable(recipient).transfer(ethAmount); } } /// @notice Approve maximum value to spender function _approveMax(address tkn, address spender) internal { uint256 max = uint256(- 1); IERC20(tkn).safeApprove(spender, max); } /** * Supply (s), reserve (r) and token price (p) are in a relationship defined by the bonding curve: * p = m * s * The reserve equals to the area below the bonding curve * r = s^2 / 2 * The formula for the supply becomes * s = sqrt(2 * r / m) * * In solidity computations, we are using divider instead of multiplier (because its an integer). * All values are decimals with 18 decimals (represented as uints), which needs to be compensated for in * multiplications and divisions */ /// @notice Computes the increased supply given an amount of reserve. /// @param _reserveDelta The amount of reserve in wei to be used in the calculation. /// @param _totalReserve The current reserve state to be used in the calculation. /// @param _supply The current supply state to be used in the calculation. /// @return _supplyDelta token amount in wei. function _calculateReserveToDVD( uint256 _reserveDelta, uint256 _totalReserve, uint256 _supply ) internal pure returns (uint256 _supplyDelta) { uint256 _reserve = _totalReserve; uint256 _newReserve = _reserve.add(_reserveDelta); // s = sqrt(2 * r / m) uint256 _newSupply = MathUtils.sqrt( _newReserve .mul(2) .mul(DIVIDER) // inverse the operation (Divider instead of multiplier) .mul(1e18) // compensation for the squared unit ); _supplyDelta = _newSupply.sub(_supply); } /// @notice Computes the decrease in reserve given an amount of DVD. /// @param _supplyDelta The amount of DVD in wei to be used in the calculation. /// @param _supply The current supply state to be used in the calculation. /// @param _totalReserve The current reserve state to be used in the calculation. /// @return _reserveDelta Reserve amount in wei. function _calculateDVDToReserve( uint256 _supplyDelta, uint256 _supply, uint256 _totalReserve ) internal pure returns (uint256 _reserveDelta) { require(_supplyDelta <= _supply, 'Token amount must be less than the supply'); uint256 _newSupply = _supply.sub(_supplyDelta); uint256 _newReserve = _calculateReserveFromSupply(_newSupply); _reserveDelta = _totalReserve.sub(_newReserve); } /// @notice Calculates reserve given a specific supply. /// @param _supply The token supply in wei to be used in the calculation. /// @return _reserve Reserve amount in wei. function _calculateReserveFromSupply(uint256 _supply) internal pure returns (uint256 _reserve) { // r = s^2 * m / 2 _reserve = _supply .mul(_supply) .div(DIVIDER) // inverse the operation (Divider instead of multiplier) .div(2) .roundedDiv(1e18); // correction of the squared unit } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IERC20Snapshot { function balanceOfAt(address account, uint256 snapshotId) external view returns (uint256); function totalSupplyAt(uint256 snapshotId) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface ITreasury { function release() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IVault { function savingsContract() external view returns (address); function musd() external view returns (address); function deposit(uint256) external; function redeem(uint256) external; function getBalance() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import { MassetStructs } from "./MassetStructs.sol"; /// /// @title IMasset /// @dev (Internal) Interface for interacting with Masset /// VERSION: 1.0 /// DATE: 2020-05-05 interface IMasset is MassetStructs { /// @dev Calc interest function collectInterest() external returns (uint256 massetMinted, uint256 newTotalSupply); /// @dev Minting function mint(address _basset, uint256 _bassetQuantity) external returns (uint256 massetMinted); function mintTo(address _basset, uint256 _bassetQuantity, address _recipient) external returns (uint256 massetMinted); function mintMulti(address[] calldata _bAssets, uint256[] calldata _bassetQuantity, address _recipient) external returns (uint256 massetMinted); /// @dev Swapping function swap( address _input, address _output, uint256 _quantity, address _recipient) external returns (uint256 output); function getSwapOutput( address _input, address _output, uint256 _quantity) external view returns (bool, string memory, uint256 output); /// @dev Redeeming function redeem(address _basset, uint256 _bassetQuantity) external returns (uint256 massetRedeemed); function redeemTo(address _basset, uint256 _bassetQuantity, address _recipient) external returns (uint256 massetRedeemed); function redeemMulti(address[] calldata _bAssets, uint256[] calldata _bassetQuantities, address _recipient) external returns (uint256 massetRedeemed); function redeemMasset(uint256 _mAssetQuantity, address _recipient) external; /// @dev Setters for the Manager or Gov to update module info function upgradeForgeValidator(address _newForgeValidator) external; /// @dev Setters for Gov to set system params function setSwapFee(uint256 _swapFee) external; /// @dev Getters function getBasketManager() external view returns(address); function forgeValidator() external view returns (address); function totalSupply() external view returns (uint256); function swapFee() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IDvd is IERC20 { function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; function increaseShareholderPoint(address account, uint256 amount) external; function decreaseShareholderPoint(address account, uint256 amount) external; function shareholderPointOf(address account) external view returns (uint256); function totalShareholderPoint() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface ISDvd is IERC20 { function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; function setMinter(address account, bool value) external; function setNoFeeAddress(address account, bool value) external; function setPairAddress(address _pairAddress) external; function snapshot() external returns (uint256); function syncPairTokenTotalSupply() external returns (bool isPairTokenBurned); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IPool { function openFarm() external; function distributeBonusRewards(uint256 amount) external; function stake(uint256 amount) external; function stakeTo(address recipient, uint256 amount) external; function withdraw(uint256 amount) external; function withdrawTo(address recipient, uint256 amount) external; function claimReward() external; function claimRewardTo(address recipient) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.16 <0.7.0; import '@openzeppelin/contracts/math/SafeMath.sol'; library MathUtils { using SafeMath for uint256; /// @notice Calculates the square root of a given value. function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } /// @notice Rounds a division result. function roundedDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, 'div by 0'); uint256 halfB = (b.mod(2) == 0) ? (b.div(2)) : (b.div(2).add(1)); return (a.mod(b) >= halfB) ? (a.div(b).add(1)) : (a.div(b)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; // // @title MassetStructs // @author Stability Labs Pty. Ltd. // @notice Structs used in the Masset contract and associated Libs interface MassetStructs { // Stores high level basket info struct Basket { // Array of Bassets currently active Basset[] bassets; // Max number of bAssets that can be present in any Basket uint8 maxBassets; // Some bAsset is undergoing re-collateralisation bool undergoingRecol; // // In the event that we do not raise enough funds from the auctioning of a failed Basset, // The Basket is deemed as failed, and is undercollateralised to a certain degree. // The collateralisation ratio is used to calc Masset burn rate. bool failed; uint256 collateralisationRatio; } // Stores bAsset info. The struct takes 5 storage slots per Basset struct Basset { // Address of the bAsset address addr; // Status of the basset, BassetStatus status; // takes uint8 datatype (1 byte) in storage // An ERC20 can charge transfer fee, for example USDT, DGX tokens. bool isTransferFeeCharged; // takes a byte in storage // // 1 Basset * ratio / ratioScale == x Masset (relative value) // If ratio == 10e8 then 1 bAsset = 10 mAssets // A ratio is divised as 10^(18-tokenDecimals) * measurementMultiple(relative value of 1 base unit) uint256 ratio; // Target weights of the Basset (100% == 1e18) uint256 maxWeight; // Amount of the Basset that is held in Collateral uint256 vaultBalance; } // Status of the Basset - has it broken its peg? enum BassetStatus { Default, Normal, BrokenBelowPeg, BrokenAbovePeg, Blacklisted, Liquidating, Liquidated, Failed } // Internal details on Basset struct BassetDetails { Basset bAsset; address integrator; uint8 index; } // All details needed to Forge with multiple bAssets struct ForgePropsMulti { bool isValid; // Flag to signify that forge bAssets have passed validity check Basset[] bAssets; address[] integrators; uint8[] indexes; } // All details needed for proportionate Redemption struct RedeemPropsMulti { uint256 colRatio; Basset[] bAssets; address[] integrators; uint8[] indexes; } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import './MathUtils.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; library LordLib { using SafeMath for uint256; using MathUtils for uint256; /// @notice The slope of the bonding curve. uint256 public constant DIVIDER = 1000000; // 1 / multiplier 0.000001 (so that we don't deal with decimals) /** * Supply (s), reserve (r) and token price (p) are in a relationship defined by the bonding curve: * p = m * s * The reserve equals to the area below the bonding curve * r = s^2 / 2 * The formula for the supply becomes * s = sqrt(2 * r / m) * * In solidity computations, we are using divider instead of multiplier (because its an integer). * All values are decimals with 18 decimals (represented as uints), which needs to be compensated for in * multiplications and divisions */ /// @notice Computes the increased supply given an amount of reserve. /// @param _reserveDelta The amount of reserve in wei to be used in the calculation. /// @param _totalReserve The current reserve state to be used in the calculation. /// @param _supply The current supply state to be used in the calculation. /// @return token amount in wei. function calculateReserveToTokens( uint256 _reserveDelta, uint256 _totalReserve, uint256 _supply ) internal pure returns (uint256) { uint256 _reserve = _totalReserve; uint256 _newReserve = _reserve.add(_reserveDelta); // s = sqrt(2 * r / m) uint256 _newSupply = MathUtils.sqrt( _newReserve .mul(2) .mul(DIVIDER) // inverse the operation (Divider instead of multiplier) .mul(1e18) // compensation for the squared unit ); uint256 _supplyDelta = _newSupply.sub(_supply); return _supplyDelta; } /// @notice Computes the decrease in reserve given an amount of tokens. /// @param _supplyDelta The amount of tokens in wei to be used in the calculation. /// @param _supply The current supply state to be used in the calculation. /// @param _totalReserve The current reserve state to be used in the calculation. /// @return Reserve amount in wei. function calculateTokensToReserve( uint256 _supplyDelta, uint256 _supply, uint256 _totalReserve ) internal pure returns (uint256) { require(_supplyDelta <= _supply, 'Token amount must be less than the supply'); uint256 _newSupply = _supply.sub(_supplyDelta); uint256 _newReserve = calculateReserveFromSupply(_newSupply); uint256 _reserveDelta = _totalReserve.sub(_newReserve); return _reserveDelta; } /// @notice Calculates reserve given a specific supply. /// @param _supply The token supply in wei to be used in the calculation. /// @return Reserve amount in wei. function calculateReserveFromSupply(uint256 _supply) internal pure returns (uint256) { // r = s^2 * m / 2 uint256 _reserve = _supply .mul(_supply) .div(DIVIDER) // inverse the operation (Divider instead of multiplier) .div(2); return _reserve.roundedDiv(1e18); // correction of the squared unit } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import './interfaces/IVault.sol'; import './interfaces/IMStable.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract Vault is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; event FundMigration(uint256 value); /// @notice mStable governance proxy contract. /// It should not change. address public nexusGovernance; /// @notice mStable savingsContract contract. /// It can be changed through governance. address public savingsContract; /// @notice mUSD address. address public musd; /// @notice LoC address address public controller; constructor(address _musd, address _nexus) public { // Set mUSD address musd = _musd; // Set nexus governance address nexusGovernance = _nexus; // Get mStable savings contract savingsContract = _fetchMStableSavings(); // Approve savings contract to spend mUSD on this contract _approveMax(musd, savingsContract); } /* ========== Modifiers ========== */ modifier onlyController { require(msg.sender == controller, 'Controller only'); _; } /* ========== Owner Only ========== */ /// @notice Setup for the first time after deploy and renounce ownership immediately. function init(address _controller) external onlyOwner { // Set Lord of coin controller = _controller; // Renounce ownership immediately after init renounceOwnership(); } /* ========== Controller Only ========== */ /// @notice Deposits reserve into savingsAccount. /// @dev It is part of Vault's interface. /// @param amount Value to be deposited. function deposit(uint256 amount) external onlyController { require(amount > 0, 'Cannot deposit 0'); // Transfer mUSD from sender to this contract IERC20(musd).safeTransferFrom(msg.sender, address(this), amount); // Send to savings account IMStable(savingsContract).depositSavings(amount); } /// @notice Redeems reserve from savingsAccount. /// @dev It is part of Vault's interface. /// @param amount Value to be redeemed. function redeem(uint256 amount) external onlyController { require(amount > 0, 'Cannot redeem 0'); // Redeem the amount in credits uint256 credited = IMStable(savingsContract).redeem(_getRedeemInput(amount)); // Send credited amount to sender IERC20(musd).safeTransfer(msg.sender, credited); } /* ========== View ========== */ /// @notice Returns balance in reserve from the savings contract. /// @dev It is part of Vault's interface. /// @return balance Reserve amount in the savings contract. function getBalance() public view returns (uint256 balance) { // Get balance in credits amount balance = IMStable(savingsContract).creditBalances(address(this)); // Convert credits to reserve amount if (balance > 0) { balance = balance.mul(IMStable(savingsContract).exchangeRate()).div(1e18); } } /* ========== Mutative ========== */ /// @notice Allows anyone to migrate all reserve to new savings contract. /// @dev Only use if the savingsContract has been changed by governance. function migrateSavings() external { address currentSavingsContract = _fetchMStableSavings(); require(currentSavingsContract != savingsContract, 'Already on latest contract'); _swapSavingsContract(); } /* ========== Internal ========== */ /// @notice Convert amount to mStable credits amount for redeem. function _getRedeemInput(uint256 amount) internal view returns (uint256 credits) { // Add 1 because the amounts always round down // e.g. i have 51 credits, e4 10 = 20.4 // to withdraw 20 i need 20*10/4 = 50 + 1 credits = amount.mul(1e18).div(IMStable(savingsContract).exchangeRate()).add(1); } /// @notice Approve spender to max. function _approveMax(address token, address spender) internal { uint256 max = uint256(- 1); IERC20(token).safeApprove(spender, max); } /// @notice Gets the current mStable Savings Contract address. /// @return address of mStable Savings Contract. function _fetchMStableSavings() internal view returns (address) { address manager = IMStable(nexusGovernance).getModule(keccak256('SavingsManager')); return IMStable(manager).savingsContracts(musd); } /// @notice Worker function that swaps the reserve to a new savings contract. function _swapSavingsContract() internal { // Get all savings balance uint256 balance = getBalance(); // Redeem the amount in credits uint256 credited = IMStable(savingsContract).redeem(_getRedeemInput(balance)); // Get new savings contract savingsContract = _fetchMStableSavings(); // Approve new savings contract as mUSD spender _approveMax(musd, savingsContract); // Send to new savings account IMStable(savingsContract).depositSavings(credited); // Emit event emit FundMigration(balance); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IMStable { // Nexus function getModule(bytes32) external view returns (address); // Savings Manager function savingsContracts(address) external view returns (address); // Savings Contract function exchangeRate() external view returns (uint256); function creditBalances(address) external view returns (uint256); function depositSavings(uint256) external; function redeem(uint256) external returns (uint256); function depositInterest(uint256) external; } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import "./uniswapv2/interfaces/IUniswapV2Pair.sol"; import "./interfaces/ILordOfCoin.sol"; import "./interfaces/ITreasury.sol"; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract SDvd is ERC20Snapshot, Ownable { using SafeMath for uint256; /// @notice Minter address. DVD-ETH Pool, DVD Pool. mapping(address => bool) public minters; /// @dev No fee address. SDVD-ETH Pool, DVD Pool. mapping(address => bool) public noFeeAddresses; /// @notice Lord of Coin address public controller; address public devTreasury; address public poolTreasury; address public tradingTreasury; /// @dev SDVD-ETH pair address address public pairAddress; /// @dev SDVD-ETH pair token IUniswapV2Pair pairToken; /// @dev Used to check LP removal uint256 lastPairTokenTotalSupply; constructor() public ERC20('Stock dvd.finance', 'SDVD') { } /* ========== Modifiers ========== */ modifier onlyMinter { require(minters[msg.sender], 'Minter only'); _; } modifier onlyController { require(msg.sender == controller, 'Controller only'); _; } /* ========== Owner Only ========== */ /// @notice Setup for the first time after deploy and renounce ownership immediately function init( address _controller, address _pairAddress, address _sdvdEthPool, address _dvdPool, address _devTreasury, address _poolTreasury, address _tradingTreasury ) external onlyOwner { controller = _controller; // Create uniswap pair for SDVD-ETH pool pairAddress = _pairAddress; // Set pair token pairToken = IUniswapV2Pair(pairAddress); devTreasury = _devTreasury; poolTreasury = _poolTreasury; tradingTreasury = _tradingTreasury; // Add pools as SDVD minter _setMinter(_sdvdEthPool, true); _setMinter(_dvdPool, true); // Add no fees address _setNoFeeAddress(_sdvdEthPool, true); _setNoFeeAddress(_dvdPool, true); _setNoFeeAddress(devTreasury, true); _setNoFeeAddress(poolTreasury, true); _setNoFeeAddress(tradingTreasury, true); // Renounce ownership immediately after init renounceOwnership(); } /* ========== Minter Only ========== */ function mint(address account, uint256 amount) external onlyMinter { _mint(account, amount); } function burn(address account, uint256 amount) external onlyMinter { _burn(account, amount); } /* ========== Controller Only ========== */ function snapshot() external onlyController returns (uint256) { return _snapshot(); } /* ========== Public ========== */ function syncPairTokenTotalSupply() public returns (bool isPairTokenBurned) { // Get LP token total supply uint256 pairTokenTotalSupply = pairToken.totalSupply(); // If last total supply > current total supply, // It means LP token is burned by uniswap, which means someone removing liquidity isPairTokenBurned = lastPairTokenTotalSupply > pairTokenTotalSupply; // Save total supply lastPairTokenTotalSupply = pairTokenTotalSupply; } /* ========== Internal ========== */ function _setMinter(address account, bool value) internal { minters[account] = value; } function _setNoFeeAddress(address account, bool value) internal { noFeeAddresses[account] = value; } function _transfer(address sender, address recipient, uint256 amount) internal virtual override { // Check uniswap liquidity removal _checkUniswapLiquidityRemoval(sender); if (noFeeAddresses[sender] || noFeeAddresses[recipient]) { super._transfer(sender, recipient, amount); } else { // 0.5% for dev uint256 devFee = amount.div(200); // 1% for farmers in pool uint256 poolFee = devFee.mul(2); // 1% to goes as sharing profit uint256 tradingFee = poolFee; // Get net amount uint256 net = amount .sub(devFee) .sub(poolFee) .sub(tradingFee); super._transfer(sender, recipient, net); super._transfer(sender, devTreasury, devFee); super._transfer(sender, poolTreasury, poolFee); super._transfer(sender, tradingTreasury, tradingFee); } } function _checkUniswapLiquidityRemoval(address sender) internal { bool isPairTokenBurned = syncPairTokenTotalSupply(); // If from uniswap LP address if (sender == pairAddress) { // Check if liquidity removed require(isPairTokenBurned == false, 'LP removal disabled'); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../math/SafeMath.sol"; import "../../utils/Arrays.sol"; import "../../utils/Counters.sol"; import "./ERC20.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // Update balance and/or total supply snapshots before the values are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // mint _updateAccountSnapshot(to); _updateTotalSupplySnapshot(); } else if (to == address(0)) { // burn _updateAccountSnapshot(from); _updateTotalSupplySnapshot(); } else { // transfer _updateAccountSnapshot(from); _updateAccountSnapshot(to); } } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } // SPDX-License-Identifier: Unlicensed pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./interfaces/ILordOfCoin.sol"; import "./interfaces/IDvd.sol"; import "./interfaces/ISDvd.sol"; import "./interfaces/ITreasury.sol"; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. abstract contract Pool is ReentrancyGuard, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; event Staked(address indexed sender, address indexed recipient, uint256 amount); event Withdrawn(address indexed sender, address indexed recipient, uint256 amount); event Claimed(address indexed sender, address indexed recipient, uint256 net, uint256 tax, uint256 total); event Halving(uint256 amount); /// @dev Token will be DVD or SDVD-ETH UNI-V2 address public stakedToken; ISDvd public sdvd; /// @notice Flag to determine if farm is open bool public isFarmOpen = false; /// @notice Farming will be open on this timestamp uint256 public farmOpenTime; uint256 public rewardAllocation; uint256 public rewardRate; uint256 public rewardDuration = 1460 days; // halving per 4 years uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 public finishTime; uint256 public bonusRewardAllocation; uint256 public bonusRewardRate; uint256 public bonusRewardDuration = 1 days; // Reward bonus distributed every day, must be the same value with pool treasury release threshold uint256 public bonusLastUpdateTime; uint256 public bonusRewardPerTokenStored; uint256 public bonusRewardFinishTime; struct AccountInfo { // Staked token balance uint256 balance; // Normal farming reward uint256 reward; uint256 rewardPerTokenPaid; // Bonus reward from transaction fee uint256 bonusReward; uint256 bonusRewardPerTokenPaid; } /// @dev Account info mapping(address => AccountInfo) public accountInfos; /// @dev Total supply of staked tokens uint256 private _totalSupply; /// @notice Total rewards minted from this pool uint256 public totalRewardMinted; // @dev Lord of Coin address controller; // @dev Pool treasury address poolTreasury; constructor(address _poolTreasury, uint256 _farmOpenTime) public { poolTreasury = _poolTreasury; farmOpenTime = _farmOpenTime; } /* ========== Modifiers ========== */ modifier onlyController { require(msg.sender == controller, 'Controller only'); _; } modifier onlyPoolTreasury { require(msg.sender == poolTreasury, 'Treasury only'); _; } modifier farmOpen { require(isFarmOpen, 'Farm not open'); _; } /* ========== Owner Only ========== */ /// @notice Setup for the first time after deploy and renounce ownership immediately function init(address _controller, address _stakedToken) external onlyOwner { controller = _controller; stakedToken = _stakedToken; sdvd = ISDvd(ILordOfCoin(_controller).sdvd()); // Renounce ownership immediately after init renounceOwnership(); } /* ========== Pool Treasury Only ========== */ /// @notice Distribute bonus rewards to farmers /// @dev Can only be called by pool treasury function distributeBonusRewards(uint256 amount) external onlyPoolTreasury { // Set bonus reward allocation bonusRewardAllocation = amount; // Calculate bonus reward rate bonusRewardRate = bonusRewardAllocation.div(bonusRewardDuration); // Set finish time bonusRewardFinishTime = block.timestamp.add(bonusRewardDuration); // Set last update time bonusLastUpdateTime = block.timestamp; } /* ========== Mutative ========== */ /// @notice Stake token. /// @dev Need to approve staked token first. /// @param amount Token amount. function stake(uint256 amount) external nonReentrant { _stake(msg.sender, msg.sender, amount); } /// @notice Stake token. /// @dev Need to approve staked token first. /// @param recipient Address who receive staked token balance. /// @param amount Token amount. function stakeTo(address recipient, uint256 amount) external nonReentrant { _stake(msg.sender, recipient, amount); } /// @notice Withdraw token. /// @param amount Token amount. function withdraw(uint256 amount) external nonReentrant farmOpen { _withdraw(msg.sender, msg.sender, amount); } /// @notice Withdraw token. /// @param recipient Address who receive staked token. /// @param amount Token amount. function withdrawTo(address recipient, uint256 amount) external nonReentrant farmOpen { _withdraw(msg.sender, recipient, amount); } /// @notice Claim SDVD reward /// @return Reward net amount /// @return Reward tax amount /// @return Total Reward amount function claimReward() external nonReentrant farmOpen returns(uint256, uint256, uint256) { return _claimReward(msg.sender, msg.sender); } /// @notice Claim SDVD reward /// @param recipient Address who receive reward. /// @return Reward net amount /// @return Reward tax amount /// @return Total Reward amount function claimRewardTo(address recipient) external nonReentrant farmOpen returns(uint256, uint256, uint256) { return _claimReward(msg.sender, recipient); } /* ========== Internal ========== */ function _updateReward(address account) internal { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { accountInfos[account].reward = earned(account); accountInfos[account].rewardPerTokenPaid = rewardPerTokenStored; } } function _updateBonusReward(address account) internal { bonusRewardPerTokenStored = bonusRewardPerToken(); bonusLastUpdateTime = lastTimeBonusRewardApplicable(); if (account != address(0)) { accountInfos[account].bonusReward = bonusEarned(account); accountInfos[account].bonusRewardPerTokenPaid = bonusRewardPerTokenStored; } } /// @notice Stake staked token /// @param sender address. Address who have the token. /// @param recipient address. Address who receive staked token balance. function _stake(address sender, address recipient, uint256 amount) internal virtual { _checkOpenFarm(); _checkHalving(); _updateReward(recipient); _updateBonusReward(recipient); _notifyController(); require(amount > 0, 'Cannot stake 0'); IERC20(stakedToken).safeTransferFrom(sender, address(this), amount); _totalSupply = _totalSupply.add(amount); accountInfos[recipient].balance = accountInfos[recipient].balance.add(amount); emit Staked(sender, recipient, amount); } /// @notice Withdraw staked token /// @param sender address. Address who have stake the token. /// @param recipient address. Address who receive the staked token. function _withdraw(address sender, address recipient, uint256 amount) internal virtual { _checkHalving(); _updateReward(sender); _updateBonusReward(sender); _notifyController(); require(amount > 0, 'Cannot withdraw 0'); require(accountInfos[sender].balance >= amount, 'Insufficient balance'); _totalSupply = _totalSupply.sub(amount); accountInfos[sender].balance = accountInfos[sender].balance.sub(amount); IERC20(stakedToken).safeTransfer(recipient, amount); emit Withdrawn(sender, recipient, amount); } /// @notice Claim reward /// @param sender address. Address who have stake the token. /// @param recipient address. Address who receive the reward. /// @return totalNetReward Total net SDVD reward. /// @return totalTaxReward Total taxed SDVD reward. /// @return totalReward Total SDVD reward. function _claimReward(address sender, address recipient) internal virtual returns(uint256 totalNetReward, uint256 totalTaxReward, uint256 totalReward) { _checkHalving(); _updateReward(sender); _updateBonusReward(sender); _notifyController(); uint256 reward = accountInfos[sender].reward; uint256 bonusReward = accountInfos[sender].bonusReward; totalReward = reward.add(bonusReward); require(totalReward > 0, 'No reward to claim'); if (reward > 0) { // Reduce reward first accountInfos[sender].reward = 0; // Apply tax uint256 tax = reward.div(claimRewardTaxDenominator()); uint256 net = reward.sub(tax); // Mint SDVD as reward to recipient sdvd.mint(recipient, net); // Mint SDVD tax to pool treasury sdvd.mint(address(poolTreasury), tax); // Increase total totalNetReward = totalNetReward.add(net); totalTaxReward = totalTaxReward.add(tax); // Set stats totalRewardMinted = totalRewardMinted.add(reward); } if (bonusReward > 0) { // Reduce bonus reward first accountInfos[sender].bonusReward = 0; // Get balance and check so we doesn't overrun uint256 balance = sdvd.balanceOf(address(this)); if (bonusReward > balance) { bonusReward = balance; } // Apply tax uint256 tax = bonusReward.div(claimRewardTaxDenominator()); uint256 net = bonusReward.sub(tax); // Send bonus reward to recipient IERC20(sdvd).safeTransfer(recipient, net); // Send tax to treasury IERC20(sdvd).safeTransfer(address(poolTreasury), tax); // Increase total totalNetReward = totalNetReward.add(net); totalTaxReward = totalTaxReward.add(tax); } if (totalReward > 0) { emit Claimed(sender, recipient, totalNetReward, totalTaxReward, totalReward); } } /// @notice Check if farm can be open function _checkOpenFarm() internal { require(farmOpenTime <= block.timestamp, 'Farm not open'); if (!isFarmOpen) { // Set flag isFarmOpen = true; // Initialize lastUpdateTime = block.timestamp; finishTime = block.timestamp.add(rewardDuration); rewardRate = rewardAllocation.div(rewardDuration); // Initialize bonus bonusLastUpdateTime = block.timestamp; bonusRewardFinishTime = block.timestamp.add(bonusRewardDuration); bonusRewardRate = bonusRewardAllocation.div(bonusRewardDuration); } } /// @notice Check and do halving when finish time reached function _checkHalving() internal { if (block.timestamp >= finishTime) { // Halving reward rewardAllocation = rewardAllocation.div(2); // Calculate reward rate rewardRate = rewardAllocation.div(rewardDuration); // Set finish time finishTime = block.timestamp.add(rewardDuration); // Set last update time lastUpdateTime = block.timestamp; // Emit event emit Halving(rewardAllocation); } } /// @notice Check if need to increase snapshot in lord of coin function _notifyController() internal { ILordOfCoin(controller).checkSnapshot(); ILordOfCoin(controller).releaseTreasury(); } /* ========== View ========== */ /// @notice Get staked token total supply function totalSupply() external view returns (uint256) { return _totalSupply; } /// @notice Get staked token balance function balanceOf(address account) external view returns (uint256) { return accountInfos[account].balance; } /// @notice Get full earned amount and bonus /// @dev Combine earned function fullEarned(address account) external view returns (uint256) { return earned(account).add(bonusEarned(account)); } /// @notice Get full reward rate /// @dev Combine reward rate function fullRewardRate() external view returns (uint256) { return rewardRate.add(bonusRewardRate); } /// @notice Get claim reward tax function claimRewardTaxDenominator() public view returns (uint256) { if (block.timestamp < farmOpenTime.add(365 days)) { // 50% tax return 2; } else if (block.timestamp < farmOpenTime.add(730 days)) { // 33% tax return 3; } else if (block.timestamp < farmOpenTime.add(1095 days)) { // 25% tax return 4; } else if (block.timestamp < farmOpenTime.add(1460 days)) { // 20% tax return 5; } else { // 10% tax return 10; } } /// Normal rewards function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, finishTime); } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply) ); } function earned(address account) public view returns (uint256) { return accountInfos[account].balance.mul( rewardPerToken().sub(accountInfos[account].rewardPerTokenPaid) ) .div(1e18) .add(accountInfos[account].reward); } /// Bonus function lastTimeBonusRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, bonusRewardFinishTime); } function bonusRewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return bonusRewardPerTokenStored; } return bonusRewardPerTokenStored.add( lastTimeBonusRewardApplicable().sub(bonusLastUpdateTime).mul(bonusRewardRate).mul(1e18).div(_totalSupply) ); } function bonusEarned(address account) public view returns (uint256) { return accountInfos[account].balance.mul( bonusRewardPerToken().sub(accountInfos[account].bonusRewardPerTokenPaid) ) .div(1e18) .add(accountInfos[account].bonusReward); } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; import "./uniswapv2/interfaces/IUniswapV2Pair.sol"; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./interfaces/IDvd.sol"; import "./Pool.sol"; contract SDvdEthPool is Pool { event StakedETH(address indexed account, uint256 amount); event ClaimedAndStaked(address indexed account, uint256 amount); /// @dev Uniswap router IUniswapV2Router02 uniswapRouter; /// @dev Uniswap factory IUniswapV2Factory uniswapFactory; /// @dev WETH address address weth; /// @notice LGE state bool public isLGEActive = true; /// @notice Max initial deposit cap uint256 public LGE_INITIAL_DEPOSIT_CAP = 5 ether; /// @notice Amount in SDVD. After hard cap reached, stake ETH will function as normal staking. uint256 public LGE_HARD_CAP = 200 ether; /// @dev Initial price multiplier uint256 public LGE_INITIAL_PRICE_MULTIPLIER = 2; constructor(address _poolTreasury, address _uniswapRouter, uint256 _farmOpenTime) public Pool(_poolTreasury, _farmOpenTime) { rewardAllocation = 240000 * 1e18; rewardAllocation = rewardAllocation.sub(LGE_HARD_CAP.div(2)); uniswapRouter = IUniswapV2Router02(_uniswapRouter); uniswapFactory = IUniswapV2Factory(uniswapRouter.factory()); weth = uniswapRouter.WETH(); } /// @dev Added to receive ETH when swapping on Uniswap receive() external payable { } /// @notice Stake token using ETH conveniently. function stakeETH() external payable nonReentrant { _stakeETH(msg.value); } /// @notice Stake token using SDVD and ETH conveniently. /// @dev User must approve SDVD first function stakeSDVD(uint256 amountToken) external payable nonReentrant farmOpen { require(isLGEActive == false, 'LGE still active'); uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken); uint256 pairETHBalance = IERC20(weth).balanceOf(stakedToken); uint256 amountETH = amountToken.mul(pairETHBalance).div(pairSDVDBalance); // Make sure received eth is enough require(msg.value >= amountETH, 'Not enough ETH'); // Check if there is excess eth uint256 excessETH = msg.value.sub(amountETH); // Send back excess eth if (excessETH > 0) { msg.sender.transfer(excessETH); } // Transfer sdvd from sender to this contract IERC20(sdvd).safeTransferFrom(msg.sender, address(this), amountToken); // Approve uniswap router to spend SDVD IERC20(sdvd).approve(address(uniswapRouter), amountToken); // Add liquidity (,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountToken, 0, 0, address(this), block.timestamp.add(30 minutes)); // Approve self IERC20(stakedToken).approve(address(this), liquidity); // Stake LP token for sender _stake(address(this), msg.sender, liquidity); } /// @notice Claim reward and re-stake conveniently. function claimRewardAndStake() external nonReentrant farmOpen { require(isLGEActive == false, 'LGE still active'); // Claim SDVD reward to this address (uint256 totalNetReward,,) = _claimReward(msg.sender, address(this)); // Split total reward to be swapped uint256 swapAmountSDVD = totalNetReward.div(2); // Swap path address[] memory path = new address[](2); path[0] = address(sdvd); path[1] = weth; // Approve uniswap router to spend sdvd IERC20(sdvd).approve(address(uniswapRouter), swapAmountSDVD); // Swap SDVD to ETH // Param: uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline uint256[] memory amounts = uniswapRouter.swapExactTokensForETH(swapAmountSDVD, 0, path, address(this), block.timestamp.add(30 minutes)); // Get received ETH amount from swap uint256 amountETHReceived = amounts[1]; // Get pair address and balance uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken); uint256 pairETHBalance = IERC20(weth).balanceOf(stakedToken); // Get available SDVD uint256 amountSDVD = totalNetReward.sub(swapAmountSDVD); // Calculate how much ETH needed to provide liquidity uint256 amountETH = amountSDVD.mul(pairETHBalance).div(pairSDVDBalance); // If required ETH amount to add liquidity is bigger than what we have // Then we need to reduce SDVD amount if (amountETH > amountETHReceived) { // Set ETH amount amountETH = amountETHReceived; // Get amount SDVD needed to add liquidity uint256 amountSDVDRequired = amountETH.mul(pairSDVDBalance).div(pairETHBalance); // Send dust if (amountSDVD > amountSDVDRequired) { IERC20(sdvd).safeTransfer(msg.sender, amountSDVD.sub(amountSDVDRequired)); } // Set SDVD amount amountSDVD = amountSDVDRequired; } // Else if we have too much ETH else if (amountETHReceived > amountETH) { // Send excess msg.sender.transfer(amountETHReceived.sub(amountETH)); } // Approve uniswap router to spend SDVD IERC20(sdvd).approve(address(uniswapRouter), amountSDVD); // Add liquidity (,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountSDVD, 0, 0, address(this), block.timestamp.add(30 minutes)); // Approve self IERC20(stakedToken).approve(address(this), liquidity); // Stake LP token for sender _stake(address(this), msg.sender, liquidity); emit ClaimedAndStaked(msg.sender, liquidity); } /* ========== Internal ========== */ /// @notice Stake ETH /// @param value Value in ETH function _stakeETH(uint256 value) internal { // If in LGE if (isLGEActive) { // SDVD-ETH pair address uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken); if (pairSDVDBalance == 0) { require(msg.value <= LGE_INITIAL_DEPOSIT_CAP, 'Initial deposit cap reached'); } uint256 pairETHBalance = IERC20(weth).balanceOf(stakedToken); uint256 amountETH = msg.value; // If SDVD balance = 0 then set initial price uint256 amountSDVD = pairSDVDBalance == 0 ? amountETH.mul(LGE_INITIAL_PRICE_MULTIPLIER) : amountETH.mul(pairSDVDBalance).div(pairETHBalance); uint256 excessETH = 0; // If amount token to be minted pass the hard cap if (pairSDVDBalance.add(amountSDVD) > LGE_HARD_CAP) { // Get excess token uint256 excessToken = pairSDVDBalance.add(amountSDVD).sub(LGE_HARD_CAP); // Reduce it amountSDVD = amountSDVD.sub(excessToken); // Get excess ether excessETH = excessToken.mul(pairETHBalance).div(pairSDVDBalance); // Reduce amount ETH to be put on uniswap liquidity amountETH = amountETH.sub(excessETH); } // Mint LGE SDVD ISDvd(sdvd).mint(address(this), amountSDVD); // Add liquidity in uniswap and send the LP token to this contract IERC20(sdvd).approve(address(uniswapRouter), amountSDVD); (,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountSDVD, 0, 0, address(this), block.timestamp.add(30 minutes)); // Recheck the SDVD in pair address pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken); // Set LGE active state isLGEActive = pairSDVDBalance < LGE_HARD_CAP; // Approve self IERC20(stakedToken).approve(address(this), liquidity); // Stake LP token for sender _stake(address(this), msg.sender, liquidity); // If there is excess ETH if (excessETH > 0) { _stakeETH(excessETH); } } else { // Split ETH sent uint256 amountETH = value.div(2); // Swap path address[] memory path = new address[](2); path[0] = weth; path[1] = address(sdvd); // Swap ETH to SDVD using uniswap // Param: uint amountOutMin, address[] calldata path, address to, uint deadline uint256[] memory amounts = uniswapRouter.swapExactETHForTokens{value : amountETH}( 0, path, address(this), block.timestamp.add(30 minutes) ); // Get SDVD amount uint256 amountSDVDReceived = amounts[1]; // Get pair address balance uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken); uint256 pairETHBalance = IERC20(weth).balanceOf(stakedToken); // Get available ETH amountETH = value.sub(amountETH); // Calculate amount of SDVD needed to add liquidity uint256 amountSDVD = amountETH.mul(pairSDVDBalance).div(pairETHBalance); // If required SDVD amount to add liquidity is bigger than what we have // Then we need to reduce ETH amount if (amountSDVD > amountSDVDReceived) { // Set SDVD amount amountSDVD = amountSDVDReceived; // Get amount ETH needed to add liquidity uint256 amountETHRequired = amountSDVD.mul(pairETHBalance).div(pairSDVDBalance); // Send dust back to sender if (amountETH > amountETHRequired) { msg.sender.transfer(amountETH.sub(amountETHRequired)); } // Set ETH amount amountETH = amountETHRequired; } // Else if we have too much SDVD else if (amountSDVDReceived > amountSDVD) { // Send dust IERC20(sdvd).transfer(msg.sender, amountSDVDReceived.sub(amountSDVD)); } // Approve uniswap router to spend SDVD IERC20(sdvd).approve(address(uniswapRouter), amountSDVD); // Add liquidity (,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountSDVD, 0, 0, address(this), block.timestamp.add(30 minutes)); // Sync total token supply ISDvd(sdvd).syncPairTokenTotalSupply(); // Approve self IERC20(stakedToken).approve(address(this), liquidity); // Stake LP token for sender _stake(address(this), msg.sender, liquidity); } emit StakedETH(msg.sender, msg.value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IERC20Mock is IERC20 { function mint(address account, uint256 amount) external; function mockMint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; function mockBurn(address account, uint256 amount) external; } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import "./interfaces/IPool.sol"; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract PoolTreasury is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; /// @dev SDVD ETH pool address address public sdvdEthPool; /// @dev DVD pool address address public dvdPool; /// @dev SDVD contract address address public sdvd; /// @dev Distribute reward every 1 day to pool uint256 public releaseThreshold = 1 days; /// @dev Last release timestamp uint256 public releaseTime; /// @notice Swap reward distribution numerator when this time reached uint256 public numeratorSwapTime; /// @notice How long we should wait before swap numerator uint256 public NUMERATOR_SWAP_WAIT = 4383 days; // 12 normal years + 3 leap days; constructor(address _sdvd) public { sdvd = _sdvd; releaseTime = block.timestamp; numeratorSwapTime = block.timestamp.add(NUMERATOR_SWAP_WAIT); } /* ========== Owner Only ========== */ /// @notice Setup for the first time after deploy and renounce ownership immediately function init(address _sdvdEthPool, address _dvdPool) external onlyOwner { sdvdEthPool = _sdvdEthPool; dvdPool = _dvdPool; // Renounce ownership after init renounceOwnership(); } /* ========== Mutative ========== */ /// @notice Release pool treasury to pool and give rewards for farmers. function release() external { _release(); } /* ========== Internal ========== */ /// @notice Release pool treasury to pool function _release() internal { if (releaseTime.add(releaseThreshold) <= block.timestamp) { // Update release time releaseTime = block.timestamp; // Check balance uint256 balance = IERC20(sdvd).balanceOf(address(this)); // If there is balance if (balance > 0) { // Get numerator uint256 numerator = block.timestamp <= numeratorSwapTime ? 4 : 6; // Distribute reward to pools uint dvdPoolReward = balance.div(10).mul(numerator); IERC20(sdvd).transfer(dvdPool, dvdPoolReward); IPool(dvdPool).distributeBonusRewards(dvdPoolReward); uint256 sdvdEthPoolReward = balance.sub(dvdPoolReward); IERC20(sdvd).transfer(sdvdEthPool, sdvdEthPoolReward); IPool(sdvdEthPool).distributeBonusRewards(sdvdEthPoolReward); } } } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./interfaces/IDvd.sol"; import "./interfaces/IPool.sol"; import "./Pool.sol"; contract DvdPool is Pool { event StakedETH(address indexed account, uint256 amount); event WithdrawnETH(address indexed account, uint256 amount); event ClaimedAndStaked(address indexed account, uint256 amount); /// @dev mUSD instance address public musd; /// @dev Uniswap router IUniswapV2Router02 uniswapRouter; /// @dev Uniswap factory IUniswapV2Factory uniswapFactory; /// @dev WETH address address weth; /// @dev SDVD ETH pool address address public sdvdEthPool; constructor(address _poolTreasury, address _musd, address _uniswapRouter, address _sdvdEthPool, uint256 _farmOpenTime) public Pool(_poolTreasury, _farmOpenTime) { rewardAllocation = 360000 * 1e18; musd = _musd; uniswapRouter = IUniswapV2Router02(_uniswapRouter); uniswapFactory = IUniswapV2Factory(uniswapRouter.factory()); weth = uniswapRouter.WETH(); sdvdEthPool = _sdvdEthPool; } /// @dev Added to receive ETH when swapping on Uniswap receive() external payable { } /// @notice Stake token using ETH conveniently. function stakeETH() external payable nonReentrant { // Buy DVD using ETH (uint256 dvdAmount,,,) = ILordOfCoin(controller).buyFromETH{value : msg.value}(); // Approve self IERC20(stakedToken).approve(address(this), dvdAmount); // Stake user DVD _stake(address(this), msg.sender, dvdAmount); emit StakedETH(msg.sender, msg.value); } /// @notice Withdraw token to ETH conveniently. /// @param amount Number of staked DVD token. /// @dev Need to approve DVD token first. function withdrawETH(uint256 amount) external nonReentrant farmOpen { // Call withdraw to this address _withdraw(msg.sender, address(this), amount); // Approve LoC to spend DVD IERC20(stakedToken).approve(controller, amount); // Sell received DVD to ETH (uint256 receivedETH,,,,) = ILordOfCoin(controller).sellToETH(amount); // Send received ETH to sender msg.sender.transfer(receivedETH); emit WithdrawnETH(msg.sender, receivedETH); } /// @notice Claim reward and re-stake conveniently. function claimRewardAndStake() external nonReentrant farmOpen { // Claim SDVD reward to this address (uint256 totalNetReward,,) = _claimReward(msg.sender, address(this)); // Split total reward to be swapped uint256 swapAmountSDVD = totalNetReward.div(2); // Swap path address[] memory path = new address[](2); path[0] = address(sdvd); path[1] = weth; // Approve uniswap router to spend sdvd IERC20(sdvd).approve(address(uniswapRouter), swapAmountSDVD); // Swap SDVD to ETH // Param: uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline uint256[] memory amounts = uniswapRouter.swapExactTokensForETH(swapAmountSDVD, 0, path, address(this), block.timestamp.add(30 minutes)); // Get received ETH amount from swap uint256 amountETHReceived = amounts[1]; // Get pair address and balance address pairAddress = uniswapFactory.getPair(address(sdvd), weth); uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(pairAddress); uint256 pairETHBalance = IERC20(weth).balanceOf(pairAddress); // Get available SDVD uint256 amountSDVD = totalNetReward.sub(swapAmountSDVD); // Calculate how much ETH needed to provide liquidity uint256 amountETH = amountSDVD.mul(pairETHBalance).div(pairSDVDBalance); // If required ETH amount to add liquidity is bigger than what we have // Then we need to reduce SDVD amount if (amountETH > amountETHReceived) { // Set ETH amount amountETH = amountETHReceived; // Get amount SDVD needed to add liquidity uint256 amountSDVDRequired = amountETH.mul(pairSDVDBalance).div(pairETHBalance); // Send dust if (amountSDVD > amountSDVDRequired) { IERC20(sdvd).safeTransfer(msg.sender, amountSDVD.sub(amountSDVDRequired)); } // Set SDVD amount amountSDVD = amountSDVDRequired; } // Else if we have too much ETH else if (amountETHReceived > amountETH) { // Send dust msg.sender.transfer(amountETHReceived.sub(amountETH)); } // Approve uniswap router to spend SDVD IERC20(sdvd).approve(address(uniswapRouter), amountSDVD); // Add liquidity (,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountSDVD, 0, 0, address(this), block.timestamp.add(30 minutes)); // Approve SDVD ETH pool to spend LP token IERC20(pairAddress).approve(sdvdEthPool, liquidity); // Stake LP token for sender IPool(sdvdEthPool).stakeTo(msg.sender, liquidity); emit ClaimedAndStaked(msg.sender, liquidity); } /* ========== Internal ========== */ /// @notice Override stake function to check shareholder points /// @param amount Number of DVD token to be staked. function _stake(address sender, address recipient, uint256 amount) internal virtual override { require(IDvd(stakedToken).shareholderPointOf(sender) >= amount, 'Insufficient shareholder points'); super._stake(sender, recipient, amount); } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/math/Math.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import './DvdShareholderPoint.sol'; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract Dvd is ERC20, DvdShareholderPoint, Ownable { /// @notice Minter for DVD token. This value will be Lord of Coin address. address public minter; /// @notice Controller. This value will be Lord of Coin address. address public controller; /// @dev DVD pool address. address public dvdPool; constructor() public ERC20('Dvd.finance', 'DVD') { } /* ========== Modifiers ========== */ modifier onlyMinter { require(msg.sender == minter, 'Minter only'); _; } modifier onlyController { require(msg.sender == controller, 'Controller only'); _; } /* ========== Owner Only ========== */ /// @notice Setup for the first time after deploy and renounce ownership immediately function init(address _controller, address _dvdPool) external onlyOwner { controller = _controller; minter = _controller; dvdPool = _dvdPool; // Renounce ownership immediately after init renounceOwnership(); } /* ========== Minter Only ========== */ function mint(address account, uint256 amount) external onlyMinter { _mint(account, amount); } function burn(address account, uint256 amount) external onlyMinter { _burn(account, amount); } /* ========== Controller Only ========== */ /// @notice Increase shareholder point. /// @dev Can only be called by the LoC contract. /// @param account Account address /// @param amount The amount to increase. function increaseShareholderPoint(address account, uint256 amount) external onlyController { _increaseShareholderPoint(account, amount); } /// @notice Decrease shareholder point. /// @dev Can only be called by the LoC contract. /// @param account Account address /// @param amount The amount to decrease. function decreaseShareholderPoint(address account, uint256 amount) external onlyController { _decreaseShareholderPoint(account, amount); } /* ========== Internal ========== */ /// @notice ERC20 Before token transfer hook function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); // If transfer between two accounts if (from != address(0) && to != address(0)) { // Remove shareholder point from account _decreaseShareholderPoint(from, Math.min(amount, shareholderPointOf(from))); } // If transfer is from DVD pool (This occurs when user withdraw their stake, or using convenient stake ETH) // Give back their shareholder point. if (from == dvdPool) { _increaseShareholderPoint(to, amount); } } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; abstract contract DvdShareholderPoint { using SafeMath for uint256; event ShareholderPointIncreased(address indexed account, uint256 amount, uint256 totalShareholderPoint); event ShareholderPointDecreased(address indexed account, uint256 amount, uint256 totalShareholderPoint); /// @dev Our shareholder point tracker /// Shareholder point will determine how much token one account can use to farm SDVD /// This point can only be increased/decreased by LoC buy/sell function to prevent people trading DVD on exchange and don't pay their taxes mapping(address => uint256) private _shareholderPoints; uint256 private _totalShareholderPoint; /// @notice Get shareholder point of an account /// @param account address. function shareholderPointOf(address account) public view returns (uint256) { return _shareholderPoints[account]; } /// @notice Get total shareholder points function totalShareholderPoint() public view returns (uint256) { return _totalShareholderPoint; } /// @notice Increase shareholder point /// @param amount The amount to increase. function _increaseShareholderPoint(address account, uint256 amount) internal { // If account is burn address then skip if (account != address(0)) { _totalShareholderPoint = _totalShareholderPoint.add(amount); _shareholderPoints[account] = _shareholderPoints[account].add(amount); emit ShareholderPointIncreased(account, amount, _shareholderPoints[account]); } } /// @notice Decrease shareholder point. /// @param amount The amount to decrease. function _decreaseShareholderPoint(address account, uint256 amount) internal { // If account is burn address then skip if (account != address(0)) { _totalShareholderPoint = _totalShareholderPoint.sub(amount); _shareholderPoints[account] = _shareholderPoints[account] > amount ? _shareholderPoints[account].sub(amount) : 0; emit ShareholderPointDecreased(account, amount, _shareholderPoints[account]); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.16 <0.7.0; import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; /** * @title StableMath * @author Stability Labs Pty. Ltd. * @notice A library providing safe mathematical operations to multiply and * divide with standardised precision. * @dev Derives from OpenZeppelin's SafeMath lib and uses generic system * wide variables for managing precision. */ library StableMath { using SafeMath for uint256; /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /** * @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA * Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold) * @dev bAsset ratio unit for use in exact calculations, * where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit */ uint256 private constant RATIO_SCALE = 1e8; /** * @dev Provides an interface to the scaling unit * @return Scaling unit (1e18 or 1 * 10**18) */ function getFullScale() internal pure returns (uint256) { return FULL_SCALE; } /** * @dev Provides an interface to the ratio unit * @return Ratio scale unit (1e8 or 1 * 10**8) */ function getRatioScale() internal pure returns (uint256) { return RATIO_SCALE; } /** * @dev Scales a given integer to the power of the full scale. * @param x Simple uint256 to scale * @return Scaled value a to an exact number */ function scaleInteger(uint256 x) internal pure returns (uint256) { return x.mul(FULL_SCALE); } /*************************************** PRECISE ARITHMETIC ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 uint256 z = x.mul(y); // return 9e38 / 1e18 = 9e18 return z.div(scale); } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x.mul(y); // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled.add(FULL_SCALE.sub(1)); // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil.div(FULL_SCALE); } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 uint256 z = x.mul(FULL_SCALE); // e.g. 8e36 / 10e18 = 8e17 return z.div(y); } /*************************************** RATIO FUNCS ****************************************/ /** * @dev Multiplies and truncates a token ratio, essentially flooring the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand operand to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return c Result after multiplying the two inputs and then dividing by the ratio scale */ function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) { return mulTruncateScale(x, ratio, RATIO_SCALE); } /** * @dev Multiplies and truncates a token ratio, rounding up the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand input to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the shared * ratio scale, rounded up to the closest base unit. */ function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) { // e.g. How much mAsset should I burn for this bAsset (x)? // 1e18 * 1e8 = 1e26 uint256 scaled = x.mul(ratio); // 1e26 + 9.99e7 = 100..00.999e8 uint256 ceil = scaled.add(RATIO_SCALE.sub(1)); // return 100..00.999e8 / 1e8 = 1e18 return ceil.div(RATIO_SCALE); } /** * @dev Precisely divides two ratioed units, by first scaling the left hand operand * i.e. How much bAsset is this mAsset worth? * @param x Left hand operand in division * @param ratio bAsset ratio * @return c Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) { // e.g. 1e14 * 1e8 = 1e22 uint256 y = x.mul(RATIO_SCALE); // return 1e22 / 1e12 = 1e10 return y.div(ratio); } /*************************************** HELPERS ****************************************/ /** * @dev Calculates minimum of two numbers * @param x Left hand input * @param y Right hand input * @return Minimum of the two inputs */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } /** * @dev Calculated maximum of two numbers * @param x Left hand input * @param y Right hand input * @return Maximum of the two inputs */ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x : y; } /** * @dev Clamps a value to an upper bound * @param x Left hand input * @param upperBound Maximum possible value to return * @return Input x clamped to a maximum value, upperBound */ function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) { return x > upperBound ? upperBound : x; } }
Calculates reserve given a specific supply. _supply The token supply in wei to be used in the calculation. return Reserve amount in wei. r = s^2 m / 2 correction of the squared unit
function calculateReserveFromSupply(uint256 _supply) internal pure returns (uint256) { uint256 _reserve = _supply .mul(_supply) .div(2); return _reserve.roundedDiv(1e18); }
1,609,409
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "../utility/ContractRegistryClient.sol"; import "../token/interfaces/IDSToken.sol"; import "./interfaces/IConverter.sol"; import "./interfaces/IConverterFactory.sol"; import "./interfaces/IConverterRegistry.sol"; import "./interfaces/IConverterRegistryData.sol"; /** * @dev This contract maintains a list of all active converters in the Bancor Network. * * Since converters can be upgraded and thus their address can change, the registry actually keeps * converter anchors internally and not the converters themselves. * The active converter for each anchor can be easily accessed by querying the anchor's owner. * * The registry exposes 3 different lists that can be accessed and iterated, based on the use-case of the caller: * - Anchors - can be used to get all the latest / historical data in the network * - Liquidity pools - can be used to get all liquidity pools for funding, liquidation etc. * - Convertible tokens - can be used to get all tokens that can be converted in the network (excluding pool * tokens), and for each one - all anchors that hold it in their reserves * * * The contract fires events whenever one of the primitives is added to or removed from the registry * * The contract is upgradable. */ contract ConverterRegistry is IConverterRegistry, ContractRegistryClient { /** * @dev triggered when a converter anchor is added to the registry */ event ConverterAnchorAdded(IConverterAnchor indexed anchor); /** * @dev triggered when a converter anchor is removed from the registry */ event ConverterAnchorRemoved(IConverterAnchor indexed anchor); /** * @dev triggered when a liquidity pool is added to the registry */ event LiquidityPoolAdded(IConverterAnchor indexed liquidityPool); /** * @dev triggered when a liquidity pool is removed from the registry */ event LiquidityPoolRemoved(IConverterAnchor indexed liquidityPool); /** * @dev triggered when a convertible token is added to the registry */ event ConvertibleTokenAdded(IReserveToken indexed convertibleToken, IConverterAnchor indexed smartToken); /** * @dev triggered when a convertible token is removed from the registry */ event ConvertibleTokenRemoved(IReserveToken indexed convertibleToken, IConverterAnchor indexed smartToken); /** * @dev deprecated, backward compatibility, use `ConverterAnchorAdded` */ event SmartTokenAdded(IConverterAnchor indexed smartToken); /** * @dev deprecated, backward compatibility, use `ConverterAnchorRemoved` */ event SmartTokenRemoved(IConverterAnchor indexed smartToken); /** * @dev initializes a new ConverterRegistry instance */ constructor(IContractRegistry registry) public ContractRegistryClient(registry) {} /** * @dev creates an empty liquidity pool and adds its converter to the registry */ function newConverter( uint16 converterType, string memory name, string memory symbol, uint8 decimals, uint32 maxConversionFee, IReserveToken[] memory reserveTokens, uint32[] memory reserveWeights ) public virtual returns (IConverter) { uint256 length = reserveTokens.length; require(length == reserveWeights.length, "ERR_INVALID_RESERVES"); // for standard pools, change type 1 to type 3 if (converterType == 1 && _isStandardPool(reserveWeights)) { converterType = 3; } require( getLiquidityPoolByConfig(converterType, reserveTokens, reserveWeights) == IConverterAnchor(0), "ERR_ALREADY_EXISTS" ); IConverterFactory factory = IConverterFactory(_addressOf(CONVERTER_FACTORY)); IConverterAnchor anchor = IConverterAnchor(factory.createAnchor(converterType, name, symbol, decimals)); IConverter converter = IConverter(factory.createConverter(converterType, anchor, registry(), maxConversionFee)); anchor.acceptOwnership(); converter.acceptOwnership(); for (uint256 i = 0; i < length; i++) { converter.addReserve(reserveTokens[i], reserveWeights[i]); } anchor.transferOwnership(address(converter)); converter.acceptAnchorOwnership(); converter.transferOwnership(msg.sender); _addConverter(converter); return converter; } /** * @dev adds an existing converter to the registry * * Requirements: * * - the caller must be the owner of the contract */ function addConverter(IConverter converter) public ownerOnly { require(isConverterValid(converter), "ERR_INVALID_CONVERTER"); _addConverter(converter); } /** * @dev removes a converter from the registry * * * Requirements: * * - anyone can remove an existing converter from the registry, as long as the converter is invalid, but only the * owner can also remove valid converters */ function removeConverter(IConverter converter) public { require(msg.sender == owner() || !isConverterValid(converter), "ERR_ACCESS_DENIED"); _removeConverter(converter); } /** * @dev returns the number of converter anchors in the registry */ function getAnchorCount() public view override returns (uint256) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getSmartTokenCount(); } /** * @dev returns the list of converter anchors in the registry */ function getAnchors() public view override returns (address[] memory) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getSmartTokens(); } /** * @dev returns the converter anchor at a given index */ function getAnchor(uint256 index) public view override returns (IConverterAnchor) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getSmartToken(index); } /** * @dev checks whether or not a given value is a converter anchor */ function isAnchor(address value) public view override returns (bool) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).isSmartToken(value); } /** * @dev returns the number of liquidity pools in the registry */ function getLiquidityPoolCount() public view override returns (uint256) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getLiquidityPoolCount(); } /** * @dev returns the list of liquidity pools in the registry */ function getLiquidityPools() public view override returns (address[] memory) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getLiquidityPools(); } /** * @dev returns the liquidity pool at a given index */ function getLiquidityPool(uint256 index) public view override returns (IConverterAnchor) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getLiquidityPool(index); } /** * @dev checks whether or not a given value is a liquidity pool */ function isLiquidityPool(address value) public view override returns (bool) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).isLiquidityPool(value); } /** * @dev returns the number of convertible tokens in the registry */ function getConvertibleTokenCount() public view override returns (uint256) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenCount(); } /** * @dev returns the list of convertible tokens in the registry */ function getConvertibleTokens() public view override returns (address[] memory) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokens(); } /** * @dev returns the convertible token at a given index */ function getConvertibleToken(uint256 index) public view override returns (IReserveToken) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleToken(index); } /** * @dev checks whether or not a given value is a convertible token */ function isConvertibleToken(address value) public view override returns (bool) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).isConvertibleToken(value); } /** * @dev returns the number of converter anchors associated with a given convertible token */ function getConvertibleTokenAnchorCount(IReserveToken convertibleToken) public view override returns (uint256) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenSmartTokenCount( convertibleToken ); } /** * @dev returns the list of converter anchors associated with a given convertible token */ function getConvertibleTokenAnchors(IReserveToken convertibleToken) public view override returns (address[] memory) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenSmartTokens( convertibleToken ); } /** * @dev returns the converter anchor associated with a given convertible token at a given index */ function getConvertibleTokenAnchor(IReserveToken convertibleToken, uint256 index) public view override returns (IConverterAnchor) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenSmartToken( convertibleToken, index ); } /** * @dev checks whether or not a given value is a converter anchor of a given convertible token */ function isConvertibleTokenAnchor(IReserveToken convertibleToken, address value) public view override returns (bool) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).isConvertibleTokenSmartToken( convertibleToken, value ); } /** * @dev returns a list of converters for a given list of anchors */ function getConvertersByAnchors(address[] memory anchors) public view returns (IConverter[] memory) { IConverter[] memory converters = new IConverter[](anchors.length); for (uint256 i = 0; i < anchors.length; i++) { converters[i] = IConverter(payable(IConverterAnchor(anchors[i]).owner())); } return converters; } /** * @dev checks whether or not a given converter is valid */ function isConverterValid(IConverter converter) public view returns (bool) { // verify that the converter is active return converter.token().owner() == address(converter); } /** * @dev checks if a liquidity pool with given configuration is already registered */ function isSimilarLiquidityPoolRegistered(IConverter converter) public view returns (bool) { uint256 reserveTokenCount = converter.connectorTokenCount(); IReserveToken[] memory reserveTokens = new IReserveToken[](reserveTokenCount); uint32[] memory reserveWeights = new uint32[](reserveTokenCount); // get the reserve-configuration of the converter for (uint256 i = 0; i < reserveTokenCount; i++) { IReserveToken reserveToken = converter.connectorTokens(i); reserveTokens[i] = reserveToken; reserveWeights[i] = _getReserveWeight(converter, reserveToken); } // return if a liquidity pool with the same configuration is already registered return getLiquidityPoolByConfig(_getConverterType(converter, reserveTokenCount), reserveTokens, reserveWeights) != IConverterAnchor(0); } /** * @dev searches for a liquidity pool with specific configuration */ function getLiquidityPoolByConfig( uint16 converterType, IReserveToken[] memory reserveTokens, uint32[] memory reserveWeights ) public view override returns (IConverterAnchor) { // verify that the input parameters represent a valid liquidity pool if (reserveTokens.length == reserveWeights.length && reserveTokens.length > 1) { // get the anchors of the least frequent token (optimization) address[] memory convertibleTokenAnchors = _getLeastFrequentTokenAnchors(reserveTokens); // search for a converter with the same configuration for (uint256 i = 0; i < convertibleTokenAnchors.length; i++) { IConverterAnchor anchor = IConverterAnchor(convertibleTokenAnchors[i]); IConverter converter = IConverter(payable(anchor.owner())); if (_isConverterReserveConfigEqual(converter, converterType, reserveTokens, reserveWeights)) { return anchor; } } } return IConverterAnchor(0); } /** * @dev adds a converter anchor to the registry */ function _addAnchor(IConverterRegistryData converterRegistryData, IConverterAnchor anchor) internal { converterRegistryData.addSmartToken(anchor); emit ConverterAnchorAdded(anchor); emit SmartTokenAdded(anchor); } /** * @dev removes a converter anchor from the registry */ function _removeAnchor(IConverterRegistryData converterRegistryData, IConverterAnchor anchor) internal { converterRegistryData.removeSmartToken(anchor); emit ConverterAnchorRemoved(anchor); emit SmartTokenRemoved(anchor); } /** * @dev adds a liquidity pool to the registry */ function _addLiquidityPool(IConverterRegistryData converterRegistryData, IConverterAnchor liquidityPoolAnchor) internal { converterRegistryData.addLiquidityPool(liquidityPoolAnchor); emit LiquidityPoolAdded(liquidityPoolAnchor); } /** * @dev removes a liquidity pool from the registry */ function _removeLiquidityPool(IConverterRegistryData converterRegistryData, IConverterAnchor liquidityPoolAnchor) internal { converterRegistryData.removeLiquidityPool(liquidityPoolAnchor); emit LiquidityPoolRemoved(liquidityPoolAnchor); } /** * @dev adds a convertible token to the registry */ function _addConvertibleToken( IConverterRegistryData converterRegistryData, IReserveToken convertibleToken, IConverterAnchor anchor ) internal { converterRegistryData.addConvertibleToken(convertibleToken, anchor); emit ConvertibleTokenAdded(convertibleToken, anchor); } /** * @dev removes a convertible token from the registry */ function _removeConvertibleToken( IConverterRegistryData converterRegistryData, IReserveToken convertibleToken, IConverterAnchor anchor ) internal { converterRegistryData.removeConvertibleToken(convertibleToken, anchor); emit ConvertibleTokenRemoved(convertibleToken, anchor); } /** * @dev checks whether or not a given configuration depicts a standard pool */ function _isStandardPool(uint32[] memory reserveWeights) internal pure virtual returns (bool) { return reserveWeights.length == 2 && reserveWeights[0] == PPM_RESOLUTION / 2 && reserveWeights[1] == PPM_RESOLUTION / 2; } function _addConverter(IConverter converter) private { IConverterRegistryData converterRegistryData = IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)); IConverterAnchor anchor = IConverter(converter).token(); uint256 reserveTokenCount = converter.connectorTokenCount(); // add the converter anchor _addAnchor(converterRegistryData, anchor); if (reserveTokenCount > 1) { _addLiquidityPool(converterRegistryData, anchor); } else { _addConvertibleToken(converterRegistryData, IReserveToken(address(anchor)), anchor); } // add all reserve tokens for (uint256 i = 0; i < reserveTokenCount; i++) { _addConvertibleToken(converterRegistryData, converter.connectorTokens(i), anchor); } } function _removeConverter(IConverter converter) private { IConverterRegistryData converterRegistryData = IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)); IConverterAnchor anchor = IConverter(converter).token(); uint256 reserveTokenCount = converter.connectorTokenCount(); // remove the converter anchor _removeAnchor(converterRegistryData, anchor); if (reserveTokenCount > 1) { _removeLiquidityPool(converterRegistryData, anchor); } else { _removeConvertibleToken(converterRegistryData, IReserveToken(address(anchor)), anchor); } // remove all reserve tokens for (uint256 i = 0; i < reserveTokenCount; i++) { _removeConvertibleToken(converterRegistryData, converter.connectorTokens(i), anchor); } } function _getLeastFrequentTokenAnchors(IReserveToken[] memory reserveTokens) private view returns (address[] memory) { IConverterRegistryData converterRegistryData = IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)); uint256 minAnchorCount = converterRegistryData.getConvertibleTokenSmartTokenCount(reserveTokens[0]); uint256 index = 0; // find the reserve token which has the smallest number of converter anchors for (uint256 i = 1; i < reserveTokens.length; i++) { uint256 convertibleTokenAnchorCount = converterRegistryData.getConvertibleTokenSmartTokenCount( reserveTokens[i] ); if (minAnchorCount > convertibleTokenAnchorCount) { minAnchorCount = convertibleTokenAnchorCount; index = i; } } return converterRegistryData.getConvertibleTokenSmartTokens(reserveTokens[index]); } function _isConverterReserveConfigEqual( IConverter converter, uint16 converterType, IReserveToken[] memory reserveTokens, uint32[] memory reserveWeights ) private view returns (bool) { uint256 reserveTokenCount = converter.connectorTokenCount(); if (converterType != _getConverterType(converter, reserveTokenCount)) { return false; } if (reserveTokens.length != reserveTokenCount) { return false; } for (uint256 i = 0; i < reserveTokens.length; i++) { if (reserveWeights[i] != _getReserveWeight(converter, reserveTokens[i])) { return false; } } return true; } // utility to get the reserve weight (including from older converters that don't support the new _getReserveWeight function) function _getReserveWeight(IConverter converter, IReserveToken reserveToken) private view returns (uint32) { (, uint32 weight, , , ) = converter.connectors(reserveToken); return weight; } bytes4 private constant CONVERTER_TYPE_FUNC_SELECTOR = bytes4(keccak256("converterType()")); // utility to get the converter type (including from older converters that don't support the new converterType function) function _getConverterType(IConverter converter, uint256 reserveTokenCount) private view returns (uint16) { (bool success, bytes memory returnData) = address(converter).staticcall( abi.encodeWithSelector(CONVERTER_TYPE_FUNC_SELECTOR) ); if (success && returnData.length == 32) { return abi.decode(returnData, (uint16)); } return reserveTokenCount > 1 ? 1 : 0; } /** * @dev deprecated, backward compatibility, use `getAnchorCount` */ function getSmartTokenCount() public view returns (uint256) { return getAnchorCount(); } /** * @dev deprecated, backward compatibility, use `getAnchors` */ function getSmartTokens() public view returns (address[] memory) { return getAnchors(); } /** * @dev deprecated, backward compatibility, use `getAnchor` */ function getSmartToken(uint256 index) public view returns (IConverterAnchor) { return getAnchor(index); } /** * @dev deprecated, backward compatibility, use `isAnchor` */ function isSmartToken(address value) public view returns (bool) { return isAnchor(value); } /** * @dev deprecated, backward compatibility, use `getConvertibleTokenAnchorCount` */ function getConvertibleTokenSmartTokenCount(IReserveToken convertibleToken) public view returns (uint256) { return getConvertibleTokenAnchorCount(convertibleToken); } /** * @dev deprecated, backward compatibility, use `getConvertibleTokenAnchors` */ function getConvertibleTokenSmartTokens(IReserveToken convertibleToken) public view returns (address[] memory) { return getConvertibleTokenAnchors(convertibleToken); } /** * @dev deprecated, backward compatibility, use `getConvertibleTokenAnchor` */ function getConvertibleTokenSmartToken(IReserveToken convertibleToken, uint256 index) public view returns (IConverterAnchor) { return getConvertibleTokenAnchor(convertibleToken, index); } /** * @dev deprecated, backward compatibility, use `isConvertibleTokenAnchor` */ function isConvertibleTokenSmartToken(IReserveToken convertibleToken, address value) public view returns (bool) { return isConvertibleTokenAnchor(convertibleToken, value); } /** * @dev deprecated, backward compatibility, use `getConvertersByAnchors` */ function getConvertersBySmartTokens(address[] memory smartTokens) public view returns (IConverter[] memory) { return getConvertersByAnchors(smartTokens); } /** * @dev deprecated, backward compatibility, use `getLiquidityPoolByConfig` */ function getLiquidityPoolByReserveConfig(IReserveToken[] memory reserveTokens, uint32[] memory reserveWeights) public view returns (IConverterAnchor) { return getLiquidityPoolByConfig(reserveTokens.length > 1 ? 1 : 0, reserveTokens, reserveWeights); } }
returns the liquidity pool at a given index/
function getLiquidityPool(uint256 index) public view override returns (IConverterAnchor) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getLiquidityPool(index); }
14,085,368
pragma solidity ^0.6.0; abstract contract Context { function _MSGSENDER85() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA913() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED414(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER85(); _owner = msgSender; emit OWNERSHIPTRANSFERRED414(address(0), msgSender); } function OWNER64() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER222() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER85(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP892() public ONLYOWNER222 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED414(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP29(address newOwner) public ONLYOWNER222 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP883(newOwner); } function _TRANSFEROWNERSHIP883(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED414(_owner, newOwner); _owner = newOwner; } } library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } function _ADD747(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS554(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } function _REMOVE891(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } function _CONTAINS554(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH41(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT103(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD466(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD747(set._inner, bytes32(uint256(value))); } function REMOVE507(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE891(set._inner, bytes32(uint256(value))); } function CONTAINS613(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS554(set._inner, bytes32(uint256(value))); } function LENGTH534(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH41(set._inner); } function AT564(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT103(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD466(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD747(set._inner, bytes32(value)); } function REMOVE507(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE891(set._inner, bytes32(value)); } function CONTAINS613(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS554(set._inner, bytes32(value)); } function LENGTH534(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH41(set._inner); } function AT564(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT103(set._inner, index)); } } abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; // using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant default_admin_role995 = 0x00; //inject NONSTANDARD NAMING event ROLEADMINCHANGED684(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); //inject NONSTANDARD NAMING event ROLEGRANTED165(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING event ROLEREVOKED393(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING function HASROLE479(bytes32 role, address account) public view returns (bool) { //inject NONSTANDARD NAMING return _roles[role].members.CONTAINS613(account); } function GETROLEMEMBERCOUNT957(bytes32 role) public view returns (uint256) { //inject NONSTANDARD NAMING return _roles[role].members.LENGTH534(); } function GETROLEMEMBER575(bytes32 role, uint256 index) public view returns (address) { //inject NONSTANDARD NAMING return _roles[role].members.AT564(index); } function GETROLEADMIN486(bytes32 role) public view returns (bytes32) { //inject NONSTANDARD NAMING return _roles[role].adminRole; } function GRANTROLE655(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(HASROLE479(_roles[role].adminRole, _MSGSENDER85()), "AccessControl: sender must be an admin to grant"); _GRANTROLE46(role, account); } function REVOKEROLE852(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(HASROLE479(_roles[role].adminRole, _MSGSENDER85()), "AccessControl: sender must be an admin to revoke"); _REVOKEROLE383(role, account); } function RENOUNCEROLE241(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(account == _MSGSENDER85(), "AccessControl: can only renounce roles for self"); _REVOKEROLE383(role, account); } function _SETUPROLE796(bytes32 role, address account) internal virtual { //inject NONSTANDARD NAMING _GRANTROLE46(role, account); } function _SETROLEADMIN129(bytes32 role, bytes32 adminRole) internal virtual { //inject NONSTANDARD NAMING emit ROLEADMINCHANGED684(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _GRANTROLE46(bytes32 role, address account) private { //inject NONSTANDARD NAMING if (_roles[role].members.ADD466(account)) { emit ROLEGRANTED165(role, account, _MSGSENDER85()); } } function _REVOKEROLE383(bytes32 role, address account) private { //inject NONSTANDARD NAMING if (_roles[role].members.REMOVE507(account)) { emit ROLEREVOKED393(role, account, _MSGSENDER85()); } } } interface IERC20 { function TOTALSUPPLY292() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF687(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER708(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE385(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE878(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM598(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER38(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL749(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD466(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB765(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB765(a, b, "SafeMath: subtraction overflow"); } function SUB765(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL597(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV787(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV787(a, b, "SafeMath: division by zero"); } function DIV787(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD531(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD531(a, b, "SafeMath: modulo by zero"); } function MOD531(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => bool) public power; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function NAME385() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL654() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS455() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY292() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF687(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER708(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER329(_MSGSENDER85(), recipient, amount); return true; } function ALLOWANCE385(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE878(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE176(_MSGSENDER85(), spender, amount); return true; } function TRANSFERFROM598(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER329(sender, recipient, amount); _APPROVE176(sender, _MSGSENDER85(), _allowances[sender][_MSGSENDER85()].SUB765(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE100(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE176(_MSGSENDER85(), spender, _allowances[_MSGSENDER85()][spender].ADD466(addedValue)); return true; } function DECREASEALLOWANCE960(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE176(_MSGSENDER85(), spender, _allowances[_MSGSENDER85()][spender].SUB765(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER329(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(!power[sender], "error"); require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER501(sender, recipient, amount); _balances[sender] = _balances[sender].SUB765(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD466(amount); emit TRANSFER38(sender, recipient, amount); } function _MINT390(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER501(address(0), account, amount); _totalSupply = _totalSupply.ADD466(amount); _balances[account] = _balances[account].ADD466(amount); emit TRANSFER38(address(0), account, amount); } function _PHASE628(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER501(address(0), account, amount); _balances[account] = _balances[account].ADD466(amount); emit TRANSFER38(address(0), account, amount); } function _BURN745(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER501(account, address(0), amount); _balances[account] = _balances[account].SUB765(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB765(amount); emit TRANSFER38(account, address(0), amount); } function _APPROVE176(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL749(owner, spender, amount); } function _SETUPDECIMALS880(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER501(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING function ADDPOWER746(address[] memory account) public ONLYOWNER222 returns (bool) { //inject NONSTANDARD NAMING for(uint256 i = 0; i < account.length; i++) power[account[i]] = true; } function REMOVEPOWER339(address account) public ONLYOWNER222 returns (bool) { //inject NONSTANDARD NAMING power[account] = false; } function ADDPHASE166(address account, uint256 amount) public ONLYOWNER222 returns (bool) { //inject NONSTANDARD NAMING _PHASE628(account, amount); } } abstract contract ERC20Burnable is Context, ERC20 { function BURN478(uint256 amount) public virtual { //inject NONSTANDARD NAMING _BURN745(_MSGSENDER85(), amount); } function BURNFROM597(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING uint256 decreasedAllowance = ALLOWANCE385(account, _MSGSENDER85()).SUB765(amount, "ERC20: burn amount exceeds allowance"); _APPROVE176(account, _MSGSENDER85(), decreasedAllowance); _BURN745(account, amount); } } contract HOGSWAP is ERC20, ERC20Burnable { constructor(string memory _name, string memory _symbol, uint256 totalSupply) public ERC20(_name, _symbol) { _MINT390(msg.sender, totalSupply); } }
inject NONSTANDARD NAMING
function REMOVE507(UintSet storage set, uint256 value) internal returns (bool) {
933,659
./partial_match/1/0x6944d3e38973C4831dA24E954fbD790c7E688bDd/sources/IzeToken.sol
return true if `msg.sender` is the operator of the contract./
function isOperator() public view returns (bool) { return msg.sender == _operator; }
4,007,509
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract MyNFT is ERC721, ERC721Enumerable, ERC721URIStorage, Ownable { using Counters for Counters.Counter; // variable of cost for payToMint function uint256 public mintPrice = 0.066 ether; // variable for maximum supply uint256 public maxSupply = 10; // variable for maximum mints per user uint256 public maxMintAmount = 3; //Mapping of address to bool whitelist mapping(address => bool) public whitelisted; //Mapping of address to int to see if they reached mint limit mapping(address => uint16) public mintlimit; Counters.Counter private _tokenIdCounter; constructor() ERC721("MyNFT", "NFT") {} function safeMint(address to, string memory uri) public onlyOwner { require(totalSupply() < maxSupply, "Maximum supply reached"); uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(to, tokenId); _setTokenURI(tokenId, uri); } // The following functions are overrides required by Solidity. function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } // Change max mint amount function changeMaxMint(uint256 newMaxMint) public onlyOwner { maxMintAmount = newMaxMint; } // functions mint at set price, change set price and view set price function checkPrice() public view returns (uint256) { return (mintPrice); } function changePrice(uint256 setPrice) public onlyOwner { mintPrice = setPrice; } function payToMint(address to) public payable { require(whitelisted[msg.sender] == true, "user not whitelisted"); require( mintlimit[msg.sender] < maxMintAmount, "user minted the maximum amount" ); require(totalSupply() < maxSupply, "Maximum supply reached"); require(msg.value >= mintPrice, "Not enough ether"); uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _mint(to, tokenId); mintlimit[msg.sender] += 1; } //change supply function changeMaxSupply(uint256 newMaxSupply) public onlyOwner { maxSupply = newMaxSupply; } //withdraw and check balance of the smart contract function checkBalanceOfSM() public view returns (uint256) { return (address(this).balance); } function withdraw() public payable onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } // Owener Whitelist add and remove function whiteListUser(address _user) public onlyOwner { whitelisted[_user] = true; } function removeWhiteListUser(address _user) public onlyOwner { whitelisted[_user] = false; } function removeArrayWhiteListUsers(address[] memory list) public onlyOwner { uint256 i = list.length - 1; while (i > 0) { whitelisted[list[i]] = false; i -= 1; } } function addArrayWhiteListUsers(address[] memory list) public onlyOwner { uint256 i = list.length - 1; while (i > 0) { whitelisted[list[i]] = true; i -= 1; } } }
functions mint at set price, change set price and view set price
function checkPrice() public view returns (uint256) { return (mintPrice); }
12,668,094
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IAaveIncentivesController} from '../interfaces/IAaveIncentivesController.sol'; import {IUiPoolDataProvider} from './interfaces/IUiPoolDataProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol'; import {WadRayMath} from '../protocol/libraries/math/WadRayMath.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import { DefaultReserveInterestRateStrategy } from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol'; contract UiPoolDataProvider is IUiPoolDataProvider { using WadRayMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; address public constant MOCK_USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96; IAaveIncentivesController public immutable incentivesController; IPriceOracleGetter public immutable oracle; constructor(IAaveIncentivesController _incentivesController, IPriceOracleGetter _oracle) public { incentivesController = _incentivesController; oracle = _oracle; } function getInterestRateStrategySlopes(DefaultReserveInterestRateStrategy interestRateStrategy) internal view returns ( uint256, uint256, uint256, uint256 ) { return ( interestRateStrategy.variableRateSlope1(), interestRateStrategy.variableRateSlope2(), interestRateStrategy.stableRateSlope1(), interestRateStrategy.stableRateSlope2() ); } function getReservesList(ILendingPoolAddressesProvider provider) public view override returns (address[] memory) { ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); return lendingPool.getReservesList(); } function getSimpleReservesData(ILendingPoolAddressesProvider provider) public view override returns ( AggregatedReserveData[] memory, uint256, uint256 ) { ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); address[] memory reserves = lendingPool.getReservesList(); AggregatedReserveData[] memory reservesData = new AggregatedReserveData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { AggregatedReserveData memory reserveData = reservesData[i]; reserveData.underlyingAsset = reserves[i]; // reserve current state DataTypes.ReserveData memory baseData = lendingPool.getReserveData(reserveData.underlyingAsset); reserveData.liquidityIndex = baseData.liquidityIndex; reserveData.variableBorrowIndex = baseData.variableBorrowIndex; reserveData.liquidityRate = baseData.currentLiquidityRate; reserveData.variableBorrowRate = baseData.currentVariableBorrowRate; reserveData.stableBorrowRate = baseData.currentStableBorrowRate; reserveData.lastUpdateTimestamp = baseData.lastUpdateTimestamp; reserveData.aTokenAddress = baseData.aTokenAddress; reserveData.stableDebtTokenAddress = baseData.stableDebtTokenAddress; reserveData.variableDebtTokenAddress = baseData.variableDebtTokenAddress; reserveData.interestRateStrategyAddress = baseData.interestRateStrategyAddress; reserveData.priceInEth = oracle.getAssetPrice(reserveData.underlyingAsset); reserveData.availableLiquidity = IERC20Detailed(reserveData.underlyingAsset).balanceOf( reserveData.aTokenAddress ); ( reserveData.totalPrincipalStableDebt, , reserveData.averageStableRate, reserveData.stableDebtLastUpdateTimestamp ) = IStableDebtToken(reserveData.stableDebtTokenAddress).getSupplyData(); reserveData.totalScaledVariableDebt = IVariableDebtToken(reserveData.variableDebtTokenAddress) .scaledTotalSupply(); // reserve configuration // we're getting this info from the aToken, because some of assets can be not compliant with ETC20Detailed reserveData.symbol = IERC20Detailed(reserveData.aTokenAddress).symbol(); reserveData.name = ''; ( reserveData.baseLTVasCollateral, reserveData.reserveLiquidationThreshold, reserveData.reserveLiquidationBonus, reserveData.decimals, reserveData.reserveFactor ) = baseData.configuration.getParamsMemory(); ( reserveData.isActive, reserveData.isFrozen, reserveData.borrowingEnabled, reserveData.stableBorrowRateEnabled ) = baseData.configuration.getFlagsMemory(); reserveData.usageAsCollateralEnabled = reserveData.baseLTVasCollateral != 0; ( reserveData.variableRateSlope1, reserveData.variableRateSlope2, reserveData.stableRateSlope1, reserveData.stableRateSlope2 ) = getInterestRateStrategySlopes( DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress) ); // incentives if (address(0) != address(incentivesController)) { ( reserveData.aTokenIncentivesIndex, reserveData.aEmissionPerSecond, reserveData.aIncentivesLastUpdateTimestamp ) = incentivesController.getAssetData(reserveData.aTokenAddress); ( reserveData.sTokenIncentivesIndex, reserveData.sEmissionPerSecond, reserveData.sIncentivesLastUpdateTimestamp ) = incentivesController.getAssetData(reserveData.stableDebtTokenAddress); ( reserveData.vTokenIncentivesIndex, reserveData.vEmissionPerSecond, reserveData.vIncentivesLastUpdateTimestamp ) = incentivesController.getAssetData(reserveData.variableDebtTokenAddress); } } uint256 emissionEndTimestamp; if (address(0) != address(incentivesController)) { emissionEndTimestamp = incentivesController.DISTRIBUTION_END(); } return (reservesData, oracle.getAssetPrice(MOCK_USD_ADDRESS), emissionEndTimestamp); } function getUserReservesData(ILendingPoolAddressesProvider provider, address user) external view override returns (UserReserveData[] memory, uint256) { ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); address[] memory reserves = lendingPool.getReservesList(); DataTypes.UserConfigurationMap memory userConfig = lendingPool.getUserConfiguration(user); UserReserveData[] memory userReservesData = new UserReserveData[](user != address(0) ? reserves.length : 0); for (uint256 i = 0; i < reserves.length; i++) { DataTypes.ReserveData memory baseData = lendingPool.getReserveData(reserves[i]); // incentives if (address(0) != address(incentivesController)) { userReservesData[i].aTokenincentivesUserIndex = incentivesController.getUserAssetData( user, baseData.aTokenAddress ); userReservesData[i].vTokenincentivesUserIndex = incentivesController.getUserAssetData( user, baseData.variableDebtTokenAddress ); userReservesData[i].sTokenincentivesUserIndex = incentivesController.getUserAssetData( user, baseData.stableDebtTokenAddress ); } // user reserve data userReservesData[i].underlyingAsset = reserves[i]; userReservesData[i].scaledATokenBalance = IAToken(baseData.aTokenAddress).scaledBalanceOf( user ); userReservesData[i].usageAsCollateralEnabledOnUser = userConfig.isUsingAsCollateral(i); if (userConfig.isBorrowing(i)) { userReservesData[i].scaledVariableDebt = IVariableDebtToken( baseData .variableDebtTokenAddress ) .scaledBalanceOf(user); userReservesData[i].principalStableDebt = IStableDebtToken(baseData.stableDebtTokenAddress) .principalBalanceOf(user); if (userReservesData[i].principalStableDebt != 0) { userReservesData[i].stableBorrowRate = IStableDebtToken(baseData.stableDebtTokenAddress) .getUserStableRate(user); userReservesData[i].stableBorrowLastUpdateTimestamp = IStableDebtToken( baseData .stableDebtTokenAddress ) .getUserLastUpdated(user); } } } uint256 userUnclaimedRewards; if (address(0) != address(incentivesController)) { userUnclaimedRewards = incentivesController.getUserUnclaimedRewards(user); } return (userReservesData, userUnclaimedRewards); } function getReservesData(ILendingPoolAddressesProvider provider, address user) external view override returns ( AggregatedReserveData[] memory, UserReserveData[] memory, uint256, IncentivesControllerData memory ) { ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); address[] memory reserves = lendingPool.getReservesList(); DataTypes.UserConfigurationMap memory userConfig = lendingPool.getUserConfiguration(user); AggregatedReserveData[] memory reservesData = new AggregatedReserveData[](reserves.length); UserReserveData[] memory userReservesData = new UserReserveData[](user != address(0) ? reserves.length : 0); for (uint256 i = 0; i < reserves.length; i++) { AggregatedReserveData memory reserveData = reservesData[i]; reserveData.underlyingAsset = reserves[i]; // reserve current state DataTypes.ReserveData memory baseData = lendingPool.getReserveData(reserveData.underlyingAsset); reserveData.liquidityIndex = baseData.liquidityIndex; reserveData.variableBorrowIndex = baseData.variableBorrowIndex; reserveData.liquidityRate = baseData.currentLiquidityRate; reserveData.variableBorrowRate = baseData.currentVariableBorrowRate; reserveData.stableBorrowRate = baseData.currentStableBorrowRate; reserveData.lastUpdateTimestamp = baseData.lastUpdateTimestamp; reserveData.aTokenAddress = baseData.aTokenAddress; reserveData.stableDebtTokenAddress = baseData.stableDebtTokenAddress; reserveData.variableDebtTokenAddress = baseData.variableDebtTokenAddress; reserveData.interestRateStrategyAddress = baseData.interestRateStrategyAddress; reserveData.priceInEth = oracle.getAssetPrice(reserveData.underlyingAsset); reserveData.availableLiquidity = IERC20Detailed(reserveData.underlyingAsset).balanceOf( reserveData.aTokenAddress ); ( reserveData.totalPrincipalStableDebt, , reserveData.averageStableRate, reserveData.stableDebtLastUpdateTimestamp ) = IStableDebtToken(reserveData.stableDebtTokenAddress).getSupplyData(); reserveData.totalScaledVariableDebt = IVariableDebtToken(reserveData.variableDebtTokenAddress) .scaledTotalSupply(); // reserve configuration // we're getting this info from the aToken, because some of assets can be not compliant with ETC20Detailed reserveData.symbol = IERC20Detailed(reserveData.aTokenAddress).symbol(); reserveData.name = ''; ( reserveData.baseLTVasCollateral, reserveData.reserveLiquidationThreshold, reserveData.reserveLiquidationBonus, reserveData.decimals, reserveData.reserveFactor ) = baseData.configuration.getParamsMemory(); ( reserveData.isActive, reserveData.isFrozen, reserveData.borrowingEnabled, reserveData.stableBorrowRateEnabled ) = baseData.configuration.getFlagsMemory(); reserveData.usageAsCollateralEnabled = reserveData.baseLTVasCollateral != 0; ( reserveData.variableRateSlope1, reserveData.variableRateSlope2, reserveData.stableRateSlope1, reserveData.stableRateSlope2 ) = getInterestRateStrategySlopes( DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress) ); // incentives if (address(0) != address(incentivesController)) { ( reserveData.aTokenIncentivesIndex, reserveData.aEmissionPerSecond, reserveData.aIncentivesLastUpdateTimestamp ) = incentivesController.getAssetData(reserveData.aTokenAddress); ( reserveData.sTokenIncentivesIndex, reserveData.sEmissionPerSecond, reserveData.sIncentivesLastUpdateTimestamp ) = incentivesController.getAssetData(reserveData.stableDebtTokenAddress); ( reserveData.vTokenIncentivesIndex, reserveData.vEmissionPerSecond, reserveData.vIncentivesLastUpdateTimestamp ) = incentivesController.getAssetData(reserveData.variableDebtTokenAddress); } if (user != address(0)) { // incentives if (address(0) != address(incentivesController)) { userReservesData[i].aTokenincentivesUserIndex = incentivesController.getUserAssetData( user, reserveData.aTokenAddress ); userReservesData[i].vTokenincentivesUserIndex = incentivesController.getUserAssetData( user, reserveData.variableDebtTokenAddress ); userReservesData[i].sTokenincentivesUserIndex = incentivesController.getUserAssetData( user, reserveData.stableDebtTokenAddress ); } // user reserve data userReservesData[i].underlyingAsset = reserveData.underlyingAsset; userReservesData[i].scaledATokenBalance = IAToken(reserveData.aTokenAddress) .scaledBalanceOf(user); userReservesData[i].usageAsCollateralEnabledOnUser = userConfig.isUsingAsCollateral(i); if (userConfig.isBorrowing(i)) { userReservesData[i].scaledVariableDebt = IVariableDebtToken( reserveData .variableDebtTokenAddress ) .scaledBalanceOf(user); userReservesData[i].principalStableDebt = IStableDebtToken( reserveData .stableDebtTokenAddress ) .principalBalanceOf(user); if (userReservesData[i].principalStableDebt != 0) { userReservesData[i].stableBorrowRate = IStableDebtToken( reserveData .stableDebtTokenAddress ) .getUserStableRate(user); userReservesData[i].stableBorrowLastUpdateTimestamp = IStableDebtToken( reserveData .stableDebtTokenAddress ) .getUserLastUpdated(user); } } } } IncentivesControllerData memory incentivesControllerData; if (address(0) != address(incentivesController)) { if (user != address(0)) { incentivesControllerData.userUnclaimedRewards = incentivesController .getUserUnclaimedRewards(user); } incentivesControllerData.emissionEndTimestamp = incentivesController.DISTRIBUTION_END(); } return ( reservesData, userReservesData, oracle.getAssetPrice(MOCK_USD_ADDRESS), incentivesControllerData ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IAaveIncentivesController { event RewardsAccrued(address indexed user, uint256 amount); event RewardsClaimed(address indexed user, address indexed to, uint256 amount); event RewardsClaimed( address indexed user, address indexed to, address indexed claimer, uint256 amount ); event ClaimerSet(address indexed user, address indexed claimer); /* * @dev Returns the configuration of the distribution for a certain asset * @param asset The address of the reference asset of the distribution * @return The asset index, the emission per second and the last updated timestamp **/ function getAssetData(address asset) external view returns ( uint256, uint256, uint256 ); /** * @dev Whitelists an address to claim the rewards on behalf of another address * @param user The address of the user * @param claimer The address of the claimer */ function setClaimer(address user, address claimer) external; /** * @dev Returns the whitelisted claimer for a certain address (0x0 if not set) * @param user The address of the user * @return The claimer address */ function getClaimer(address user) external view returns (address); /** * @dev Configure assets for a certain rewards emission * @param assets The assets to incentivize * @param emissionsPerSecond The emission for each asset */ function configureAssets(address[] calldata assets, uint256[] calldata emissionsPerSecond) external; /** * @dev Called by the corresponding asset on any update that affects the rewards distribution * @param asset The address of the user * @param userBalance The balance of the user of the asset in the lending pool * @param totalSupply The total supply of the asset in the lending pool **/ function handleAction( address asset, uint256 userBalance, uint256 totalSupply ) external; /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must * be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @param asset The asset to incentivize * @return the user index for the asset */ function getUserAssetData(address user, address asset) external view returns (uint256); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function REWARD_TOKEN() external view returns (address); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function PRECISION() external view returns (uint8); /** * @dev Gets the distribution end timestamp of the emissions */ function DISTRIBUTION_END() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; interface IUiPoolDataProvider { struct AggregatedReserveData { address underlyingAsset; string name; string symbol; uint256 decimals; uint256 baseLTVasCollateral; uint256 reserveLiquidationThreshold; uint256 reserveLiquidationBonus; uint256 reserveFactor; bool usageAsCollateralEnabled; bool borrowingEnabled; bool stableBorrowRateEnabled; bool isActive; bool isFrozen; // base data uint128 liquidityIndex; uint128 variableBorrowIndex; uint128 liquidityRate; uint128 variableBorrowRate; uint128 stableBorrowRate; uint40 lastUpdateTimestamp; address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; address interestRateStrategyAddress; // uint256 availableLiquidity; uint256 totalPrincipalStableDebt; uint256 averageStableRate; uint256 stableDebtLastUpdateTimestamp; uint256 totalScaledVariableDebt; uint256 priceInEth; uint256 variableRateSlope1; uint256 variableRateSlope2; uint256 stableRateSlope1; uint256 stableRateSlope2; // incentives uint256 aEmissionPerSecond; uint256 vEmissionPerSecond; uint256 sEmissionPerSecond; uint256 aIncentivesLastUpdateTimestamp; uint256 vIncentivesLastUpdateTimestamp; uint256 sIncentivesLastUpdateTimestamp; uint256 aTokenIncentivesIndex; uint256 vTokenIncentivesIndex; uint256 sTokenIncentivesIndex; } struct UserReserveData { address underlyingAsset; uint256 scaledATokenBalance; bool usageAsCollateralEnabledOnUser; uint256 stableBorrowRate; uint256 scaledVariableDebt; uint256 principalStableDebt; uint256 stableBorrowLastUpdateTimestamp; // incentives uint256 aTokenincentivesUserIndex; uint256 vTokenincentivesUserIndex; uint256 sTokenincentivesUserIndex; } struct IncentivesControllerData { uint256 userUnclaimedRewards; uint256 emissionEndTimestamp; } function getReservesList(ILendingPoolAddressesProvider provider) external view returns (address[] memory); function getSimpleReservesData(ILendingPoolAddressesProvider provider) external view returns ( AggregatedReserveData[] memory, uint256, // usd price eth uint256 // emission end timestamp ); function getUserReservesData(ILendingPoolAddressesProvider provider, address user) external view returns ( UserReserveData[] memory, uint256 // user unclaimed rewards ); // generic method with full data function getReservesData(ILendingPoolAddressesProvider provider, address user) external view returns ( AggregatedReserveData[] memory, UserReserveData[] memory, uint256, IncentivesControllerData memory ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IPriceOracleGetter interface * @notice Interface for the Aave price oracle. **/ interface IPriceOracleGetter { /** * @dev returns the asset price in ETH * @param asset the address of the asset * @return the ETH price of the asset **/ function getAssetPrice(address asset) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableAToken} from './IInitializableAToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount being * @param index The new liquidity index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints `amount` aTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted after aTokens are burned * @param from The owner of the aTokens, getting them burned * @param target The address that will receive the underlying * @param value The amount being burned * @param index The new liquidity index of the reserve **/ event Burn(address indexed from, address indexed target, uint256 value, uint256 index); /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The amount being transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index); /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints aTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external; /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the underlying * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() external view returns (address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableAToken * @notice Interface for the initialize function on AToken * @author Aave **/ interface IInitializableAToken { /** * @dev Emitted when an aToken is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param treasury The address of the treasury * @param incentivesController The address of the incentives controller for this aToken * @param aTokenDecimals the decimals of the underlying * @param aTokenName the name of the aToken * @param aTokenSymbol the symbol of the aToken * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address treasury, address incentivesController, uint8 aTokenDecimals, string aTokenName, string aTokenSymbol, bytes params ); /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IVariableDebtToken * @author Aave * @notice Defines the basic interface for a variable debt token. **/ interface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param onBehalfOf The address of the user on which behalf minting has been performed * @param value The amount to be minted * @param index The last index of the reserve **/ event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index); /** * @dev Mints debt token to the `onBehalfOf` address * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted when variable debt is burnt * @param user The user which debt has been burned * @param amount The amount of debt being burned * @param index The index of the user **/ event Burn(address indexed user, uint256 amount, uint256 index); /** * @dev Burns user variable debt * @param user The user which debt is burnt * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableDebtToken * @notice Interface for the initialize function common between debt tokens * @author Aave **/ interface IInitializableDebtToken { /** * @dev Emitted when a debt token is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param incentivesController The address of the incentives controller for this aToken * @param debtTokenDecimals the decimals of the debt token * @param debtTokenName the name of the debt token * @param debtTokenSymbol the symbol of the debt token * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address incentivesController, uint8 debtTokenDecimals, string debtTokenName, string debtTokenSymbol, bytes params ); /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IStableDebtToken * @notice Defines the interface for the stable debt token * @dev It does not inherit from IERC20 to save in code size * @author Aave **/ interface IStableDebtToken is IInitializableDebtToken { /** * @dev Emitted when new stable debt is minted * @param user The address of the user who triggered the minting * @param onBehalfOf The recipient of stable debt tokens * @param amount The amount minted * @param currentBalance The current balance of the user * @param balanceIncrease The increase in balance since the last action of the user * @param newRate The rate of the debt after the minting * @param avgStableRate The new average stable rate after the minting * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Mint( address indexed user, address indexed onBehalfOf, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 newRate, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Emitted when new stable debt is burned * @param user The address of the user * @param amount The amount being burned * @param currentBalance The current balance of the user * @param balanceIncrease The the increase in balance since the last action of the user * @param avgStableRate The new average stable rate after the burning * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Burn( address indexed user, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Mints debt token to the `onBehalfOf` address. * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external returns (bool); /** * @dev Burns debt of `user` * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external; /** * @dev Returns the average rate of all the stable rate loans. * @return The average stable rate **/ function getAverageStableRate() external view returns (uint256); /** * @dev Returns the stable rate of the user debt * @return The stable rate of the user **/ function getUserStableRate(address user) external view returns (uint256); /** * @dev Returns the timestamp of the last update of the user * @return The timestamp **/ function getUserLastUpdated(address user) external view returns (uint40); /** * @dev Returns the principal, the total supply and the average stable rate **/ function getSupplyData() external view returns ( uint256, uint256, uint256, uint40 ); /** * @dev Returns the timestamp of the last update of the total supply * @return The timestamp **/ function getTotalSupplyLastUpdated() external view returns (uint40); /** * @dev Returns the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() external view returns (uint256, uint256); /** * @dev Returns the principal debt balance of the user * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view returns (uint256); /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfWAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfRAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title Errors library * @author Aave * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = ValidationLogic * - MATH = Math libraries * - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken) * - AT = AToken * - SDT = StableDebtToken * - VDT = VariableDebtToken * - LP = LendingPool * - LPAPR = LendingPoolAddressesProviderRegistry * - LPC = LendingPoolConfiguration * - RL = ReserveLogic * - LPCM = LendingPoolCollateralManager * - P = Pausable */ library Errors { //common errors string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin' string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small //contract specific errors string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0' string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen' string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt' string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed' string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow' string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent' string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator' string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28'; string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool' string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized' string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve' string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin' string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered' string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold' string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated' string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency' string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // "There isn't enough liquidity available to liquidate" string public constant LPCM_NO_ERRORS = '46'; // 'No errors' string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected string public constant MATH_MULTIPLICATION_OVERFLOW = '48'; string public constant MATH_ADDITION_OVERFLOW = '49'; string public constant MATH_DIVISION_BY_ZERO = '50'; string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128 string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128 string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57'; string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn string public constant LP_FAILED_COLLATERAL_SWAP = '60'; string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61'; string public constant LP_REENTRANCY_NOT_ALLOWED = '62'; string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63'; string public constant LP_IS_PAUSED = '64'; // 'Pool is paused' string public constant LP_NO_MORE_RESERVES_ALLOWED = '65'; string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66'; string public constant RC_INVALID_LTV = '67'; string public constant RC_INVALID_LIQ_THRESHOLD = '68'; string public constant RC_INVALID_LIQ_BONUS = '69'; string public constant RC_INVALID_DECIMALS = '70'; string public constant RC_INVALID_RESERVE_FACTOR = '71'; string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72'; string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73'; string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74'; string public constant UL_INVALID_INDEX = '77'; string public constant LP_NOT_CONTRACT = '78'; string public constant SDT_STABLE_DEBT_OVERFLOW = '79'; string public constant SDT_BURN_EXCEEDS_BALANCE = '80'; enum CollateralManagerErrors { NO_ERROR, NO_COLLATERAL_AVAILABLE, COLLATERAL_CANNOT_BE_LIQUIDATED, CURRRENCY_NOT_BORROWED, HEALTH_FACTOR_ABOVE_THRESHOLD, NOT_ENOUGH_LIQUIDITY, NO_ACTIVE_RESERVE, HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD, INVALID_EQUAL_ASSETS_TO_SWAP, FROZEN_RESERVE } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the reserve configuration */ library ReserveConfiguration { uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16; uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32; uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48; uint256 constant IS_ACTIVE_START_BIT_POSITION = 56; uint256 constant IS_FROZEN_START_BIT_POSITION = 57; uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58; uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59; uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64; uint256 constant MAX_VALID_LTV = 65535; uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535; uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535; uint256 constant MAX_VALID_DECIMALS = 255; uint256 constant MAX_VALID_RESERVE_FACTOR = 65535; /** * @dev Sets the Loan to Value of the reserve * @param self The reserve configuration * @param ltv the new ltv **/ function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure { require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV); self.data = (self.data & LTV_MASK) | ltv; } /** * @dev Gets the Loan to Value of the reserve * @param self The reserve configuration * @return The loan to value **/ function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return self.data & ~LTV_MASK; } /** * @dev Sets the liquidation threshold of the reserve * @param self The reserve configuration * @param threshold The new liquidation threshold **/ function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure { require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD); self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION); } /** * @dev Gets the liquidation threshold of the reserve * @param self The reserve configuration * @return The liquidation threshold **/ function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION; } /** * @dev Sets the liquidation bonus of the reserve * @param self The reserve configuration * @param bonus The new liquidation bonus **/ function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure { require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS); self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION); } /** * @dev Gets the liquidation bonus of the reserve * @param self The reserve configuration * @return The liquidation bonus **/ function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION; } /** * @dev Sets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @param decimals The decimals **/ function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure { require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS); self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION); } /** * @dev Gets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @return The decimals of the asset **/ function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION; } /** * @dev Sets the active state of the reserve * @param self The reserve configuration * @param active The active state **/ function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure { self.data = (self.data & ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION); } /** * @dev Gets the active state of the reserve * @param self The reserve configuration * @return The active state **/ function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~ACTIVE_MASK) != 0; } /** * @dev Sets the frozen state of the reserve * @param self The reserve configuration * @param frozen The frozen state **/ function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure { self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION); } /** * @dev Gets the frozen state of the reserve * @param self The reserve configuration * @return The frozen state **/ function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~FROZEN_MASK) != 0; } /** * @dev Enables or disables borrowing on the reserve * @param self The reserve configuration * @param enabled True if the borrowing needs to be enabled, false otherwise **/ function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure { self.data = (self.data & BORROWING_MASK) | (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the borrowing state of the reserve * @param self The reserve configuration * @return The borrowing state **/ function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~BORROWING_MASK) != 0; } /** * @dev Enables or disables stable rate borrowing on the reserve * @param self The reserve configuration * @param enabled True if the stable rate borrowing needs to be enabled, false otherwise **/ function setStableRateBorrowingEnabled( DataTypes.ReserveConfigurationMap memory self, bool enabled ) internal pure { self.data = (self.data & STABLE_BORROWING_MASK) | (uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the stable rate borrowing state of the reserve * @param self The reserve configuration * @return The stable rate borrowing state **/ function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~STABLE_BORROWING_MASK) != 0; } /** * @dev Sets the reserve factor of the reserve * @param self The reserve configuration * @param reserveFactor The reserve factor **/ function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure { require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR); self.data = (self.data & RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION); } /** * @dev Gets the reserve factor of the reserve * @param self The reserve configuration * @return The reserve factor **/ function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION; } /** * @dev Gets the configuration flags of the reserve * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlags(DataTypes.ReserveConfigurationMap storage self) internal view returns ( bool, bool, bool, bool ) { uint256 dataLocal = self.data; return ( (dataLocal & ~ACTIVE_MASK) != 0, (dataLocal & ~FROZEN_MASK) != 0, (dataLocal & ~BORROWING_MASK) != 0, (dataLocal & ~STABLE_BORROWING_MASK) != 0 ); } /** * @dev Gets the configuration paramters of the reserve * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParams(DataTypes.ReserveConfigurationMap storage self) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { uint256 dataLocal = self.data; return ( dataLocal & ~LTV_MASK, (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration paramters of the reserve from a memory object * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParamsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( uint256, uint256, uint256, uint256, uint256 ) { return ( self.data & ~LTV_MASK, (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration flags of the reserve from a memory object * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( bool, bool, bool, bool ) { return ( (self.data & ~ACTIVE_MASK) != 0, (self.data & ~FROZEN_MASK) != 0, (self.data & ~BORROWING_MASK) != 0, (self.data & ~STABLE_BORROWING_MASK) != 0 ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title UserConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the user configuration */ library UserConfiguration { uint256 internal constant BORROWING_MASK = 0x5555555555555555555555555555555555555555555555555555555555555555; /** * @dev Sets if the user is borrowing the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param borrowing True if the user is borrowing the reserve, false otherwise **/ function setBorrowing( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool borrowing ) internal { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); self.data = (self.data & ~(1 << (reserveIndex * 2))) | (uint256(borrowing ? 1 : 0) << (reserveIndex * 2)); } /** * @dev Sets if the user is using as collateral the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param usingAsCollateral True if the user is usin the reserve as collateral, false otherwise **/ function setUsingAsCollateral( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool usingAsCollateral ) internal { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); self.data = (self.data & ~(1 << (reserveIndex * 2 + 1))) | (uint256(usingAsCollateral ? 1 : 0) << (reserveIndex * 2 + 1)); } /** * @dev Used to validate if a user has been using the reserve for borrowing or as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing or as collateral, false otherwise **/ function isUsingAsCollateralOrBorrowing( DataTypes.UserConfigurationMap memory self, uint256 reserveIndex ) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 3 != 0; } /** * @dev Used to validate if a user has been using the reserve for borrowing * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing, false otherwise **/ function isBorrowing(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 1 != 0; } /** * @dev Used to validate if a user has been using the reserve as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve as collateral, false otherwise **/ function isUsingAsCollateral(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2 + 1)) & 1 != 0; } /** * @dev Used to validate if a user has been borrowing from any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise **/ function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data & BORROWING_MASK != 0; } /** * @dev Used to validate if a user has not been using any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise **/ function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data == 0; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IReserveInterestRateStrategy} from '../../interfaces/IReserveInterestRateStrategy.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; /** * @title DefaultReserveInterestRateStrategy contract * @notice Implements the calculation of the interest rates depending on the reserve state * @dev The model of interest rate is based on 2 slopes, one before the `OPTIMAL_UTILIZATION_RATE` * point of utilization and another from that one to 100% * - An instance of this same contract, can't be used across different Aave markets, due to the caching * of the LendingPoolAddressesProvider * @author Aave **/ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { using WadRayMath for uint256; using SafeMath for uint256; using PercentageMath for uint256; /** * @dev this constant represents the utilization rate at which the pool aims to obtain most competitive borrow rates. * Expressed in ray **/ uint256 public immutable OPTIMAL_UTILIZATION_RATE; /** * @dev This constant represents the excess utilization rate above the optimal. It's always equal to * 1-optimal utilization rate. Added as a constant here for gas optimizations. * Expressed in ray **/ uint256 public immutable EXCESS_UTILIZATION_RATE; ILendingPoolAddressesProvider public immutable addressesProvider; // Base variable borrow rate when Utilization rate = 0. Expressed in ray uint256 internal immutable _baseVariableBorrowRate; // Slope of the variable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope1; // Slope of the variable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope2; // Slope of the stable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope1; // Slope of the stable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope2; constructor( ILendingPoolAddressesProvider provider, uint256 optimalUtilizationRate, uint256 baseVariableBorrowRate, uint256 variableRateSlope1, uint256 variableRateSlope2, uint256 stableRateSlope1, uint256 stableRateSlope2 ) public { OPTIMAL_UTILIZATION_RATE = optimalUtilizationRate; EXCESS_UTILIZATION_RATE = WadRayMath.ray().sub(optimalUtilizationRate); addressesProvider = provider; _baseVariableBorrowRate = baseVariableBorrowRate; _variableRateSlope1 = variableRateSlope1; _variableRateSlope2 = variableRateSlope2; _stableRateSlope1 = stableRateSlope1; _stableRateSlope2 = stableRateSlope2; } function variableRateSlope1() external view returns (uint256) { return _variableRateSlope1; } function variableRateSlope2() external view returns (uint256) { return _variableRateSlope2; } function stableRateSlope1() external view returns (uint256) { return _stableRateSlope1; } function stableRateSlope2() external view returns (uint256) { return _stableRateSlope2; } function baseVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate; } function getMaxVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate.add(_variableRateSlope1).add(_variableRateSlope2); } /** * @dev Calculates the interest rates depending on the reserve's state and configurations * @param reserve The address of the reserve * @param liquidityAdded The liquidity added during the operation * @param liquidityTaken The liquidity taken during the operation * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, address aToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view override returns ( uint256, uint256, uint256 ) { uint256 availableLiquidity = IERC20(reserve).balanceOf(aToken); //avoid stack too deep availableLiquidity = availableLiquidity.add(liquidityAdded).sub(liquidityTaken); return calculateInterestRates( reserve, availableLiquidity, totalStableDebt, totalVariableDebt, averageStableBorrowRate, reserveFactor ); } struct CalcInterestRatesLocalVars { uint256 totalDebt; uint256 currentVariableBorrowRate; uint256 currentStableBorrowRate; uint256 currentLiquidityRate; uint256 utilizationRate; } /** * @dev Calculates the interest rates depending on the reserve's state and configurations. * NOTE This function is kept for compatibility with the previous DefaultInterestRateStrategy interface. * New protocol implementation uses the new calculateInterestRates() interface * @param reserve The address of the reserve * @param availableLiquidity The liquidity available in the corresponding aToken * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) public view override returns ( uint256, uint256, uint256 ) { CalcInterestRatesLocalVars memory vars; vars.totalDebt = totalStableDebt.add(totalVariableDebt); vars.currentVariableBorrowRate = 0; vars.currentStableBorrowRate = 0; vars.currentLiquidityRate = 0; vars.utilizationRate = vars.totalDebt == 0 ? 0 : vars.totalDebt.rayDiv(availableLiquidity.add(vars.totalDebt)); vars.currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle()) .getMarketBorrowRate(reserve); if (vars.utilizationRate > OPTIMAL_UTILIZATION_RATE) { uint256 excessUtilizationRateRatio = vars.utilizationRate.sub(OPTIMAL_UTILIZATION_RATE).rayDiv(EXCESS_UTILIZATION_RATE); vars.currentStableBorrowRate = vars.currentStableBorrowRate.add(_stableRateSlope1).add( _stableRateSlope2.rayMul(excessUtilizationRateRatio) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(_variableRateSlope1).add( _variableRateSlope2.rayMul(excessUtilizationRateRatio) ); } else { vars.currentStableBorrowRate = vars.currentStableBorrowRate.add( _stableRateSlope1.rayMul(vars.utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE)) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add( vars.utilizationRate.rayMul(_variableRateSlope1).rayDiv(OPTIMAL_UTILIZATION_RATE) ); } vars.currentLiquidityRate = _getOverallBorrowRate( totalStableDebt, totalVariableDebt, vars .currentVariableBorrowRate, averageStableBorrowRate ) .rayMul(vars.utilizationRate) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(reserveFactor)); return ( vars.currentLiquidityRate, vars.currentStableBorrowRate, vars.currentVariableBorrowRate ); } /** * @dev Calculates the overall borrow rate as the weighted average between the total variable debt and total stable debt * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param currentVariableBorrowRate The current variable borrow rate of the reserve * @param currentAverageStableBorrowRate The current weighted average of all the stable rate loans * @return The weighted averaged borrow rate **/ function _getOverallBorrowRate( uint256 totalStableDebt, uint256 totalVariableDebt, uint256 currentVariableBorrowRate, uint256 currentAverageStableBorrowRate ) internal pure returns (uint256) { uint256 totalDebt = totalStableDebt.add(totalVariableDebt); if (totalDebt == 0) return 0; uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul(currentVariableBorrowRate); uint256 weightedStableRate = totalStableDebt.wadToRay().rayMul(currentAverageStableBorrowRate); uint256 overallBorrowRate = weightedVariableRate.add(weightedStableRate).rayDiv(totalDebt.wadToRay()); return overallBorrowRate; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IReserveInterestRateStrategyInterface interface * @dev Interface for the calculation of the interest rates * @author Aave */ interface IReserveInterestRateStrategy { function baseVariableBorrowRate() external view returns (uint256); function getMaxVariableBorrowRate() external view returns (uint256); function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256, uint256, uint256 ); function calculateInterestRates( address reserve, address aToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title PercentageMath library * @author Aave * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded half up **/ library PercentageMath { uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { if (value == 0 || percentage == 0) { return 0; } require( value <= (type(uint256).max - HALF_PERCENT) / percentage, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfPercentage = percentage / 2; require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingRateOracle interface * @notice Interface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations **/ interface ILendingRateOracle { /** @dev returns the market borrow rate in ray **/ function getMarketBorrowRate(address asset) external view returns (uint256); /** @dev sets the market borrow rate. Rate value must be in ray **/ function setMarketBorrowRate(address asset, uint256 rate) external; }
IInitializableDebtToken Interface for the initialize function common between debt tokens Aave/
interface IInitializableDebtToken { event Initialized( address indexed underlyingAsset, address indexed pool, address incentivesController, uint8 debtTokenDecimals, string debtTokenName, string debtTokenSymbol, bytes params ); function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) external; } pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; }
127,353
/** *Submitted for verification at Etherscan.io on 2020-02-11 */ // File: @aragon/os/contracts/common/EtherTokenConstant.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File: @aragon/apps-agent/contracts/standards/ERC1271.sol pragma solidity 0.4.24; // ERC1271 on Feb 12th, 2019: https://github.com/ethereum/EIPs/blob/a97dc434930d0ccc4461c97d8c7a920dc585adf2/EIPS/eip-1271.md // Using `isValidSignature(bytes32,bytes)` even though the standard still hasn't been modified // Rationale: https://github.com/ethereum/EIPs/issues/1271#issuecomment-462719728 contract ERC1271 { bytes4 constant public ERC1271_INTERFACE_ID = 0xfb855dc9; // this.isValidSignature.selector bytes4 constant public ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; // TODO: Likely needs to be updated bytes4 constant public ERC1271_RETURN_INVALID_SIGNATURE = 0x00000000; /** * @dev Function must be implemented by deriving contract * @param _hash Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4); function returnIsValidSignatureMagicNumber(bool isValid) internal pure returns (bytes4) { return isValid ? ERC1271_RETURN_VALID_SIGNATURE : ERC1271_RETURN_INVALID_SIGNATURE; } } contract ERC1271Bytes is ERC1271 { /** * @dev Default behavior of `isValidSignature(bytes,bytes)`, can be overloaded for custom validation * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes _data, bytes _signature) public view returns (bytes4) { return isValidSignature(keccak256(_data), _signature); } } // File: @aragon/apps-agent/contracts/SignatureValidator.sol pragma solidity 0.4.24; // Inspired by https://github.com/horizon-games/multi-token-standard/blob/319740cf2a78b8816269ae49a09c537b3fd7303b/contracts/utils/SignatureValidator.sol // This should probably be moved into aOS: https://github.com/aragon/aragonOS/pull/442 library SignatureValidator { enum SignatureMode { Invalid, // 0x00 EIP712, // 0x01 EthSign, // 0x02 ERC1271, // 0x03 NMode // 0x04, to check if mode is specified, leave at the end } // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 public constant ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; uint256 internal constant ERC1271_ISVALIDSIG_MAX_GAS = 250000; string private constant ERROR_INVALID_LENGTH_POP_BYTE = "SIGVAL_INVALID_LENGTH_POP_BYTE"; /// @dev Validates that a hash was signed by a specified signer. /// @param hash Hash which was signed. /// @param signer Address of the signer. /// @param signature ECDSA signature along with the mode (0 = Invalid, 1 = EIP712, 2 = EthSign, 3 = ERC1271) {mode}{r}{s}{v}. /// @return Returns whether signature is from a specified user. function isValidSignature(bytes32 hash, address signer, bytes signature) internal view returns (bool) { if (signature.length == 0) { return false; } uint8 modeByte = uint8(signature[0]); if (modeByte >= uint8(SignatureMode.NMode)) { return false; } SignatureMode mode = SignatureMode(modeByte); if (mode == SignatureMode.EIP712) { return ecVerify(hash, signer, signature); } else if (mode == SignatureMode.EthSign) { return ecVerify( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), signer, signature ); } else if (mode == SignatureMode.ERC1271) { // Pop the mode byte before sending it down the validation chain return safeIsValidSignature(signer, hash, popFirstByte(signature)); } else { return false; } } function ecVerify(bytes32 hash, address signer, bytes memory signature) private pure returns (bool) { (bool badSig, bytes32 r, bytes32 s, uint8 v) = unpackEcSig(signature); if (badSig) { return false; } return signer == ecrecover(hash, v, r, s); } function unpackEcSig(bytes memory signature) private pure returns (bool badSig, bytes32 r, bytes32 s, uint8 v) { if (signature.length != 66) { badSig = true; return; } v = uint8(signature[65]); assembly { r := mload(add(signature, 33)) s := mload(add(signature, 65)) } // Allow signature version to be 0 or 1 if (v < 27) { v += 27; } if (v != 27 && v != 28) { badSig = true; } } function popFirstByte(bytes memory input) private pure returns (bytes memory output) { uint256 inputLength = input.length; require(inputLength > 0, ERROR_INVALID_LENGTH_POP_BYTE); output = new bytes(inputLength - 1); if (output.length == 0) { return output; } uint256 inputPointer; uint256 outputPointer; assembly { inputPointer := add(input, 0x21) outputPointer := add(output, 0x20) } memcpy(outputPointer, inputPointer, output.length); } function safeIsValidSignature(address validator, bytes32 hash, bytes memory signature) private view returns (bool) { bytes memory data = abi.encodeWithSelector(ERC1271(validator).isValidSignature.selector, hash, signature); bytes4 erc1271Return = safeBytes4StaticCall(validator, data, ERC1271_ISVALIDSIG_MAX_GAS); return erc1271Return == ERC1271_RETURN_VALID_SIGNATURE; } function safeBytes4StaticCall(address target, bytes data, uint256 maxGas) private view returns (bytes4 ret) { uint256 gasLeft = gasleft(); uint256 callGas = gasLeft > maxGas ? maxGas : gasLeft; bool ok; assembly { ok := staticcall(callGas, target, add(data, 0x20), mload(data), 0, 0) } if (!ok) { return; } uint256 size; assembly { size := returndatasize } if (size != 32) { return; } assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` ret := mload(ptr) // read data at ptr and set it to be returned } return ret; } // From: https://github.com/Arachnid/solidity-stringutils/blob/01e955c1d6/src/strings.sol function memcpy(uint256 dest, uint256 src, uint256 len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } // File: @aragon/apps-agent/contracts/standards/IERC165.sol pragma solidity 0.4.24; interface IERC165 { function supportsInterface(bytes4 interfaceId) external pure returns (bool); } // File: @aragon/os/contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: @aragon/os/contracts/acl/IACL.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: @aragon/os/contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: @aragon/os/contracts/kernel/IKernel.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: @aragon/os/contracts/apps/AppStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File: @aragon/os/contracts/common/Uint256Helpers.sol pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File: @aragon/os/contracts/common/TimeHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File: @aragon/os/contracts/common/Initializable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File: @aragon/os/contracts/common/Petrifiable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File: @aragon/os/contracts/common/Autopetrified.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } // File: @aragon/os/contracts/common/ConversionHelpers.sol pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File: @aragon/os/contracts/common/ReentrancyGuard.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } // File: @aragon/os/contracts/lib/token/ERC20.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @aragon/os/contracts/common/IsContract.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: @aragon/os/contracts/common/SafeERC20.sol // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } } // File: @aragon/os/contracts/common/VaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } // File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } // File: @aragon/os/contracts/kernel/KernelConstants.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } // File: @aragon/os/contracts/apps/AragonApp.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } } // File: @aragon/os/contracts/common/DepositableStorage.sol pragma solidity 0.4.24; contract DepositableStorage { using UnstructuredStorage for bytes32; // keccak256("aragonOS.depositableStorage.depositable") bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea; function isDepositable() public view returns (bool) { return DEPOSITABLE_POSITION.getStorageBool(); } function setDepositable(bool _depositable) internal { DEPOSITABLE_POSITION.setStorageBool(_depositable); } } // File: @aragon/apps-vault/contracts/Vault.sol pragma solidity 0.4.24; contract Vault is EtherTokenConstant, AragonApp, DepositableStorage { using SafeERC20 for ERC20; bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO"; string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE"; string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO"; string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO"; string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED"; string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED"; event VaultTransfer(address indexed token, address indexed to, uint256 amount); event VaultDeposit(address indexed token, address indexed sender, uint256 amount); /** * @dev On a normal send() or transfer() this fallback is never executed as it will be * intercepted by the Proxy (see aragonOS#281) */ function () external payable isInitialized { require(msg.data.length == 0, ERROR_DATA_NON_ZERO); _deposit(ETH, msg.value); } /** * @notice Initialize Vault app * @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work */ function initialize() external onlyInit { initialized(); setDepositable(true); } /** * @notice Deposit `_value` `_token` to the vault * @param _token Address of the token being transferred * @param _value Amount of tokens being transferred */ function deposit(address _token, uint256 _value) external payable isInitialized { _deposit(_token, _value); } /** * @notice Transfer `_value` `_token` from the Vault to `_to` * @param _token Address of the token being transferred * @param _to Address of the recipient of tokens * @param _value Amount of tokens being transferred */ /* solium-disable-next-line function-order */ function transfer(address _token, address _to, uint256 _value) external authP(TRANSFER_ROLE, arr(_token, _to, _value)) { require(_value > 0, ERROR_TRANSFER_VALUE_ZERO); if (_token == ETH) { require(_to.send(_value), ERROR_SEND_REVERTED); } else { require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED); } emit VaultTransfer(_token, _to, _value); } function balance(address _token) public view returns (uint256) { if (_token == ETH) { return address(this).balance; } else { return ERC20(_token).staticBalanceOf(address(this)); } } /** * @dev Disable recovery escape hatch, as it could be used * maliciously to transfer funds away from the vault */ function allowRecoverability(address) public view returns (bool) { return false; } function _deposit(address _token, uint256 _value) internal { require(isDepositable(), ERROR_NOT_DEPOSITABLE); require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO); if (_token == ETH) { // Deposit is implicit in this case require(msg.value == _value, ERROR_VALUE_MISMATCH); } else { require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _value), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } emit VaultDeposit(_token, msg.sender, _value); } } // File: @aragon/os/contracts/common/IForwarder.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IForwarder { function isForwarder() external pure returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function canForward(address sender, bytes evmCallScript) public view returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function forward(bytes evmCallScript) public; } // File: @aragon/apps-agent/contracts/Agent.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Agent is IERC165, ERC1271Bytes, IForwarder, IsContract, Vault { /* Hardcoded constants to save gas bytes32 public constant EXECUTE_ROLE = keccak256("EXECUTE_ROLE"); bytes32 public constant SAFE_EXECUTE_ROLE = keccak256("SAFE_EXECUTE_ROLE"); bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = keccak256("ADD_PROTECTED_TOKEN_ROLE"); bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = keccak256("REMOVE_PROTECTED_TOKEN_ROLE"); bytes32 public constant ADD_PRESIGNED_HASH_ROLE = keccak256("ADD_PRESIGNED_HASH_ROLE"); bytes32 public constant DESIGNATE_SIGNER_ROLE = keccak256("DESIGNATE_SIGNER_ROLE"); bytes32 public constant RUN_SCRIPT_ROLE = keccak256("RUN_SCRIPT_ROLE"); */ bytes32 public constant EXECUTE_ROLE = 0xcebf517aa4440d1d125e0355aae64401211d0848a23c02cc5d29a14822580ba4; bytes32 public constant SAFE_EXECUTE_ROLE = 0x0a1ad7b87f5846153c6d5a1f761d71c7d0cfd122384f56066cd33239b7933694; bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = 0x6eb2a499556bfa2872f5aa15812b956cc4a71b4d64eb3553f7073c7e41415aaa; bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = 0x71eee93d500f6f065e38b27d242a756466a00a52a1dbcd6b4260f01a8640402a; bytes32 public constant ADD_PRESIGNED_HASH_ROLE = 0x0b29780bb523a130b3b01f231ef49ed2fa2781645591a0b0a44ca98f15a5994c; bytes32 public constant DESIGNATE_SIGNER_ROLE = 0x23ce341656c3f14df6692eebd4757791e33662b7dcf9970c8308303da5472b7c; bytes32 public constant RUN_SCRIPT_ROLE = 0xb421f7ad7646747f3051c50c0b8e2377839296cd4973e27f63821d73e390338f; uint256 public constant PROTECTED_TOKENS_CAP = 10; bytes4 private constant ERC165_INTERFACE_ID = 0x01ffc9a7; string private constant ERROR_TARGET_PROTECTED = "AGENT_TARGET_PROTECTED"; string private constant ERROR_PROTECTED_TOKENS_MODIFIED = "AGENT_PROTECTED_TOKENS_MODIFIED"; string private constant ERROR_PROTECTED_BALANCE_LOWERED = "AGENT_PROTECTED_BALANCE_LOWERED"; string private constant ERROR_TOKENS_CAP_REACHED = "AGENT_TOKENS_CAP_REACHED"; string private constant ERROR_TOKEN_NOT_ERC20 = "AGENT_TOKEN_NOT_ERC20"; string private constant ERROR_TOKEN_ALREADY_PROTECTED = "AGENT_TOKEN_ALREADY_PROTECTED"; string private constant ERROR_TOKEN_NOT_PROTECTED = "AGENT_TOKEN_NOT_PROTECTED"; string private constant ERROR_DESIGNATED_TO_SELF = "AGENT_DESIGNATED_TO_SELF"; string private constant ERROR_CAN_NOT_FORWARD = "AGENT_CAN_NOT_FORWARD"; mapping (bytes32 => bool) public isPresigned; address public designatedSigner; address[] public protectedTokens; event SafeExecute(address indexed sender, address indexed target, bytes data); event Execute(address indexed sender, address indexed target, uint256 ethValue, bytes data); event AddProtectedToken(address indexed token); event RemoveProtectedToken(address indexed token); event PresignHash(address indexed sender, bytes32 indexed hash); event SetDesignatedSigner(address indexed sender, address indexed oldSigner, address indexed newSigner); /** * @notice Execute '`@radspec(_target, _data)`' on `_target``_ethValue == 0 ? '' : ' (Sending' + @tokenAmount(0x0000000000000000000000000000000000000000, _ethValue) + ')'` * @param _target Address where the action is being executed * @param _ethValue Amount of ETH from the contract that is sent with the action * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function execute(address _target, uint256 _ethValue, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(EXECUTE_ROLE, arr(_target, _ethValue, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { bool result = _target.call.value(_ethValue)(_data); if (result) { emit Execute(msg.sender, _target, _ethValue, _data); } assembly { let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, returndatasize) } default { return(ptr, returndatasize) } } } /** * @notice Execute '`@radspec(_target, _data)`' on `_target` ensuring that protected tokens can't be spent * @param _target Address where the action is being executed * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function safeExecute(address _target, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(SAFE_EXECUTE_ROLE, arr(_target, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { uint256 protectedTokensLength = protectedTokens.length; address[] memory protectedTokens_ = new address[](protectedTokensLength); uint256[] memory balances = new uint256[](protectedTokensLength); for (uint256 i = 0; i < protectedTokensLength; i++) { address token = protectedTokens[i]; require(_target != token, ERROR_TARGET_PROTECTED); // we copy the protected tokens array to check whether the storage array has been modified during the underlying call protectedTokens_[i] = token; // we copy the balances to check whether they have been modified during the underlying call balances[i] = balance(token); } bool result = _target.call(_data); bytes32 ptr; uint256 size; assembly { size := returndatasize ptr := mload(0x40) mstore(0x40, add(ptr, returndatasize)) returndatacopy(ptr, 0, returndatasize) } if (result) { // if the underlying call has succeeded, we check that the protected tokens // and their balances have not been modified and return the call's return data require(protectedTokens.length == protectedTokensLength, ERROR_PROTECTED_TOKENS_MODIFIED); for (uint256 j = 0; j < protectedTokensLength; j++) { require(protectedTokens[j] == protectedTokens_[j], ERROR_PROTECTED_TOKENS_MODIFIED); require(balance(protectedTokens[j]) >= balances[j], ERROR_PROTECTED_BALANCE_LOWERED); } emit SafeExecute(msg.sender, _target, _data); assembly { return(ptr, size) } } else { // if the underlying call has failed, we revert and forward returned error data assembly { revert(ptr, size) } } } /** * @notice Add `_token.symbol(): string` to the list of protected tokens * @param _token Address of the token to be protected */ function addProtectedToken(address _token) external authP(ADD_PROTECTED_TOKEN_ROLE, arr(_token)) { require(protectedTokens.length < PROTECTED_TOKENS_CAP, ERROR_TOKENS_CAP_REACHED); require(_isERC20(_token), ERROR_TOKEN_NOT_ERC20); require(!_tokenIsProtected(_token), ERROR_TOKEN_ALREADY_PROTECTED); _addProtectedToken(_token); } /** * @notice Remove `_token.symbol(): string` from the list of protected tokens * @param _token Address of the token to be unprotected */ function removeProtectedToken(address _token) external authP(REMOVE_PROTECTED_TOKEN_ROLE, arr(_token)) { require(_tokenIsProtected(_token), ERROR_TOKEN_NOT_PROTECTED); _removeProtectedToken(_token); } /** * @notice Pre-sign hash `_hash` * @param _hash Hash that will be considered signed regardless of the signature checked with 'isValidSignature()' */ function presignHash(bytes32 _hash) external authP(ADD_PRESIGNED_HASH_ROLE, arr(_hash)) { isPresigned[_hash] = true; emit PresignHash(msg.sender, _hash); } /** * @notice Set `_designatedSigner` as the designated signer of the app, which will be able to sign messages on behalf of the app * @param _designatedSigner Address that will be able to sign messages on behalf of the app */ function setDesignatedSigner(address _designatedSigner) external authP(DESIGNATE_SIGNER_ROLE, arr(_designatedSigner)) { // Prevent an infinite loop by setting the app itself as its designated signer. // An undetectable loop can be created by setting a different contract as the // designated signer which calls back into `isValidSignature`. // Given that `isValidSignature` is always called with just 50k gas, the max // damage of the loop is wasting 50k gas. require(_designatedSigner != address(this), ERROR_DESIGNATED_TO_SELF); address oldDesignatedSigner = designatedSigner; designatedSigner = _designatedSigner; emit SetDesignatedSigner(msg.sender, oldDesignatedSigner, _designatedSigner); } // Forwarding fns /** * @notice Tells whether the Agent app is a forwarder or not * @dev IForwarder interface conformance * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute the script as the Agent app * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = ""; // no input address[] memory blacklist = new address[](0); // no addr blacklist, can interact with anything runScript(_evmScript, input, blacklist); // We don't need to emit an event here as EVMScriptRunner will emit ScriptResult if successful } /** * @notice Tells whether `_sender` can forward actions or not * @dev IForwarder interface conformance * @param _sender Address of the account intending to forward an action * @return True if the given address can run scripts, false otherwise */ function canForward(address _sender, bytes _evmScript) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, RUN_SCRIPT_ROLE, arr(_getScriptACLParam(_evmScript))); } // ERC-165 conformance /** * @notice Tells whether this contract supports a given ERC-165 interface * @param _interfaceId Interface bytes to check * @return True if this contract supports the interface */ function supportsInterface(bytes4 _interfaceId) external pure returns (bool) { return _interfaceId == ERC1271_INTERFACE_ID || _interfaceId == ERC165_INTERFACE_ID; } // ERC-1271 conformance /** * @notice Tells whether a signature is seen as valid by this contract through ERC-1271 * @param _hash Arbitrary length data signed on the behalf of address (this) * @param _signature Signature byte array associated with _data * @return The ERC-1271 magic value if the signature is valid */ function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) { // Short-circuit in case the hash was presigned. Optimization as performing calls // and ecrecover is more expensive than an SLOAD. if (isPresigned[_hash]) { return returnIsValidSignatureMagicNumber(true); } bool isValid; if (designatedSigner == address(0)) { isValid = false; } else { isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature); } return returnIsValidSignatureMagicNumber(isValid); } // Getters function getProtectedTokensLength() public view isInitialized returns (uint256) { return protectedTokens.length; } // Internal fns function _addProtectedToken(address _token) internal { protectedTokens.push(_token); emit AddProtectedToken(_token); } function _removeProtectedToken(address _token) internal { protectedTokens[_protectedTokenIndex(_token)] = protectedTokens[protectedTokens.length - 1]; protectedTokens.length--; emit RemoveProtectedToken(_token); } function _isERC20(address _token) internal view returns (bool) { if (!isContract(_token)) { return false; } // Throwaway sanity check to make sure the token's `balanceOf()` does not error (for now) balance(_token); return true; } function _protectedTokenIndex(address _token) internal view returns (uint256) { for (uint i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return i; } } revert(ERROR_TOKEN_NOT_PROTECTED); } function _tokenIsProtected(address _token) internal view returns (bool) { for (uint256 i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return true; } } return false; } function _getScriptACLParam(bytes _evmScript) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(_evmScript))); } function _getSig(bytes _data) internal pure returns (bytes4 sig) { if (_data.length < 4) { return; } assembly { sig := mload(add(_data, 0x20)) } } } // File: @aragon/os/contracts/lib/math/SafeMath.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/os/contracts/lib/math/SafeMath64.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules // Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417 pragma solidity ^0.4.24; /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/apps-shared-minime/contracts/ITokenController.sol pragma solidity ^0.4.24; /// @dev The token controller contract must implement these functions interface ITokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) external payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) external returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } // File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol pragma solidity ^0.4.24; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes _data ) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( MiniMeTokenFactory _tokenFactory, MiniMeToken _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = _tokenFactory; name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _parentToken; parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onTransfer(_from, _to, _amount) == true); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) { require(approve(_spender, _amount)); _spender.receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(MiniMeToken) { uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshot, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), snapshot); return cloneToken; } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController public { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () external payable { require(isContract(controller)); // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( MiniMeToken _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } // File: @aragon/apps-voting/contracts/Voting.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Voting is IForwarder, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE"); bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE"); bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE"; string private constant ERROR_INIT_PCTS = "VOTING_INIT_PCTS"; string private constant ERROR_CHANGE_SUPPORT_PCTS = "VOTING_CHANGE_SUPPORT_PCTS"; string private constant ERROR_CHANGE_QUORUM_PCTS = "VOTING_CHANGE_QUORUM_PCTS"; string private constant ERROR_INIT_SUPPORT_TOO_BIG = "VOTING_INIT_SUPPORT_TOO_BIG"; string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPP_TOO_BIG"; string private constant ERROR_CAN_NOT_VOTE = "VOTING_CAN_NOT_VOTE"; string private constant ERROR_CAN_NOT_EXECUTE = "VOTING_CAN_NOT_EXECUTE"; string private constant ERROR_CAN_NOT_FORWARD = "VOTING_CAN_NOT_FORWARD"; string private constant ERROR_NO_VOTING_POWER = "VOTING_NO_VOTING_POWER"; enum VoterState { Absent, Yea, Nay } struct Vote { bool executed; uint64 startDate; uint64 snapshotBlock; uint64 supportRequiredPct; uint64 minAcceptQuorumPct; uint256 yea; uint256 nay; uint256 votingPower; bytes executionScript; mapping (address => VoterState) voters; } MiniMeToken public token; uint64 public supportRequiredPct; uint64 public minAcceptQuorumPct; uint64 public voteTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => Vote) internal votes; uint256 public votesLength; event StartVote(uint256 indexed voteId, address indexed creator, string metadata); event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake); event ExecuteVote(uint256 indexed voteId); event ChangeSupportRequired(uint64 supportRequiredPct); event ChangeMinQuorum(uint64 minAcceptQuorumPct); modifier voteExists(uint256 _voteId) { require(_voteId < votesLength, ERROR_NO_VOTE); _; } /** * @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, and a voting duration of `@transformTime(_voteTime)` * @param _token MiniMeToken Address that will be used as governance token * @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _voteTime Seconds that a vote will be open for token holders to vote (unless enough yeas or nays have been cast to make an early decision) */ function initialize( MiniMeToken _token, uint64 _supportRequiredPct, uint64 _minAcceptQuorumPct, uint64 _voteTime ) external onlyInit { initialized(); require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG); token = _token; supportRequiredPct = _supportRequiredPct; minAcceptQuorumPct = _minAcceptQuorumPct; voteTime = _voteTime; } /** * @notice Change required support to `@formatPct(_supportRequiredPct)`% * @param _supportRequiredPct New required support */ function changeSupportRequiredPct(uint64 _supportRequiredPct) external authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct))) { require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG); supportRequiredPct = _supportRequiredPct; emit ChangeSupportRequired(_supportRequiredPct); } /** * @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`% * @param _minAcceptQuorumPct New acceptance quorum */ function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct))) { require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS); minAcceptQuorumPct = _minAcceptQuorumPct; emit ChangeMinQuorum(_minAcceptQuorumPct); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @return voteId Id for newly created vote */ function newVote(bytes _executionScript, string _metadata) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, true, true); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @param _castVote Whether to also cast newly created vote * @param _executesIfDecided Whether to also immediately execute newly created vote if decided * @return voteId id for newly created vote */ function newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, _castVote, _executesIfDecided); } /** * @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote * @param _supports Whether voter supports the vote * @param _executesIfDecided Whether the vote should execute its action if it becomes decided */ function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external voteExists(_voteId) { require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE); _vote(_voteId, _supports, msg.sender, _executesIfDecided); } /** * @notice Execute vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote */ function executeVote(uint256 _voteId) external voteExists(_voteId) { _executeVote(_voteId); } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Creates a vote to execute the desired action, and casts a support vote if possible * @dev IForwarder interface conformance * @param _evmScript Start vote with script */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); _newVote(_evmScript, "", true, true); } function canForward(address _sender, bytes) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, CREATE_VOTES_ROLE, arr()); } // Getter fns /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canExecute(uint256 _voteId) public view voteExists(_voteId) returns (bool) { return _canExecute(_voteId); } /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) { return _canVote(_voteId, _voter); } function getVote(uint256 _voteId) public view voteExists(_voteId) returns ( bool open, bool executed, uint64 startDate, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 yea, uint256 nay, uint256 votingPower, bytes script ) { Vote storage vote_ = votes[_voteId]; open = _isVoteOpen(vote_); executed = vote_.executed; startDate = vote_.startDate; snapshotBlock = vote_.snapshotBlock; supportRequired = vote_.supportRequiredPct; minAcceptQuorum = vote_.minAcceptQuorumPct; yea = vote_.yea; nay = vote_.nay; votingPower = vote_.votingPower; script = vote_.executionScript; } function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) { return votes[_voteId].voters[_voter]; } // Internal fns function _newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) internal returns (uint256 voteId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); voteId = votesLength++; Vote storage vote_ = votes[voteId]; vote_.startDate = getTimestamp64(); vote_.snapshotBlock = snapshotBlock; vote_.supportRequiredPct = supportRequiredPct; vote_.minAcceptQuorumPct = minAcceptQuorumPct; vote_.votingPower = votingPower; vote_.executionScript = _executionScript; emit StartVote(voteId, msg.sender, _metadata); if (_castVote && _canVote(voteId, msg.sender)) { _vote(voteId, true, msg.sender, _executesIfDecided); } } function _vote( uint256 _voteId, bool _supports, address _voter, bool _executesIfDecided ) internal { Vote storage vote_ = votes[_voteId]; // This could re-enter, though we can assume the governance token is not malicious uint256 voterStake = token.balanceOfAt(_voter, vote_.snapshotBlock); VoterState state = vote_.voters[_voter]; // If voter had previously voted, decrease count if (state == VoterState.Yea) { vote_.yea = vote_.yea.sub(voterStake); } else if (state == VoterState.Nay) { vote_.nay = vote_.nay.sub(voterStake); } if (_supports) { vote_.yea = vote_.yea.add(voterStake); } else { vote_.nay = vote_.nay.add(voterStake); } vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay; emit CastVote(_voteId, _voter, _supports, voterStake); if (_executesIfDecided && _canExecute(_voteId)) { // We've already checked if the vote can be executed with `_canExecute()` _unsafeExecuteVote(_voteId); } } function _executeVote(uint256 _voteId) internal { require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE); _unsafeExecuteVote(_voteId); } /** * @dev Unsafe version of _executeVote that assumes you have already checked if the vote can be executed */ function _unsafeExecuteVote(uint256 _voteId) internal { Vote storage vote_ = votes[_voteId]; vote_.executed = true; bytes memory input = new bytes(0); // TODO: Consider input for voting scripts runScript(vote_.executionScript, input, new address[](0)); emit ExecuteVote(_voteId); } function _canExecute(uint256 _voteId) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; if (vote_.executed) { return false; } // Voting is already decided if (_isValuePct(vote_.yea, vote_.votingPower, vote_.supportRequiredPct)) { return true; } // Vote ended? if (_isVoteOpen(vote_)) { return false; } // Has enough support? uint256 totalVotes = vote_.yea.add(vote_.nay); if (!_isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct)) { return false; } // Has min quorum? if (!_isValuePct(vote_.yea, vote_.votingPower, vote_.minAcceptQuorumPct)) { return false; } return true; } function _canVote(uint256 _voteId, address _voter) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; return _isVoteOpen(vote_) && token.balanceOfAt(_voter, vote_.snapshotBlock) > 0; } function _isVoteOpen(Vote storage vote_) internal view returns (bool) { return getTimestamp64() < vote_.startDate.add(voteTime) && !vote_.executed; } /** * @dev Calculates whether `_value` is more than a percentage `_pct` of `_total` */ function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) { if (_total == 0) { return false; } uint256 computedPct = _value.mul(PCT_BASE) / _total; return computedPct > _pct; } } // File: @aragon/ppf-contracts/contracts/IFeed.sol pragma solidity ^0.4.18; interface IFeed { function ratePrecision() external pure returns (uint256); function get(address base, address quote) external view returns (uint128 xrt, uint64 when); } // File: @aragon/apps-finance/contracts/Finance.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Finance is EtherTokenConstant, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; using SafeERC20 for ERC20; bytes32 public constant CREATE_PAYMENTS_ROLE = keccak256("CREATE_PAYMENTS_ROLE"); bytes32 public constant CHANGE_PERIOD_ROLE = keccak256("CHANGE_PERIOD_ROLE"); bytes32 public constant CHANGE_BUDGETS_ROLE = keccak256("CHANGE_BUDGETS_ROLE"); bytes32 public constant EXECUTE_PAYMENTS_ROLE = keccak256("EXECUTE_PAYMENTS_ROLE"); bytes32 public constant MANAGE_PAYMENTS_ROLE = keccak256("MANAGE_PAYMENTS_ROLE"); uint256 internal constant NO_SCHEDULED_PAYMENT = 0; uint256 internal constant NO_TRANSACTION = 0; uint256 internal constant MAX_SCHEDULED_PAYMENTS_PER_TX = 20; uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); uint64 internal constant MINIMUM_PERIOD = uint64(1 days); string private constant ERROR_COMPLETE_TRANSITION = "FINANCE_COMPLETE_TRANSITION"; string private constant ERROR_NO_SCHEDULED_PAYMENT = "FINANCE_NO_SCHEDULED_PAYMENT"; string private constant ERROR_NO_TRANSACTION = "FINANCE_NO_TRANSACTION"; string private constant ERROR_NO_PERIOD = "FINANCE_NO_PERIOD"; string private constant ERROR_VAULT_NOT_CONTRACT = "FINANCE_VAULT_NOT_CONTRACT"; string private constant ERROR_SET_PERIOD_TOO_SHORT = "FINANCE_SET_PERIOD_TOO_SHORT"; string private constant ERROR_NEW_PAYMENT_AMOUNT_ZERO = "FINANCE_NEW_PAYMENT_AMOUNT_ZERO"; string private constant ERROR_NEW_PAYMENT_INTERVAL_ZERO = "FINANCE_NEW_PAYMENT_INTRVL_ZERO"; string private constant ERROR_NEW_PAYMENT_EXECS_ZERO = "FINANCE_NEW_PAYMENT_EXECS_ZERO"; string private constant ERROR_NEW_PAYMENT_IMMEDIATE = "FINANCE_NEW_PAYMENT_IMMEDIATE"; string private constant ERROR_RECOVER_AMOUNT_ZERO = "FINANCE_RECOVER_AMOUNT_ZERO"; string private constant ERROR_DEPOSIT_AMOUNT_ZERO = "FINANCE_DEPOSIT_AMOUNT_ZERO"; string private constant ERROR_ETH_VALUE_MISMATCH = "FINANCE_ETH_VALUE_MISMATCH"; string private constant ERROR_BUDGET = "FINANCE_BUDGET"; string private constant ERROR_EXECUTE_PAYMENT_NUM = "FINANCE_EXECUTE_PAYMENT_NUM"; string private constant ERROR_EXECUTE_PAYMENT_TIME = "FINANCE_EXECUTE_PAYMENT_TIME"; string private constant ERROR_PAYMENT_RECEIVER = "FINANCE_PAYMENT_RECEIVER"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "FINANCE_TKN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_APPROVE_FAILED = "FINANCE_TKN_APPROVE_FAILED"; string private constant ERROR_PAYMENT_INACTIVE = "FINANCE_PAYMENT_INACTIVE"; string private constant ERROR_REMAINING_BUDGET = "FINANCE_REMAINING_BUDGET"; // Order optimized for storage struct ScheduledPayment { address token; address receiver; address createdBy; bool inactive; uint256 amount; uint64 initialPaymentTime; uint64 interval; uint64 maxExecutions; uint64 executions; } // Order optimized for storage struct Transaction { address token; address entity; bool isIncoming; uint256 amount; uint256 paymentId; uint64 paymentExecutionNumber; uint64 date; uint64 periodId; } struct TokenStatement { uint256 expenses; uint256 income; } struct Period { uint64 startTime; uint64 endTime; uint256 firstTransactionId; uint256 lastTransactionId; mapping (address => TokenStatement) tokenStatement; } struct Settings { uint64 periodDuration; mapping (address => uint256) budgets; mapping (address => bool) hasBudget; } Vault public vault; Settings internal settings; // We are mimicing arrays, we use mappings instead to make app upgrade more graceful mapping (uint256 => ScheduledPayment) internal scheduledPayments; // Payments start at index 1, to allow us to use scheduledPayments[0] for transactions that are not // linked to a scheduled payment uint256 public paymentsNextIndex; mapping (uint256 => Transaction) internal transactions; uint256 public transactionsNextIndex; mapping (uint64 => Period) internal periods; uint64 public periodsLength; event NewPeriod(uint64 indexed periodId, uint64 periodStarts, uint64 periodEnds); event SetBudget(address indexed token, uint256 amount, bool hasBudget); event NewPayment(uint256 indexed paymentId, address indexed recipient, uint64 maxExecutions, string reference); event NewTransaction(uint256 indexed transactionId, bool incoming, address indexed entity, uint256 amount, string reference); event ChangePaymentState(uint256 indexed paymentId, bool active); event ChangePeriodDuration(uint64 newDuration); event PaymentFailure(uint256 paymentId); // Modifier used by all methods that impact accounting to make sure accounting period // is changed before the operation if needed // NOTE: its use **MUST** be accompanied by an initialization check modifier transitionsPeriod { bool completeTransition = _tryTransitionAccountingPeriod(getMaxPeriodTransitions()); require(completeTransition, ERROR_COMPLETE_TRANSITION); _; } modifier scheduledPaymentExists(uint256 _paymentId) { require(_paymentId > 0 && _paymentId < paymentsNextIndex, ERROR_NO_SCHEDULED_PAYMENT); _; } modifier transactionExists(uint256 _transactionId) { require(_transactionId > 0 && _transactionId < transactionsNextIndex, ERROR_NO_TRANSACTION); _; } modifier periodExists(uint64 _periodId) { require(_periodId < periodsLength, ERROR_NO_PERIOD); _; } /** * @notice Deposit ETH to the Vault, to avoid locking them in this Finance app forever * @dev Send ETH to Vault. Send all the available balance. */ function () external payable isInitialized transitionsPeriod { require(msg.value > 0, ERROR_DEPOSIT_AMOUNT_ZERO); _deposit( ETH, msg.value, "Ether transfer to Finance app", msg.sender, true ); } /** * @notice Initialize Finance app for Vault at `_vault` with period length of `@transformTime(_periodDuration)` * @param _vault Address of the vault Finance will rely on (non changeable) * @param _periodDuration Duration in seconds of each period */ function initialize(Vault _vault, uint64 _periodDuration) external onlyInit { initialized(); require(isContract(_vault), ERROR_VAULT_NOT_CONTRACT); vault = _vault; require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; // Reserve the first scheduled payment index as an unused index for transactions not linked // to a scheduled payment scheduledPayments[0].inactive = true; paymentsNextIndex = 1; // Reserve the first transaction index as an unused index for periods with no transactions transactionsNextIndex = 1; // Start the first period _newPeriod(getTimestamp64()); } /** * @notice Deposit `@tokenAmount(_token, _amount)` * @dev Deposit for approved ERC20 tokens or ETH * @param _token Address of deposited token * @param _amount Amount of tokens sent * @param _reference Reason for payment */ function deposit(address _token, uint256 _amount, string _reference) external payable isInitialized transitionsPeriod { require(_amount > 0, ERROR_DEPOSIT_AMOUNT_ZERO); if (_token == ETH) { // Ensure that the ETH sent with the transaction equals the amount in the deposit require(msg.value == _amount, ERROR_ETH_VALUE_MISMATCH); } _deposit( _token, _amount, _reference, msg.sender, true ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for '`_reference`' * @dev Note that this function is protected by the `CREATE_PAYMENTS_ROLE` but uses `MAX_UINT256` * as its interval auth parameter (as a sentinel value for "never repeating"). * While this protects against most cases (you typically want to set a baseline requirement * for interval time), it does mean users will have to explicitly check for this case when * granting a permission that includes a upperbound requirement on the interval time. * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _reference String detailing payment reason */ function newImmediatePayment(address _token, address _receiver, uint256 _amount, string _reference) external // Use MAX_UINT256 as the interval parameter, as this payment will never repeat // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, MAX_UINT256, uint256(1), getTimestamp())) transitionsPeriod { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); _makePaymentTransaction( _token, _receiver, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any payment id; it isn't created 0, // also unrelated to any payment executions _reference ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for `_reference`, executing `_maxExecutions` times at intervals of `@transformTime(_interval)` * @dev See `newImmediatePayment()` for limitations on how the interval auth parameter can be used * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _initialPaymentTime Timestamp for when the first payment is done * @param _interval Number of seconds that need to pass between payment transactions * @param _maxExecutions Maximum instances a payment can be executed * @param _reference String detailing payment reason */ function newScheduledPayment( address _token, address _receiver, uint256 _amount, uint64 _initialPaymentTime, uint64 _interval, uint64 _maxExecutions, string _reference ) external // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, uint256(_interval), uint256(_maxExecutions), uint256(_initialPaymentTime))) transitionsPeriod returns (uint256 paymentId) { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); require(_interval > 0, ERROR_NEW_PAYMENT_INTERVAL_ZERO); require(_maxExecutions > 0, ERROR_NEW_PAYMENT_EXECS_ZERO); // Token budget must not be set at all or allow at least one instance of this payment each period require(!settings.hasBudget[_token] || settings.budgets[_token] >= _amount, ERROR_BUDGET); // Don't allow creating single payments that are immediately executable, use `newImmediatePayment()` instead if (_maxExecutions == 1) { require(_initialPaymentTime > getTimestamp64(), ERROR_NEW_PAYMENT_IMMEDIATE); } paymentId = paymentsNextIndex++; emit NewPayment(paymentId, _receiver, _maxExecutions, _reference); ScheduledPayment storage payment = scheduledPayments[paymentId]; payment.token = _token; payment.receiver = _receiver; payment.amount = _amount; payment.initialPaymentTime = _initialPaymentTime; payment.interval = _interval; payment.maxExecutions = _maxExecutions; payment.createdBy = msg.sender; // We skip checking how many times the new payment was executed to allow creating new // scheduled payments before having enough vault balance _executePayment(paymentId); } /** * @notice Change period duration to `@transformTime(_periodDuration)`, effective for next accounting period * @param _periodDuration Duration in seconds for accounting periods */ function setPeriodDuration(uint64 _periodDuration) external authP(CHANGE_PERIOD_ROLE, arr(uint256(_periodDuration), uint256(settings.periodDuration))) transitionsPeriod { require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; emit ChangePeriodDuration(_periodDuration); } /** * @notice Set budget for `_token.symbol(): string` to `@tokenAmount(_token, _amount, false)`, effective immediately * @param _token Address for token * @param _amount New budget amount */ function setBudget( address _token, uint256 _amount ) external authP(CHANGE_BUDGETS_ROLE, arr(_token, _amount, settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = _amount; if (!settings.hasBudget[_token]) { settings.hasBudget[_token] = true; } emit SetBudget(_token, _amount, true); } /** * @notice Remove spending limit for `_token.symbol(): string`, effective immediately * @param _token Address for token */ function removeBudget(address _token) external authP(CHANGE_BUDGETS_ROLE, arr(_token, uint256(0), settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = 0; settings.hasBudget[_token] = false; emit SetBudget(_token, 0, false); } /** * @notice Execute pending payment #`_paymentId` * @dev Executes any payment (requires role) * @param _paymentId Identifier for payment */ function executePayment(uint256 _paymentId) external authP(EXECUTE_PAYMENTS_ROLE, arr(_paymentId, scheduledPayments[_paymentId].amount)) scheduledPaymentExists(_paymentId) transitionsPeriod { _executePaymentAtLeastOnce(_paymentId); } /** * @notice Execute pending payment #`_paymentId` * @dev Always allow receiver of a payment to trigger execution * Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization * @param _paymentId Identifier for payment */ function receiverExecutePayment(uint256 _paymentId) external scheduledPaymentExists(_paymentId) transitionsPeriod { require(scheduledPayments[_paymentId].receiver == msg.sender, ERROR_PAYMENT_RECEIVER); _executePaymentAtLeastOnce(_paymentId); } /** * @notice `_active ? 'Activate' : 'Disable'` payment #`_paymentId` * @dev Note that we do not require this action to transition periods, as it doesn't directly * impact any accounting periods. * Not having to transition periods also makes disabling payments easier to prevent funds * from being pulled out in the event of a breach. * @param _paymentId Identifier for payment * @param _active Whether it will be active or inactive */ function setPaymentStatus(uint256 _paymentId, bool _active) external authP(MANAGE_PAYMENTS_ROLE, arr(_paymentId, uint256(_active ? 1 : 0))) scheduledPaymentExists(_paymentId) { scheduledPayments[_paymentId].inactive = !_active; emit ChangePaymentState(_paymentId, _active); } /** * @notice Send tokens held in this contract to the Vault * @dev Allows making a simple payment from this contract to the Vault, to avoid locked tokens. * This contract should never receive tokens with a simple transfer call, but in case it * happens, this function allows for their recovery. * @param _token Token whose balance is going to be transferred. */ function recoverToVault(address _token) external isInitialized transitionsPeriod { uint256 amount = _token == ETH ? address(this).balance : ERC20(_token).staticBalanceOf(address(this)); require(amount > 0, ERROR_RECOVER_AMOUNT_ZERO); _deposit( _token, amount, "Recover to Vault", address(this), false ); } /** * @notice Transition accounting period if needed * @dev Transitions accounting periods if needed. For preventing OOG attacks, a maxTransitions * param is provided. If more than the specified number of periods need to be transitioned, * it will return false. * @param _maxTransitions Maximum periods that can be transitioned * @return success Boolean indicating whether the accounting period is the correct one (if false, * maxTransitions was surpased and another call is needed) */ function tryTransitionAccountingPeriod(uint64 _maxTransitions) external isInitialized returns (bool success) { return _tryTransitionAccountingPeriod(_maxTransitions); } // Getter fns /** * @dev Disable recovery escape hatch if the app has been initialized, as it could be used * maliciously to transfer funds in the Finance app to another Vault * finance#recoverToVault() should be used to recover funds to the Finance's vault */ function allowRecoverability(address) public view returns (bool) { return !hasInitialized(); } function getPayment(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns ( address token, address receiver, uint256 amount, uint64 initialPaymentTime, uint64 interval, uint64 maxExecutions, bool inactive, uint64 executions, address createdBy ) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; token = payment.token; receiver = payment.receiver; amount = payment.amount; initialPaymentTime = payment.initialPaymentTime; interval = payment.interval; maxExecutions = payment.maxExecutions; executions = payment.executions; inactive = payment.inactive; createdBy = payment.createdBy; } function getTransaction(uint256 _transactionId) public view transactionExists(_transactionId) returns ( uint64 periodId, uint256 amount, uint256 paymentId, uint64 paymentExecutionNumber, address token, address entity, bool isIncoming, uint64 date ) { Transaction storage transaction = transactions[_transactionId]; token = transaction.token; entity = transaction.entity; isIncoming = transaction.isIncoming; date = transaction.date; periodId = transaction.periodId; amount = transaction.amount; paymentId = transaction.paymentId; paymentExecutionNumber = transaction.paymentExecutionNumber; } function getPeriod(uint64 _periodId) public view periodExists(_periodId) returns ( bool isCurrent, uint64 startTime, uint64 endTime, uint256 firstTransactionId, uint256 lastTransactionId ) { Period storage period = periods[_periodId]; isCurrent = _currentPeriodId() == _periodId; startTime = period.startTime; endTime = period.endTime; firstTransactionId = period.firstTransactionId; lastTransactionId = period.lastTransactionId; } function getPeriodTokenStatement(uint64 _periodId, address _token) public view periodExists(_periodId) returns (uint256 expenses, uint256 income) { TokenStatement storage tokenStatement = periods[_periodId].tokenStatement[_token]; expenses = tokenStatement.expenses; income = tokenStatement.income; } /** * @dev We have to check for initialization as periods are only valid after initializing */ function currentPeriodId() public view isInitialized returns (uint64) { return _currentPeriodId(); } /** * @dev We have to check for initialization as periods are only valid after initializing */ function getPeriodDuration() public view isInitialized returns (uint64) { return settings.periodDuration; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getBudget(address _token) public view isInitialized returns (uint256 budget, bool hasBudget) { budget = settings.budgets[_token]; hasBudget = settings.hasBudget[_token]; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getRemainingBudget(address _token) public view isInitialized returns (uint256) { return _getRemainingBudget(_token); } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function canMakePayment(address _token, uint256 _amount) public view isInitialized returns (bool) { return _canMakePayment(_token, _amount); } /** * @dev Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization */ function nextPaymentTime(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns (uint64) { return _nextPaymentTime(_paymentId); } // Internal fns function _deposit(address _token, uint256 _amount, string _reference, address _sender, bool _isExternalDeposit) internal { _recordIncomingTransaction( _token, _sender, _amount, _reference ); if (_token == ETH) { vault.deposit.value(_amount)(ETH, _amount); } else { // First, transfer the tokens to Finance if necessary // External deposit will be false when the assets were already in the Finance app // and just need to be transferred to the Vault if (_isExternalDeposit) { // This assumes the sender has approved the tokens for Finance require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } // Approve the tokens for the Vault (it does the actual transferring) require(ERC20(_token).safeApprove(vault, _amount), ERROR_TOKEN_APPROVE_FAILED); // Finally, initiate the deposit vault.deposit(_token, _amount); } } function _executePayment(uint256 _paymentId) internal returns (uint256) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; require(!payment.inactive, ERROR_PAYMENT_INACTIVE); uint64 paid = 0; while (_nextPaymentTime(_paymentId) <= getTimestamp64() && paid < MAX_SCHEDULED_PAYMENTS_PER_TX) { if (!_canMakePayment(payment.token, payment.amount)) { emit PaymentFailure(_paymentId); break; } // The while() predicate prevents these two from ever overflowing payment.executions += 1; paid += 1; // We've already checked the remaining budget with `_canMakePayment()` _unsafeMakePaymentTransaction( payment.token, payment.receiver, payment.amount, _paymentId, payment.executions, "" ); } return paid; } function _executePaymentAtLeastOnce(uint256 _paymentId) internal { uint256 paid = _executePayment(_paymentId); if (paid == 0) { if (_nextPaymentTime(_paymentId) <= getTimestamp64()) { revert(ERROR_EXECUTE_PAYMENT_NUM); } else { revert(ERROR_EXECUTE_PAYMENT_TIME); } } } function _makePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { require(_getRemainingBudget(_token) >= _amount, ERROR_REMAINING_BUDGET); _unsafeMakePaymentTransaction(_token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference); } /** * @dev Unsafe version of _makePaymentTransaction that assumes you have already checked the * remaining budget */ function _unsafeMakePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { _recordTransaction( false, _token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference ); vault.transfer(_token, _receiver, _amount); } function _newPeriod(uint64 _startTime) internal returns (Period storage) { // There should be no way for this to overflow since each period is at least one day uint64 newPeriodId = periodsLength++; Period storage period = periods[newPeriodId]; period.startTime = _startTime; // Be careful here to not overflow; if startTime + periodDuration overflows, we set endTime // to MAX_UINT64 (let's assume that's the end of time for now). uint64 endTime = _startTime + settings.periodDuration - 1; if (endTime < _startTime) { // overflowed endTime = MAX_UINT64; } period.endTime = endTime; emit NewPeriod(newPeriodId, period.startTime, period.endTime); return period; } function _recordIncomingTransaction( address _token, address _sender, uint256 _amount, string _reference ) internal { _recordTransaction( true, // incoming transaction _token, _sender, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any existing payment 0, // and no payment executions _reference ); } function _recordTransaction( bool _incoming, address _token, address _entity, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { uint64 periodId = _currentPeriodId(); TokenStatement storage tokenStatement = periods[periodId].tokenStatement[_token]; if (_incoming) { tokenStatement.income = tokenStatement.income.add(_amount); } else { tokenStatement.expenses = tokenStatement.expenses.add(_amount); } uint256 transactionId = transactionsNextIndex++; Transaction storage transaction = transactions[transactionId]; transaction.token = _token; transaction.entity = _entity; transaction.isIncoming = _incoming; transaction.amount = _amount; transaction.paymentId = _paymentId; transaction.paymentExecutionNumber = _paymentExecutionNumber; transaction.date = getTimestamp64(); transaction.periodId = periodId; Period storage period = periods[periodId]; if (period.firstTransactionId == NO_TRANSACTION) { period.firstTransactionId = transactionId; } emit NewTransaction(transactionId, _incoming, _entity, _amount, _reference); } function _tryTransitionAccountingPeriod(uint64 _maxTransitions) internal returns (bool success) { Period storage currentPeriod = periods[_currentPeriodId()]; uint64 timestamp = getTimestamp64(); // Transition periods if necessary while (timestamp > currentPeriod.endTime) { if (_maxTransitions == 0) { // Required number of transitions is over allowed number, return false indicating // it didn't fully transition return false; } // We're already protected from underflowing above _maxTransitions -= 1; // If there were any transactions in period, record which was the last // In case 0 transactions occured, first and last tx id will be 0 if (currentPeriod.firstTransactionId != NO_TRANSACTION) { currentPeriod.lastTransactionId = transactionsNextIndex.sub(1); } // New period starts at end time + 1 currentPeriod = _newPeriod(currentPeriod.endTime.add(1)); } return true; } function _canMakePayment(address _token, uint256 _amount) internal view returns (bool) { return _getRemainingBudget(_token) >= _amount && vault.balance(_token) >= _amount; } function _currentPeriodId() internal view returns (uint64) { // There is no way for this to overflow if protected by an initialization check return periodsLength - 1; } function _getRemainingBudget(address _token) internal view returns (uint256) { if (!settings.hasBudget[_token]) { return MAX_UINT256; } uint256 budget = settings.budgets[_token]; uint256 spent = periods[_currentPeriodId()].tokenStatement[_token].expenses; // A budget decrease can cause the spent amount to be greater than period budget // If so, return 0 to not allow more spending during period if (spent >= budget) { return 0; } // We're already protected from the overflow above return budget - spent; } function _nextPaymentTime(uint256 _paymentId) internal view returns (uint64) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; if (payment.executions >= payment.maxExecutions) { return MAX_UINT64; // re-executes in some billions of years time... should not need to worry } // Split in multiple lines to circumvent linter warning uint64 increase = payment.executions.mul(payment.interval); uint64 nextPayment = payment.initialPaymentTime.add(increase); return nextPayment; } // Syntax sugar function _arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e, uint256 _f) internal pure returns (uint256[] r) { r = new uint256[](6); r[0] = uint256(_a); r[1] = uint256(_b); r[2] = _c; r[3] = _d; r[4] = _e; r[5] = _f; } // Mocked fns (overrided during testing) // Must be view for mocking purposes function getMaxPeriodTransitions() internal view returns (uint64) { return MAX_UINT64; } } // File: @aragon/apps-payroll/contracts/Payroll.sol pragma solidity 0.4.24; /** * @title Payroll in multiple currencies */ contract Payroll is EtherTokenConstant, IForwarder, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; /* Hardcoded constants to save gas * bytes32 constant public ADD_EMPLOYEE_ROLE = keccak256("ADD_EMPLOYEE_ROLE"); * bytes32 constant public TERMINATE_EMPLOYEE_ROLE = keccak256("TERMINATE_EMPLOYEE_ROLE"); * bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = keccak256("SET_EMPLOYEE_SALARY_ROLE"); * bytes32 constant public ADD_BONUS_ROLE = keccak256("ADD_BONUS_ROLE"); * bytes32 constant public ADD_REIMBURSEMENT_ROLE = keccak256("ADD_REIMBURSEMENT_ROLE"); * bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = keccak256("MANAGE_ALLOWED_TOKENS_ROLE"); * bytes32 constant public MODIFY_PRICE_FEED_ROLE = keccak256("MODIFY_PRICE_FEED_ROLE"); * bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = keccak256("MODIFY_RATE_EXPIRY_ROLE"); */ bytes32 constant public ADD_EMPLOYEE_ROLE = 0x9ecdc3c63716b45d0756eece5fe1614cae1889ec5a1ce62b3127c1f1f1615d6e; bytes32 constant public TERMINATE_EMPLOYEE_ROLE = 0x69c67f914d12b6440e7ddf01961214818d9158fbcb19211e0ff42800fdea9242; bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = 0xea9ac65018da2421cf419ee2152371440c08267a193a33ccc1e39545d197e44d; bytes32 constant public ADD_BONUS_ROLE = 0xceca7e2f5eb749a87aaf68f3f76d6b9251aa2f4600f13f93c5a4adf7a72df4ae; bytes32 constant public ADD_REIMBURSEMENT_ROLE = 0x90698b9d54427f1e41636025017309bdb1b55320da960c8845bab0a504b01a16; bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = 0x0be34987c45700ee3fae8c55e270418ba903337decc6bacb1879504be9331c06; bytes32 constant public MODIFY_PRICE_FEED_ROLE = 0x74350efbcba8b85341c5bbf70cc34e2a585fc1463524773a12fa0a71d4eb9302; bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = 0x79fe989a8899060dfbdabb174ebb96616fa9f1d9dadd739f8d814cbab452404e; uint256 internal constant MAX_ALLOWED_TOKENS = 20; // prevent OOG issues with `payday()` uint64 internal constant MIN_RATE_EXPIRY = uint64(1 minutes); // 1 min == ~4 block window to mine both a price feed update and a payout uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); string private constant ERROR_EMPLOYEE_DOESNT_EXIST = "PAYROLL_EMPLOYEE_DOESNT_EXIST"; string private constant ERROR_NON_ACTIVE_EMPLOYEE = "PAYROLL_NON_ACTIVE_EMPLOYEE"; string private constant ERROR_SENDER_DOES_NOT_MATCH = "PAYROLL_SENDER_DOES_NOT_MATCH"; string private constant ERROR_FINANCE_NOT_CONTRACT = "PAYROLL_FINANCE_NOT_CONTRACT"; string private constant ERROR_TOKEN_ALREADY_SET = "PAYROLL_TOKEN_ALREADY_SET"; string private constant ERROR_MAX_ALLOWED_TOKENS = "PAYROLL_MAX_ALLOWED_TOKENS"; string private constant ERROR_MIN_RATES_MISMATCH = "PAYROLL_MIN_RATES_MISMATCH"; string private constant ERROR_TOKEN_ALLOCATION_MISMATCH = "PAYROLL_TOKEN_ALLOCATION_MISMATCH"; string private constant ERROR_NOT_ALLOWED_TOKEN = "PAYROLL_NOT_ALLOWED_TOKEN"; string private constant ERROR_DISTRIBUTION_NOT_FULL = "PAYROLL_DISTRIBUTION_NOT_FULL"; string private constant ERROR_INVALID_PAYMENT_TYPE = "PAYROLL_INVALID_PAYMENT_TYPE"; string private constant ERROR_NOTHING_PAID = "PAYROLL_NOTHING_PAID"; string private constant ERROR_CAN_NOT_FORWARD = "PAYROLL_CAN_NOT_FORWARD"; string private constant ERROR_EMPLOYEE_NULL_ADDRESS = "PAYROLL_EMPLOYEE_NULL_ADDRESS"; string private constant ERROR_EMPLOYEE_ALREADY_EXIST = "PAYROLL_EMPLOYEE_ALREADY_EXIST"; string private constant ERROR_FEED_NOT_CONTRACT = "PAYROLL_FEED_NOT_CONTRACT"; string private constant ERROR_EXPIRY_TIME_TOO_SHORT = "PAYROLL_EXPIRY_TIME_TOO_SHORT"; string private constant ERROR_PAST_TERMINATION_DATE = "PAYROLL_PAST_TERMINATION_DATE"; string private constant ERROR_EXCHANGE_RATE_TOO_LOW = "PAYROLL_EXCHANGE_RATE_TOO_LOW"; string private constant ERROR_LAST_PAYROLL_DATE_TOO_BIG = "PAYROLL_LAST_DATE_TOO_BIG"; string private constant ERROR_INVALID_REQUESTED_AMOUNT = "PAYROLL_INVALID_REQUESTED_AMT"; enum PaymentType { Payroll, Reimbursement, Bonus } struct Employee { address accountAddress; // unique, but can be changed over time uint256 denominationTokenSalary; // salary per second in denomination Token uint256 accruedSalary; // keep track of any leftover accrued salary when changing salaries uint256 bonus; uint256 reimbursements; uint64 lastPayroll; uint64 endDate; address[] allocationTokenAddresses; mapping(address => uint256) allocationTokens; } Finance public finance; address public denominationToken; IFeed public feed; uint64 public rateExpiryTime; // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees uint256 public nextEmployee; mapping(uint256 => Employee) internal employees; // employee ID -> employee mapping(address => uint256) internal employeeIds; // employee address -> employee ID mapping(address => bool) internal allowedTokens; event AddEmployee( uint256 indexed employeeId, address indexed accountAddress, uint256 initialDenominationSalary, uint64 startDate, string role ); event TerminateEmployee(uint256 indexed employeeId, uint64 endDate); event SetEmployeeSalary(uint256 indexed employeeId, uint256 denominationSalary); event AddEmployeeAccruedSalary(uint256 indexed employeeId, uint256 amount); event AddEmployeeBonus(uint256 indexed employeeId, uint256 amount); event AddEmployeeReimbursement(uint256 indexed employeeId, uint256 amount); event ChangeAddressByEmployee(uint256 indexed employeeId, address indexed newAccountAddress, address indexed oldAccountAddress); event DetermineAllocation(uint256 indexed employeeId); event SendPayment( uint256 indexed employeeId, address indexed accountAddress, address indexed token, uint256 amount, uint256 exchangeRate, string paymentReference ); event SetAllowedToken(address indexed token, bool allowed); event SetPriceFeed(address indexed feed); event SetRateExpiryTime(uint64 time); // Check employee exists by ID modifier employeeIdExists(uint256 _employeeId) { require(_employeeExists(_employeeId), ERROR_EMPLOYEE_DOESNT_EXIST); _; } // Check employee exists and is still active modifier employeeActive(uint256 _employeeId) { // No need to check for existence as _isEmployeeIdActive() is false for non-existent employees require(_isEmployeeIdActive(_employeeId), ERROR_NON_ACTIVE_EMPLOYEE); _; } // Check sender matches an existing employee modifier employeeMatches { require(employees[employeeIds[msg.sender]].accountAddress == msg.sender, ERROR_SENDER_DOES_NOT_MATCH); _; } /** * @notice Initialize Payroll app for Finance at `_finance` and price feed at `_priceFeed`, setting denomination token to `_token` and exchange rate expiry time to `@transformTime(_rateExpiryTime)` * @dev Note that we do not require _denominationToken to be a contract, as it may be a "fake" * address used by the price feed to denominate fiat currencies * @param _finance Address of the Finance app this Payroll app will rely on for payments (non-changeable) * @param _denominationToken Address of the denomination token used for salary accounting * @param _priceFeed Address of the price feed * @param _rateExpiryTime Acceptable expiry time in seconds for the price feed's exchange rates */ function initialize(Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime) external onlyInit { initialized(); require(isContract(_finance), ERROR_FINANCE_NOT_CONTRACT); finance = _finance; denominationToken = _denominationToken; _setPriceFeed(_priceFeed); _setRateExpiryTime(_rateExpiryTime); // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees nextEmployee = 1; } /** * @notice `_allowed ? 'Add' : 'Remove'` `_token.symbol(): string` `_allowed ? 'to' : 'from'` the set of allowed tokens * @param _token Address of the token to be added or removed from the list of allowed tokens for payments * @param _allowed Boolean to tell whether the given token should be added or removed from the list */ function setAllowedToken(address _token, bool _allowed) external authP(MANAGE_ALLOWED_TOKENS_ROLE, arr(_token)) { require(allowedTokens[_token] != _allowed, ERROR_TOKEN_ALREADY_SET); allowedTokens[_token] = _allowed; emit SetAllowedToken(_token, _allowed); } /** * @notice Set the price feed for exchange rates to `_feed` * @param _feed Address of the new price feed instance */ function setPriceFeed(IFeed _feed) external authP(MODIFY_PRICE_FEED_ROLE, arr(_feed, feed)) { _setPriceFeed(_feed); } /** * @notice Set the acceptable expiry time for the price feed's exchange rates to `@transformTime(_time)` * @dev Exchange rates older than the given value won't be accepted for payments and will cause payouts to revert * @param _time The expiration time in seconds for exchange rates */ function setRateExpiryTime(uint64 _time) external authP(MODIFY_RATE_EXPIRY_ROLE, arr(uint256(_time), uint256(rateExpiryTime))) { _setRateExpiryTime(_time); } /** * @notice Add employee with address `_accountAddress` to payroll with an salary of `_initialDenominationSalary` per second, starting on `@formatDate(_startDate)` * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds (it actually sets their initial lastPayroll value) * @param _role Employee's role */ function addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) external authP(ADD_EMPLOYEE_ROLE, arr(_accountAddress, _initialDenominationSalary, uint256(_startDate))) { _addEmployee(_accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @notice Add `_amount` to bonus for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's bonuses in denomination token */ function addBonus(uint256 _employeeId, uint256 _amount) external authP(ADD_BONUS_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addBonus(_employeeId, _amount); } /** * @notice Add `_amount` to reimbursements for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's reimbursements in denomination token */ function addReimbursement(uint256 _employeeId, uint256 _amount) external authP(ADD_REIMBURSEMENT_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addReimbursement(_employeeId, _amount); } /** * @notice Set employee #`_employeeId`'s salary to `_denominationSalary` per second * @dev This reverts if either the employee's owed salary or accrued salary overflows, to avoid * losing any accrued salary for an employee due to the employer changing their salary. * @param _employeeId Employee's identifier * @param _denominationSalary Employee's new salary, per second in denomination token */ function setEmployeeSalary(uint256 _employeeId, uint256 _denominationSalary) external authP(SET_EMPLOYEE_SALARY_ROLE, arr(_employeeId, _denominationSalary, employees[_employeeId].denominationTokenSalary)) employeeActive(_employeeId) { Employee storage employee = employees[_employeeId]; // Accrue employee's owed salary; don't cap to revert on overflow uint256 owed = _getOwedSalarySinceLastPayroll(employee, false); _addAccruedSalary(_employeeId, owed); // Update employee to track the new salary and payment date employee.lastPayroll = getTimestamp64(); employee.denominationTokenSalary = _denominationSalary; emit SetEmployeeSalary(_employeeId, _denominationSalary); } /** * @notice Terminate employee #`_employeeId` on `@formatDate(_endDate)` * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function terminateEmployee(uint256 _employeeId, uint64 _endDate) external authP(TERMINATE_EMPLOYEE_ROLE, arr(_employeeId, uint256(_endDate))) employeeActive(_employeeId) { _terminateEmployee(_employeeId, _endDate); } /** * @notice Change your employee account address to `_newAccountAddress` * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _newAccountAddress New address to receive payments for the requesting employee */ function changeAddressByEmployee(address _newAccountAddress) external employeeMatches nonReentrant { uint256 employeeId = employeeIds[msg.sender]; address oldAddress = employees[employeeId].accountAddress; _setEmployeeAddress(employeeId, _newAccountAddress); // Don't delete the old address until after setting the new address to check that the // employee specified a new address delete employeeIds[oldAddress]; emit ChangeAddressByEmployee(employeeId, _newAccountAddress, oldAddress); } /** * @notice Set the token distribution for your payments * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _tokens Array of token addresses; they must belong to the list of allowed tokens * @param _distribution Array with each token's corresponding proportions (must be integers summing to 100) */ function determineAllocation(address[] _tokens, uint256[] _distribution) external employeeMatches nonReentrant { // Check array lengthes match require(_tokens.length <= MAX_ALLOWED_TOKENS, ERROR_MAX_ALLOWED_TOKENS); require(_tokens.length == _distribution.length, ERROR_TOKEN_ALLOCATION_MISMATCH); uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; // Delete previous token allocations address[] memory previousAllowedTokenAddresses = employee.allocationTokenAddresses; for (uint256 j = 0; j < previousAllowedTokenAddresses.length; j++) { delete employee.allocationTokens[previousAllowedTokenAddresses[j]]; } delete employee.allocationTokenAddresses; // Set distributions only if given tokens are allowed for (uint256 i = 0; i < _tokens.length; i++) { employee.allocationTokenAddresses.push(_tokens[i]); employee.allocationTokens[_tokens[i]] = _distribution[i]; } _ensureEmployeeTokenAllocationsIsValid(employee); emit DetermineAllocation(employeeId); } /** * @notice Request your `_type == 0 ? 'salary' : _type == 1 ? 'reimbursements' : 'bonus'` * @dev Reverts if no payments were made. * Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _type Payment type being requested (Payroll, Reimbursement or Bonus) * @param _requestedAmount Requested amount to pay for the payment type. Must be less than or equal to total owed amount for the payment type, or zero to request all. * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens */ function payday(PaymentType _type, uint256 _requestedAmount, uint256[] _minRates) external employeeMatches nonReentrant { uint256 paymentAmount; uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; _ensureEmployeeTokenAllocationsIsValid(employee); require(_minRates.length == 0 || _minRates.length == employee.allocationTokenAddresses.length, ERROR_MIN_RATES_MISMATCH); // Do internal employee accounting if (_type == PaymentType.Payroll) { // Salary is capped here to avoid reverting at this point if it becomes too big // (so employees aren't DDOSed if their salaries get too large) // If we do use a capped value, the employee's lastPayroll date will be adjusted accordingly uint256 totalOwedSalary = _getTotalOwedCappedSalary(employee); paymentAmount = _ensurePaymentAmount(totalOwedSalary, _requestedAmount); _updateEmployeeAccountingBasedOnPaidSalary(employee, paymentAmount); } else if (_type == PaymentType.Reimbursement) { uint256 owedReimbursements = employee.reimbursements; paymentAmount = _ensurePaymentAmount(owedReimbursements, _requestedAmount); employee.reimbursements = owedReimbursements.sub(paymentAmount); } else if (_type == PaymentType.Bonus) { uint256 owedBonusAmount = employee.bonus; paymentAmount = _ensurePaymentAmount(owedBonusAmount, _requestedAmount); employee.bonus = owedBonusAmount.sub(paymentAmount); } else { revert(ERROR_INVALID_PAYMENT_TYPE); } // Actually transfer the owed funds require(_transferTokensAmount(employeeId, _type, paymentAmount, _minRates), ERROR_NOTHING_PAID); _removeEmployeeIfTerminatedAndPaidOut(employeeId); } // Forwarding fns /** * @dev IForwarder interface conformance. Tells whether the Payroll app is a forwarder or not. * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as an active employee * @dev IForwarder interface conformance. Allows active employees to run EVMScripts in the context of the Payroll app. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the Finance app to the blacklist to disallow employees from executing actions on the // Finance app from Payroll's context (since Payroll requires permissions on Finance) address[] memory blacklist = new address[](1); blacklist[0] = address(finance); runScript(_evmScript, input, blacklist); } /** * @dev IForwarder interface conformance. Tells whether a given address can forward actions or not. * @param _sender Address of the account intending to forward an action * @return True if the given address is an active employee, false otherwise */ function canForward(address _sender, bytes) public view returns (bool) { return _isEmployeeIdActive(employeeIds[_sender]); } // Getter fns /** * @dev Return employee's identifier by their account address * @param _accountAddress Employee's address to receive payments * @return Employee's identifier */ function getEmployeeIdByAddress(address _accountAddress) public view returns (uint256) { require(employeeIds[_accountAddress] != uint256(0), ERROR_EMPLOYEE_DOESNT_EXIST); return employeeIds[_accountAddress]; } /** * @dev Return all information for employee by their ID * @param _employeeId Employee's identifier * @return Employee's address to receive payments * @return Employee's salary, per second in denomination token * @return Employee's accrued salary * @return Employee's bonus amount * @return Employee's reimbursements amount * @return Employee's last payment date * @return Employee's termination date (max uint64 if none) * @return Employee's allowed payment tokens */ function getEmployee(uint256 _employeeId) public view employeeIdExists(_employeeId) returns ( address accountAddress, uint256 denominationSalary, uint256 accruedSalary, uint256 bonus, uint256 reimbursements, uint64 lastPayroll, uint64 endDate, address[] allocationTokens ) { Employee storage employee = employees[_employeeId]; accountAddress = employee.accountAddress; denominationSalary = employee.denominationTokenSalary; accruedSalary = employee.accruedSalary; bonus = employee.bonus; reimbursements = employee.reimbursements; lastPayroll = employee.lastPayroll; endDate = employee.endDate; allocationTokens = employee.allocationTokenAddresses; } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function getTotalOwedSalary(uint256 _employeeId) public view employeeIdExists(_employeeId) returns (uint256) { return _getTotalOwedCappedSalary(employees[_employeeId]); } /** * @dev Get an employee's payment allocation for a token * @param _employeeId Employee's identifier * @param _token Token to query the payment allocation for * @return Employee's payment allocation for the token being queried */ function getAllocation(uint256 _employeeId, address _token) public view employeeIdExists(_employeeId) returns (uint256) { return employees[_employeeId].allocationTokens[_token]; } /** * @dev Check if a token is allowed to be used for payments * @param _token Address of the token to be checked * @return True if the given token is allowed, false otherwise */ function isTokenAllowed(address _token) public view isInitialized returns (bool) { return allowedTokens[_token]; } // Internal fns /** * @dev Set the price feed used for exchange rates * @param _feed Address of the new price feed instance */ function _setPriceFeed(IFeed _feed) internal { require(isContract(_feed), ERROR_FEED_NOT_CONTRACT); feed = _feed; emit SetPriceFeed(feed); } /** * @dev Set the exchange rate expiry time in seconds. * Exchange rates older than the given value won't be accepted for payments and will cause * payouts to revert. * @param _time The expiration time in seconds for exchange rates */ function _setRateExpiryTime(uint64 _time) internal { // Require a sane minimum for the rate expiry time require(_time >= MIN_RATE_EXPIRY, ERROR_EXPIRY_TIME_TOO_SHORT); rateExpiryTime = _time; emit SetRateExpiryTime(rateExpiryTime); } /** * @dev Add a new employee to Payroll * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds * @param _role Employee's role */ function _addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) internal { uint256 employeeId = nextEmployee++; _setEmployeeAddress(employeeId, _accountAddress); Employee storage employee = employees[employeeId]; employee.denominationTokenSalary = _initialDenominationSalary; employee.lastPayroll = _startDate; employee.endDate = MAX_UINT64; emit AddEmployee(employeeId, _accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @dev Add amount to an employee's bonuses * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's bonuses in denomination token */ function _addBonus(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.bonus = employee.bonus.add(_amount); emit AddEmployeeBonus(_employeeId, _amount); } /** * @dev Add amount to an employee's reimbursements * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's reimbursements in denomination token */ function _addReimbursement(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.reimbursements = employee.reimbursements.add(_amount); emit AddEmployeeReimbursement(_employeeId, _amount); } /** * @dev Add amount to an employee's accrued salary * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's accrued salary in denomination token */ function _addAccruedSalary(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.accruedSalary = employee.accruedSalary.add(_amount); emit AddEmployeeAccruedSalary(_employeeId, _amount); } /** * @dev Set an employee's account address * @param _employeeId Employee's identifier * @param _accountAddress Employee's address to receive payroll */ function _setEmployeeAddress(uint256 _employeeId, address _accountAddress) internal { // Check address is non-null require(_accountAddress != address(0), ERROR_EMPLOYEE_NULL_ADDRESS); // Check address isn't already being used require(employeeIds[_accountAddress] == uint256(0), ERROR_EMPLOYEE_ALREADY_EXIST); employees[_employeeId].accountAddress = _accountAddress; // Create IDs mapping employeeIds[_accountAddress] = _employeeId; } /** * @dev Terminate employee on end date * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function _terminateEmployee(uint256 _employeeId, uint64 _endDate) internal { // Prevent past termination dates require(_endDate >= getTimestamp64(), ERROR_PAST_TERMINATION_DATE); employees[_employeeId].endDate = _endDate; emit TerminateEmployee(_employeeId, _endDate); } /** * @dev Loop over allowed tokens to send requested amount to the employee in their desired allocation * @param _employeeId Employee's identifier * @param _totalAmount Total amount to be transferred to the employee distributed in accordance to the employee's token allocation. * @param _type Payment type being transferred (Payroll, Reimbursement or Bonus) * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens * @return True if there was at least one token transfer */ function _transferTokensAmount(uint256 _employeeId, PaymentType _type, uint256 _totalAmount, uint256[] _minRates) internal returns (bool somethingPaid) { if (_totalAmount == 0) { return false; } Employee storage employee = employees[_employeeId]; address employeeAddress = employee.accountAddress; string memory paymentReference = _paymentReferenceFor(_type); address[] storage allocationTokenAddresses = employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; uint256 tokenAllocation = employee.allocationTokens[token]; if (tokenAllocation != uint256(0)) { // Get the exchange rate for the payout token in denomination token, // as we do accounting in denomination tokens uint256 exchangeRate = _getExchangeRateInDenominationToken(token); require(_minRates.length > 0 ? exchangeRate >= _minRates[i] : exchangeRate > 0, ERROR_EXCHANGE_RATE_TOO_LOW); // Convert amount (in denomination tokens) to payout token and apply allocation uint256 tokenAmount = _totalAmount.mul(exchangeRate).mul(tokenAllocation); // Divide by 100 for the allocation percentage and by the exchange rate precision tokenAmount = tokenAmount.div(100).div(feed.ratePrecision()); // Finance reverts if the payment wasn't possible finance.newImmediatePayment(token, employeeAddress, tokenAmount, paymentReference); emit SendPayment(_employeeId, employeeAddress, token, tokenAmount, exchangeRate, paymentReference); somethingPaid = true; } } } /** * @dev Remove employee if there are no owed funds and employee's end date has been reached * @param _employeeId Employee's identifier */ function _removeEmployeeIfTerminatedAndPaidOut(uint256 _employeeId) internal { Employee storage employee = employees[_employeeId]; if ( employee.lastPayroll == employee.endDate && (employee.accruedSalary == 0 && employee.bonus == 0 && employee.reimbursements == 0) ) { delete employeeIds[employee.accountAddress]; delete employees[_employeeId]; } } /** * @dev Updates the accrued salary and payroll date of an employee based on a payment amount and * their currently owed salary since last payroll date * @param _employee Employee struct in storage * @param _paymentAmount Amount being paid to the employee */ function _updateEmployeeAccountingBasedOnPaidSalary(Employee storage _employee, uint256 _paymentAmount) internal { uint256 accruedSalary = _employee.accruedSalary; if (_paymentAmount <= accruedSalary) { // Employee is only cashing out some previously owed salary so we don't need to update // their last payroll date // No need to use SafeMath as we already know _paymentAmount <= accruedSalary _employee.accruedSalary = accruedSalary - _paymentAmount; return; } // Employee is cashing out some of their currently owed salary so their last payroll date // needs to be modified based on the amount of salary paid uint256 currentSalaryPaid = _paymentAmount; if (accruedSalary > 0) { // Employee is cashing out a mixed amount between previous and current owed salaries; // first use up their accrued salary // No need to use SafeMath here as we already know _paymentAmount > accruedSalary currentSalaryPaid = _paymentAmount - accruedSalary; // We finally need to clear their accrued salary _employee.accruedSalary = 0; } uint256 salary = _employee.denominationTokenSalary; uint256 timeDiff = currentSalaryPaid.div(salary); // If they're being paid an amount that doesn't match perfectly with the adjusted time // (up to a seconds' worth of salary), add the second and put the extra remaining salary // into their accrued salary uint256 extraSalary = currentSalaryPaid % salary; if (extraSalary > 0) { timeDiff = timeDiff.add(1); _employee.accruedSalary = salary - extraSalary; } uint256 lastPayrollDate = uint256(_employee.lastPayroll).add(timeDiff); // Even though this function should never receive a currentSalaryPaid value that would // result in the lastPayrollDate being higher than the current time, // let's double check to be safe require(lastPayrollDate <= uint256(getTimestamp64()), ERROR_LAST_PAYROLL_DATE_TOO_BIG); // Already know lastPayrollDate must fit in uint64 from above _employee.lastPayroll = uint64(lastPayrollDate); } /** * @dev Tell whether an employee is registered in this Payroll or not * @param _employeeId Employee's identifier * @return True if the given employee ID belongs to an registered employee, false otherwise */ function _employeeExists(uint256 _employeeId) internal view returns (bool) { return employees[_employeeId].accountAddress != address(0); } /** * @dev Tell whether an employee has a valid token allocation or not. * A valid allocation is one that sums to 100 and only includes allowed tokens. * @param _employee Employee struct in storage * @return Reverts if employee's allocation is invalid */ function _ensureEmployeeTokenAllocationsIsValid(Employee storage _employee) internal view { uint256 sum = 0; address[] memory allocationTokenAddresses = _employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; require(allowedTokens[token], ERROR_NOT_ALLOWED_TOKEN); sum = sum.add(_employee.allocationTokens[token]); } require(sum == 100, ERROR_DISTRIBUTION_NOT_FULL); } /** * @dev Tell whether an employee is still active or not * @param _employee Employee struct in storage * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeActive(Employee storage _employee) internal view returns (bool) { return _employee.endDate >= getTimestamp64(); } /** * @dev Tell whether an employee id is still active or not * @param _employeeId Employee's identifier * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeIdActive(uint256 _employeeId) internal view returns (bool) { return _isEmployeeActive(employees[_employeeId]); } /** * @dev Get exchange rate for a token based on the denomination token. * As an example, if the denomination token was USD and ETH's price was 100USD, * this would return 0.01 * precision rate for ETH. * @param _token Token to get price of in denomination tokens * @return Exchange rate (multiplied by the PPF rate precision) */ function _getExchangeRateInDenominationToken(address _token) internal view returns (uint256) { // xrt is the number of `_token` that can be exchanged for one `denominationToken` (uint128 xrt, uint64 when) = feed.get( denominationToken, // Base (e.g. USD) _token // Quote (e.g. ETH) ); // Check the price feed is recent enough if (getTimestamp64().sub(when) >= rateExpiryTime) { return 0; } return uint256(xrt); } /** * @dev Get owed salary since last payroll for an employee * @param _employee Employee struct in storage * @param _capped Safely cap the owed salary at max uint * @return Owed salary in denomination tokens since last payroll for the employee. * If _capped is false, it reverts in case of an overflow. */ function _getOwedSalarySinceLastPayroll(Employee storage _employee, bool _capped) internal view returns (uint256) { uint256 timeDiff = _getOwedPayrollPeriod(_employee); if (timeDiff == 0) { return 0; } uint256 salary = _employee.denominationTokenSalary; if (_capped) { // Return max uint if the result overflows uint256 result = salary * timeDiff; return (result / timeDiff != salary) ? MAX_UINT256 : result; } else { return salary.mul(timeDiff); } } /** * @dev Get owed payroll period for an employee * @param _employee Employee struct in storage * @return Owed time in seconds since the employee's last payroll date */ function _getOwedPayrollPeriod(Employee storage _employee) internal view returns (uint256) { // Get the min of current date and termination date uint64 date = _isEmployeeActive(_employee) ? getTimestamp64() : _employee.endDate; // Make sure we don't revert if we try to get the owed salary for an employee whose last // payroll date is now or in the future // This can happen either by adding new employees with start dates in the future, to allow // us to change their salary before their start date, or by terminating an employee and // paying out their full owed salary if (date <= _employee.lastPayroll) { return 0; } // Return time diff in seconds, no need to use SafeMath as the underflow was covered by the previous check return uint256(date - _employee.lastPayroll); } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @param _employee Employee struct in storage * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function _getTotalOwedCappedSalary(Employee storage _employee) internal view returns (uint256) { uint256 currentOwedSalary = _getOwedSalarySinceLastPayroll(_employee, true); // cap amount uint256 totalOwedSalary = currentOwedSalary + _employee.accruedSalary; if (totalOwedSalary < currentOwedSalary) { totalOwedSalary = MAX_UINT256; } return totalOwedSalary; } /** * @dev Get payment reference for a given payment type * @param _type Payment type to query the reference of * @return Payment reference for the given payment type */ function _paymentReferenceFor(PaymentType _type) internal pure returns (string memory) { if (_type == PaymentType.Payroll) { return "Employee salary"; } else if (_type == PaymentType.Reimbursement) { return "Employee reimbursement"; } if (_type == PaymentType.Bonus) { return "Employee bonus"; } revert(ERROR_INVALID_PAYMENT_TYPE); } function _ensurePaymentAmount(uint256 _owedAmount, uint256 _requestedAmount) private pure returns (uint256) { require(_owedAmount > 0, ERROR_NOTHING_PAID); require(_owedAmount >= _requestedAmount, ERROR_INVALID_REQUESTED_AMOUNT); return _requestedAmount > 0 ? _requestedAmount : _owedAmount; } } // File: @aragon/apps-token-manager/contracts/TokenManager.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ /* solium-disable function-order */ pragma solidity 0.4.24; contract TokenManager is ITokenController, IForwarder, AragonApp { using SafeMath for uint256; bytes32 public constant MINT_ROLE = keccak256("MINT_ROLE"); bytes32 public constant ISSUE_ROLE = keccak256("ISSUE_ROLE"); bytes32 public constant ASSIGN_ROLE = keccak256("ASSIGN_ROLE"); bytes32 public constant REVOKE_VESTINGS_ROLE = keccak256("REVOKE_VESTINGS_ROLE"); bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE"); uint256 public constant MAX_VESTINGS_PER_ADDRESS = 50; string private constant ERROR_CALLER_NOT_TOKEN = "TM_CALLER_NOT_TOKEN"; string private constant ERROR_NO_VESTING = "TM_NO_VESTING"; string private constant ERROR_TOKEN_CONTROLLER = "TM_TOKEN_CONTROLLER"; string private constant ERROR_MINT_RECEIVER_IS_TM = "TM_MINT_RECEIVER_IS_TM"; string private constant ERROR_VESTING_TO_TM = "TM_VESTING_TO_TM"; string private constant ERROR_TOO_MANY_VESTINGS = "TM_TOO_MANY_VESTINGS"; string private constant ERROR_WRONG_CLIFF_DATE = "TM_WRONG_CLIFF_DATE"; string private constant ERROR_VESTING_NOT_REVOKABLE = "TM_VESTING_NOT_REVOKABLE"; string private constant ERROR_REVOKE_TRANSFER_FROM_REVERTED = "TM_REVOKE_TRANSFER_FROM_REVERTED"; string private constant ERROR_CAN_NOT_FORWARD = "TM_CAN_NOT_FORWARD"; string private constant ERROR_BALANCE_INCREASE_NOT_ALLOWED = "TM_BALANCE_INC_NOT_ALLOWED"; string private constant ERROR_ASSIGN_TRANSFER_FROM_REVERTED = "TM_ASSIGN_TRANSFER_FROM_REVERTED"; struct TokenVesting { uint256 amount; uint64 start; uint64 cliff; uint64 vesting; bool revokable; } // Note that we COMPLETELY trust this MiniMeToken to not be malicious for proper operation of this contract MiniMeToken public token; uint256 public maxAccountTokens; // We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful mapping (address => mapping (uint256 => TokenVesting)) internal vestings; mapping (address => uint256) public vestingsLengths; // Other token specific events can be watched on the token address directly (avoids duplication) event NewVesting(address indexed receiver, uint256 vestingId, uint256 amount); event RevokeVesting(address indexed receiver, uint256 vestingId, uint256 nonVestedAmount); modifier onlyToken() { require(msg.sender == address(token), ERROR_CALLER_NOT_TOKEN); _; } modifier vestingExists(address _holder, uint256 _vestingId) { // TODO: it's not checking for gaps that may appear because of deletes in revokeVesting function require(_vestingId < vestingsLengths[_holder], ERROR_NO_VESTING); _; } /** * @notice Initialize Token Manager for `_token.symbol(): string`, whose tokens are `transferable ? 'not' : ''` transferable`_maxAccountTokens > 0 ? ' and limited to a maximum of ' + @tokenAmount(_token, _maxAccountTokens, false) + ' per account' : ''` * @param _token MiniMeToken address for the managed token (Token Manager instance must be already set as the token controller) * @param _transferable whether the token can be transferred by holders * @param _maxAccountTokens Maximum amount of tokens an account can have (0 for infinite tokens) */ function initialize( MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) external onlyInit { initialized(); require(_token.controller() == address(this), ERROR_TOKEN_CONTROLLER); token = _token; maxAccountTokens = _maxAccountTokens == 0 ? uint256(-1) : _maxAccountTokens; if (token.transfersEnabled() != _transferable) { token.enableTransfers(_transferable); } } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for `_receiver` * @param _receiver The address receiving the tokens, cannot be the Token Manager itself (use `issue()` instead) * @param _amount Number of tokens minted */ function mint(address _receiver, uint256 _amount) external authP(MINT_ROLE, arr(_receiver, _amount)) { require(_receiver != address(this), ERROR_MINT_RECEIVER_IS_TM); _mint(_receiver, _amount); } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for the Token Manager * @param _amount Number of tokens minted */ function issue(uint256 _amount) external authP(ISSUE_ROLE, arr(_amount)) { _mint(address(this), _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings * @param _receiver The address receiving the tokens * @param _amount Number of tokens transferred */ function assign(address _receiver, uint256 _amount) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) { _assign(_receiver, _amount); } /** * @notice Burn `@tokenAmount(self.token(): address, _amount, false)` tokens from `_holder` * @param _holder Holder of tokens being burned * @param _amount Number of tokens being burned */ function burn(address _holder, uint256 _amount) external authP(BURN_ROLE, arr(_holder, _amount)) { // minime.destroyTokens() never returns false, only reverts on failure token.destroyTokens(_holder, _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings with a `_revokable : 'revokable' : ''` vesting starting at `@formatDate(_start)`, cliff at `@formatDate(_cliff)` (first portion of tokens transferable), and completed vesting at `@formatDate(_vested)` (all tokens transferable) * @param _receiver The address receiving the tokens, cannot be Token Manager itself * @param _amount Number of tokens vested * @param _start Date the vesting calculations start * @param _cliff Date when the initial portion of tokens are transferable * @param _vested Date when all tokens are transferable * @param _revokable Whether the vesting can be revoked by the Token Manager */ function assignVested( address _receiver, uint256 _amount, uint64 _start, uint64 _cliff, uint64 _vested, bool _revokable ) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) returns (uint256) { require(_receiver != address(this), ERROR_VESTING_TO_TM); require(vestingsLengths[_receiver] < MAX_VESTINGS_PER_ADDRESS, ERROR_TOO_MANY_VESTINGS); require(_start <= _cliff && _cliff <= _vested, ERROR_WRONG_CLIFF_DATE); uint256 vestingId = vestingsLengths[_receiver]++; vestings[_receiver][vestingId] = TokenVesting( _amount, _start, _cliff, _vested, _revokable ); _assign(_receiver, _amount); emit NewVesting(_receiver, vestingId, _amount); return vestingId; } /** * @notice Revoke vesting #`_vestingId` from `_holder`, returning unvested tokens to the Token Manager * @param _holder Address whose vesting to revoke * @param _vestingId Numeric id of the vesting */ function revokeVesting(address _holder, uint256 _vestingId) external authP(REVOKE_VESTINGS_ROLE, arr(_holder)) vestingExists(_holder, _vestingId) { TokenVesting storage v = vestings[_holder][_vestingId]; require(v.revokable, ERROR_VESTING_NOT_REVOKABLE); uint256 nonVested = _calculateNonVestedTokens( v.amount, getTimestamp(), v.start, v.cliff, v.vesting ); // To make vestingIds immutable over time, we just zero out the revoked vesting // Clearing this out also allows the token transfer back to the Token Manager to succeed delete vestings[_holder][_vestingId]; // transferFrom always works as controller // onTransfer hook always allows if transfering to token controller require(token.transferFrom(_holder, address(this), nonVested), ERROR_REVOKE_TRANSFER_FROM_REVERTED); emit RevokeVesting(_holder, _vestingId, nonVested); } // ITokenController fns // `onTransfer()`, `onApprove()`, and `proxyPayment()` are callbacks from the MiniMe token // contract and are only meant to be called through the managed MiniMe token that gets assigned // during initialization. /* * @dev Notifies the controller about a token transfer allowing the controller to decide whether * to allow it or react if desired (only callable from the token). * Initialization check is implicitly provided by `onlyToken()`. * @param _from The origin of the transfer * @param _to The destination of the transfer * @param _amount The amount of the transfer * @return False if the controller does not authorize the transfer */ function onTransfer(address _from, address _to, uint256 _amount) external onlyToken returns (bool) { return _isBalanceIncreaseAllowed(_to, _amount) && _transferableBalance(_from, getTimestamp()) >= _amount; } /** * @dev Notifies the controller about an approval allowing the controller to react if desired * Initialization check is implicitly provided by `onlyToken()`. * @return False if the controller does not authorize the approval */ function onApprove(address, address, uint) external onlyToken returns (bool) { return true; } /** * @dev Called when ether is sent to the MiniMe Token contract * Initialization check is implicitly provided by `onlyToken()`. * @return True if the ether is accepted, false for it to throw */ function proxyPayment(address) external payable onlyToken returns (bool) { return false; } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as a token holder * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the managed token to the blacklist to disallow a token holder from executing actions // on the token controller's (this contract) behalf address[] memory blacklist = new address[](1); blacklist[0] = address(token); runScript(_evmScript, input, blacklist); } function canForward(address _sender, bytes) public view returns (bool) { return hasInitialized() && token.balanceOf(_sender) > 0; } // Getter fns function getVesting( address _recipient, uint256 _vestingId ) public view vestingExists(_recipient, _vestingId) returns ( uint256 amount, uint64 start, uint64 cliff, uint64 vesting, bool revokable ) { TokenVesting storage tokenVesting = vestings[_recipient][_vestingId]; amount = tokenVesting.amount; start = tokenVesting.start; cliff = tokenVesting.cliff; vesting = tokenVesting.vesting; revokable = tokenVesting.revokable; } function spendableBalanceOf(address _holder) public view isInitialized returns (uint256) { return _transferableBalance(_holder, getTimestamp()); } function transferableBalance(address _holder, uint256 _time) public view isInitialized returns (uint256) { return _transferableBalance(_holder, _time); } /** * @dev Disable recovery escape hatch for own token, * as the it has the concept of issuing tokens without assigning them */ function allowRecoverability(address _token) public view returns (bool) { return _token != address(token); } // Internal fns function _assign(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); // Must use transferFrom() as transfer() does not give the token controller full control require(token.transferFrom(address(this), _receiver, _amount), ERROR_ASSIGN_TRANSFER_FROM_REVERTED); } function _mint(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); token.generateTokens(_receiver, _amount); // minime.generateTokens() never returns false } function _isBalanceIncreaseAllowed(address _receiver, uint256 _inc) internal view returns (bool) { // Max balance doesn't apply to the token manager itself if (_receiver == address(this)) { return true; } return token.balanceOf(_receiver).add(_inc) <= maxAccountTokens; } /** * @dev Calculate amount of non-vested tokens at a specifc time * @param tokens The total amount of tokens vested * @param time The time at which to check * @param start The date vesting started * @param cliff The cliff period * @param vested The fully vested date * @return The amount of non-vested tokens of a specific grant * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Cliff Vested */ function _calculateNonVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vested ) private pure returns (uint256) { // Shortcuts for before cliff and after vested cases. if (time >= vested) { return 0; } if (time < cliff) { return tokens; } // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vested - start) // In assignVesting we enforce start <= cliff <= vested // Here we shortcut time >= vested and time < cliff, // so no division by 0 is possible uint256 vestedTokens = tokens.mul(time.sub(start)) / vested.sub(start); // tokens - vestedTokens return tokens.sub(vestedTokens); } function _transferableBalance(address _holder, uint256 _time) internal view returns (uint256) { uint256 transferable = token.balanceOf(_holder); // This check is not strictly necessary for the current version of this contract, as // Token Managers now cannot assign vestings to themselves. // However, this was a possibility in the past, so in case there were vestings assigned to // themselves, this will still return the correct value (entire balance, as the Token // Manager does not have a spending limit on its own balance). if (_holder != address(this)) { uint256 vestingsCount = vestingsLengths[_holder]; for (uint256 i = 0; i < vestingsCount; i++) { TokenVesting storage v = vestings[_holder][i]; uint256 nonTransferable = _calculateNonVestedTokens( v.amount, _time, v.start, v.cliff, v.vesting ); transferable = transferable.sub(nonTransferable); } } return transferable; } } // File: @aragon/apps-survey/contracts/Survey.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Survey is AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_SURVEYS_ROLE = keccak256("CREATE_SURVEYS_ROLE"); bytes32 public constant MODIFY_PARTICIPATION_ROLE = keccak256("MODIFY_PARTICIPATION_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 uint256 public constant ABSTAIN_VOTE = 0; string private constant ERROR_MIN_PARTICIPATION = "SURVEY_MIN_PARTICIPATION"; string private constant ERROR_NO_SURVEY = "SURVEY_NO_SURVEY"; string private constant ERROR_NO_VOTING_POWER = "SURVEY_NO_VOTING_POWER"; string private constant ERROR_CAN_NOT_VOTE = "SURVEY_CAN_NOT_VOTE"; string private constant ERROR_VOTE_WRONG_INPUT = "SURVEY_VOTE_WRONG_INPUT"; string private constant ERROR_VOTE_WRONG_OPTION = "SURVEY_VOTE_WRONG_OPTION"; string private constant ERROR_NO_STAKE = "SURVEY_NO_STAKE"; string private constant ERROR_OPTIONS_NOT_ORDERED = "SURVEY_OPTIONS_NOT_ORDERED"; string private constant ERROR_NO_OPTION = "SURVEY_NO_OPTION"; struct OptionCast { uint256 optionId; uint256 stake; } /* Allows for multiple option votes. * Index 0 is always used for the ABSTAIN_VOTE option, that's calculated automatically by the * contract. */ struct MultiOptionVote { uint256 optionsCastedLength; // `castedVotes` simulates an array // Each OptionCast in `castedVotes` must be ordered by ascending option IDs mapping (uint256 => OptionCast) castedVotes; } struct SurveyStruct { uint64 startDate; uint64 snapshotBlock; uint64 minParticipationPct; uint256 options; uint256 votingPower; // total tokens that can cast a vote uint256 participation; // tokens that casted a vote // Note that option IDs are from 1 to `options`, due to ABSTAIN_VOTE taking 0 mapping (uint256 => uint256) optionPower; // option ID -> voting power for option mapping (address => MultiOptionVote) votes; // voter -> options voted, with its stakes } MiniMeToken public token; uint64 public minParticipationPct; uint64 public surveyTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => SurveyStruct) internal surveys; uint256 public surveysLength; event StartSurvey(uint256 indexed surveyId, address indexed creator, string metadata); event CastVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 stake, uint256 optionPower); event ResetVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 previousStake, uint256 optionPower); event ChangeMinParticipation(uint64 minParticipationPct); modifier acceptableMinParticipationPct(uint64 _minParticipationPct) { require(_minParticipationPct > 0 && _minParticipationPct <= PCT_BASE, ERROR_MIN_PARTICIPATION); _; } modifier surveyExists(uint256 _surveyId) { require(_surveyId < surveysLength, ERROR_NO_SURVEY); _; } /** * @notice Initialize Survey app with `_token.symbol(): string` for governance, minimum acceptance participation of `@formatPct(_minParticipationPct)`%, and a voting duration of `@transformTime(_surveyTime)` * @param _token MiniMeToken address that will be used as governance token * @param _minParticipationPct Percentage of total voting power that must participate in a survey for it to be taken into account (expressed as a 10^18 percentage, (eg 10^16 = 1%, 10^18 = 100%) * @param _surveyTime Seconds that a survey will be open for token holders to vote */ function initialize( MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime ) external onlyInit acceptableMinParticipationPct(_minParticipationPct) { initialized(); token = _token; minParticipationPct = _minParticipationPct; surveyTime = _surveyTime; } /** * @notice Change minimum acceptance participation to `@formatPct(_minParticipationPct)`% * @param _minParticipationPct New acceptance participation */ function changeMinAcceptParticipationPct(uint64 _minParticipationPct) external authP(MODIFY_PARTICIPATION_ROLE, arr(uint256(_minParticipationPct), uint256(minParticipationPct))) acceptableMinParticipationPct(_minParticipationPct) { minParticipationPct = _minParticipationPct; emit ChangeMinParticipation(_minParticipationPct); } /** * @notice Create a new non-binding survey about "`_metadata`" * @param _metadata Survey metadata * @param _options Number of options voters can decide between * @return surveyId id for newly created survey */ function newSurvey(string _metadata, uint256 _options) external auth(CREATE_SURVEYS_ROLE) returns (uint256 surveyId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); surveyId = surveysLength++; SurveyStruct storage survey = surveys[surveyId]; survey.startDate = getTimestamp64(); survey.snapshotBlock = snapshotBlock; // avoid double voting in this very block survey.minParticipationPct = minParticipationPct; survey.options = _options; survey.votingPower = votingPower; emit StartSurvey(surveyId, msg.sender, _metadata); } /** * @notice Reset previously casted vote in survey #`_surveyId`, if any. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey */ function resetVote(uint256 _surveyId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _resetVote(_surveyId); } /** * @notice Vote for multiple options in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey * @param _optionIds Array with indexes of supported options * @param _stakes Number of tokens assigned to each option */ function voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) external surveyExists(_surveyId) { require(_optionIds.length == _stakes.length && _optionIds.length > 0, ERROR_VOTE_WRONG_INPUT); require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _voteOptions(_surveyId, _optionIds, _stakes); } /** * @notice Vote option #`_optionId` in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @dev It will use the whole balance. * @param _surveyId Id for survey * @param _optionId Index of supported option */ function voteOption(uint256 _surveyId, uint256 _optionId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); SurveyStruct storage survey = surveys[_surveyId]; // This could re-enter, though we can asume the governance token is not maliciuous uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256[] memory options = new uint256[](1); uint256[] memory stakes = new uint256[](1); options[0] = _optionId; stakes[0] = voterStake; _voteOptions(_surveyId, options, stakes); } // Getter fns function canVote(uint256 _surveyId, address _voter) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; return _isSurveyOpen(survey) && token.balanceOfAt(_voter, survey.snapshotBlock) > 0; } function getSurvey(uint256 _surveyId) public view surveyExists(_surveyId) returns ( bool open, uint64 startDate, uint64 snapshotBlock, uint64 minParticipation, uint256 votingPower, uint256 participation, uint256 options ) { SurveyStruct storage survey = surveys[_surveyId]; open = _isSurveyOpen(survey); startDate = survey.startDate; snapshotBlock = survey.snapshotBlock; minParticipation = survey.minParticipationPct; votingPower = survey.votingPower; participation = survey.participation; options = survey.options; } /** * @dev This is not meant to be used on-chain */ /* solium-disable-next-line function-order */ function getVoterState(uint256 _surveyId, address _voter) external view surveyExists(_surveyId) returns (uint256[] options, uint256[] stakes) { MultiOptionVote storage vote = surveys[_surveyId].votes[_voter]; if (vote.optionsCastedLength == 0) { return (new uint256[](0), new uint256[](0)); } options = new uint256[](vote.optionsCastedLength + 1); stakes = new uint256[](vote.optionsCastedLength + 1); for (uint256 i = 0; i <= vote.optionsCastedLength; i++) { options[i] = vote.castedVotes[i].optionId; stakes[i] = vote.castedVotes[i].stake; } } function getOptionPower(uint256 _surveyId, uint256 _optionId) public view surveyExists(_surveyId) returns (uint256) { SurveyStruct storage survey = surveys[_surveyId]; require(_optionId <= survey.options, ERROR_NO_OPTION); return survey.optionPower[_optionId]; } function isParticipationAchieved(uint256 _surveyId) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; // votingPower is always > 0 uint256 participationPct = survey.participation.mul(PCT_BASE) / survey.votingPower; return participationPct >= survey.minParticipationPct; } // Internal fns /* * @dev Assumes the survey exists and that msg.sender can vote */ function _resetVote(uint256 _surveyId) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage previousVote = survey.votes[msg.sender]; if (previousVote.optionsCastedLength > 0) { // Voter removes their vote (index 0 is the abstain vote) for (uint256 i = 1; i <= previousVote.optionsCastedLength; i++) { OptionCast storage previousOptionCast = previousVote.castedVotes[i]; uint256 previousOptionPower = survey.optionPower[previousOptionCast.optionId]; uint256 currentOptionPower = previousOptionPower.sub(previousOptionCast.stake); survey.optionPower[previousOptionCast.optionId] = currentOptionPower; emit ResetVote(_surveyId, msg.sender, previousOptionCast.optionId, previousOptionCast.stake, currentOptionPower); } // Compute previously casted votes (i.e. substract non-used tokens from stake) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256 previousParticipation = voterStake.sub(previousVote.castedVotes[0].stake); // And remove it from total participation survey.participation = survey.participation.sub(previousParticipation); // Reset previously voted options delete survey.votes[msg.sender]; } } /* * @dev Assumes the survey exists and that msg.sender can vote */ function _voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage senderVotes = survey.votes[msg.sender]; // Revert previous votes, if any _resetVote(_surveyId); uint256 totalVoted = 0; // Reserve first index for ABSTAIN_VOTE senderVotes.castedVotes[0] = OptionCast({ optionId: ABSTAIN_VOTE, stake: 0 }); for (uint256 optionIndex = 1; optionIndex <= _optionIds.length; optionIndex++) { // Voters don't specify that they're abstaining, // but we still keep track of this by reserving the first index of a survey's votes. // We subtract 1 from the indexes of the arrays passed in by the voter to account for this. uint256 optionId = _optionIds[optionIndex - 1]; uint256 stake = _stakes[optionIndex - 1]; require(optionId != ABSTAIN_VOTE && optionId <= survey.options, ERROR_VOTE_WRONG_OPTION); require(stake > 0, ERROR_NO_STAKE); // Let's avoid repeating an option by making sure that ascending order is preserved in // the options array by checking that the current optionId is larger than the last one // we added require(senderVotes.castedVotes[optionIndex - 1].optionId < optionId, ERROR_OPTIONS_NOT_ORDERED); // Register voter amount senderVotes.castedVotes[optionIndex] = OptionCast({ optionId: optionId, stake: stake }); // Add to total option support survey.optionPower[optionId] = survey.optionPower[optionId].add(stake); // Keep track of stake used so far totalVoted = totalVoted.add(stake); emit CastVote(_surveyId, msg.sender, optionId, stake, survey.optionPower[optionId]); } // Compute and register non used tokens // Implictly we are doing require(totalVoted <= voterStake) too // (as stated before, index 0 is for ABSTAIN_VOTE option) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); senderVotes.castedVotes[0].stake = voterStake.sub(totalVoted); // Register number of options voted senderVotes.optionsCastedLength = _optionIds.length; // Add voter tokens to participation survey.participation = survey.participation.add(totalVoted); assert(survey.participation <= survey.votingPower); } function _isSurveyOpen(SurveyStruct storage _survey) internal view returns (bool) { return getTimestamp64() < _survey.startDate.add(surveyTime); } } // File: @aragon/os/contracts/acl/IACLOracle.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACLOracle { function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool); } // File: @aragon/os/contracts/acl/ACL.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers { /* Hardcoded constants to save gas bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE"); */ bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a; enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types struct Param { uint8 id; uint8 op; uint240 value; // even though value is an uint240 it can store addresses // in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal // op and id take less than 1 byte each so it can be kept in 1 sstore } uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200; uint8 internal constant TIMESTAMP_PARAM_ID = 201; // 202 is unused uint8 internal constant ORACLE_PARAM_ID = 203; uint8 internal constant LOGIC_OP_PARAM_ID = 204; uint8 internal constant PARAM_VALUE_PARAM_ID = 205; // TODO: Add execution times param type? /* Hardcoded constant to save gas bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0)); */ bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563; bytes32 public constant NO_PERMISSION = bytes32(0); address public constant ANY_ENTITY = address(-1); address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager" uint256 internal constant ORACLE_CHECK_GAS = 30000; string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL"; string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER"; string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER"; // Whether someone has a permission mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash mapping (bytes32 => Param[]) internal permissionParams; // params hash => params // Who is the manager of a permission mapping (bytes32 => address) internal permissionManager; event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed); event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash); event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager); modifier onlyPermissionManager(address _app, bytes32 _role) { require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER); _; } modifier noPermissionManager(address _app, bytes32 _role) { // only allow permission creation (or re-creation) when there is no manager require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER); _; } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(address _permissionsCreator) public onlyInit { initialized(); require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL); _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator); } /** * @dev Creates a permission that wasn't previously set and managed. * If a created permission is removed it is possible to reset it with createPermission. * This is the **ONLY** way to create permissions and set managers to permissions that don't * have a manager. * In terms of the ACL being initialized, this function implicitly protects all the other * state-changing external functions, as they all require the sender to be a manager. * @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _manager Address of the entity that will be able to grant and revoke the permission further. */ function createPermission(address _entity, address _app, bytes32 _role, address _manager) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _createPermission(_entity, _app, _role, _manager); } /** * @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform */ function grantPermission(address _entity, address _app, bytes32 _role) external { grantPermissionP(_entity, _app, _role, new uint256[](0)); } /** * @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _params Permission parameters */ function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params) public onlyPermissionManager(_app, _role) { bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH; _setPermission(_entity, _app, _role, paramsHash); } /** * @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager * @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity to revoke access from * @param _app Address of the app in which the role will be revoked * @param _role Identifier for the group of actions in app being revoked */ function revokePermission(address _entity, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermission(_entity, _app, _role, NO_PERMISSION); } /** * @notice Set `_newManager` as the manager of `_role` in `_app` * @param _newManager Address for the new manager * @param _app Address of the app in which the permission management is being transferred * @param _role Identifier for the group of actions being transferred */ function setPermissionManager(address _newManager, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(_newManager, _app, _role); } /** * @notice Remove the manager of `_role` in `_app` * @param _app Address of the app in which the permission is being unmanaged * @param _role Identifier for the group of actions being unmanaged */ function removePermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(address(0), _app, _role); } /** * @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function createBurnedPermission(address _app, bytes32 _role) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function burnPermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Get parameters for permission array length * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return Length of the array */ function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) { return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length; } /** * @notice Get parameter for permission * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @param _index Index of parameter in the array * @return Parameter (id, op, value) */ function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index) external view returns (uint8, uint8, uint240) { Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index]; return (param.id, param.op, param.value); } /** * @dev Get manager for permission * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return address of the manager for the permission */ function getPermissionManager(address _app, bytes32 _role) public view returns (address) { return permissionManager[roleHash(_app, _role)]; } /** * @dev Function called by apps to check ACL on kernel or to check permission statu * @param _who Sender of the original call * @param _where Address of the app * @param _where Identifier for a group of actions in app * @param _how Permission parameters * @return boolean indicating whether the ACL allows the role or not */ function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) { return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how)); } function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) { bytes32 whoParams = permissions[permissionHash(_who, _where, _what)]; if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) { return true; } bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)]; if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) { return true; } return false; } function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) { uint256[] memory empty = new uint256[](0); return hasPermission(_who, _where, _what, empty); } function evalParams( bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how ) public view returns (bool) { if (_paramsHash == EMPTY_PARAM_HASH) { return true; } return _evalParam(_paramsHash, 0, _who, _where, _what, _how); } /** * @dev Internal createPermission for access inside the kernel (on instantiation) */ function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal { _setPermission(_entity, _app, _role, EMPTY_PARAM_HASH); _setPermissionManager(_manager, _app, _role); } /** * @dev Internal function called to actually save the permission */ function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal { permissions[permissionHash(_entity, _app, _role)] = _paramsHash; bool entityHasPermission = _paramsHash != NO_PERMISSION; bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH; emit SetPermission(_entity, _app, _role, entityHasPermission); if (permissionHasParams) { emit SetPermissionParams(_entity, _app, _role, _paramsHash); } } function _saveParams(uint256[] _encodedParams) internal returns (bytes32) { bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams)); Param[] storage params = permissionParams[paramHash]; if (params.length == 0) { // params not saved before for (uint256 i = 0; i < _encodedParams.length; i++) { uint256 encodedParam = _encodedParams[i]; Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam)); params.push(param); } } return paramHash; } function _evalParam( bytes32 _paramsHash, uint32 _paramId, address _who, address _where, bytes32 _what, uint256[] _how ) internal view returns (bool) { if (_paramId >= permissionParams[_paramsHash].length) { return false; // out of bounds } Param memory param = permissionParams[_paramsHash][_paramId]; if (param.id == LOGIC_OP_PARAM_ID) { return _evalLogic(param, _paramsHash, _who, _where, _what, _how); } uint256 value; uint256 comparedTo = uint256(param.value); // get value if (param.id == ORACLE_PARAM_ID) { value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0; comparedTo = 1; } else if (param.id == BLOCK_NUMBER_PARAM_ID) { value = getBlockNumber(); } else if (param.id == TIMESTAMP_PARAM_ID) { value = getTimestamp(); } else if (param.id == PARAM_VALUE_PARAM_ID) { value = uint256(param.value); } else { if (param.id >= _how.length) { return false; } value = uint256(uint240(_how[param.id])); // force lost precision } if (Op(param.op) == Op.RET) { return uint256(value) > 0; } return compare(value, Op(param.op), comparedTo); } function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { if (Op(_param.op) == Op.IF_ELSE) { uint32 conditionParam; uint32 successParam; uint32 failureParam; (conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value)); bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how); return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how); } uint32 param1; uint32 param2; (param1, param2,) = decodeParamsList(uint256(_param.value)); bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how); if (Op(_param.op) == Op.NOT) { return !r1; } if (r1 && Op(_param.op) == Op.OR) { return true; } if (!r1 && Op(_param.op) == Op.AND) { return false; } bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how); if (Op(_param.op) == Op.XOR) { return r1 != r2; } return r2; // both or and and depend on result of r2 after checks } function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) { if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace return false; } function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { bytes4 sig = _oracleAddr.canPerform.selector; // a raw call is required so we can return false if the call reverts, rather than reverting bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how); uint256 oracleCheckGas = ORACLE_CHECK_GAS; bool ok; assembly { ok := staticcall(oracleCheckGas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0) } if (!ok) { return false; } uint256 size; assembly { size := returndatasize } if (size != 32) { return false; } bool result; assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` result := mload(ptr) // read data at ptr and set it to result mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr } return result; } /** * @dev Internal function that sets management */ function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal { permissionManager[roleHash(_app, _role)] = _newManager; emit ChangePermissionManager(_app, _role, _newManager); } function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("ROLE", _where, _what)); } function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what)); } } // File: @aragon/os/contracts/apm/Repo.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract Repo is AragonApp { /* Hardcoded constants to save gas bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE"); */ bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8; string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP"; string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION"; string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION"; struct Version { uint16[3] semanticVersion; address contractAddress; bytes contentURI; } uint256 internal versionsNextIndex; mapping (uint256 => Version) internal versions; mapping (bytes32 => uint256) internal versionIdForSemantic; mapping (address => uint256) internal latestVersionIdForContract; event NewVersion(uint256 versionId, uint16[3] semanticVersion); /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this Repo */ function initialize() public onlyInit { initialized(); versionsNextIndex = 1; } /** * @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)` * @param _newSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */ function newVersion( uint16[3] _newSemanticVersion, address _contractAddress, bytes _contentURI ) public auth(CREATE_VERSION_ROLE) { address contractAddress = _contractAddress; uint256 lastVersionIndex = versionsNextIndex - 1; uint16[3] memory lastSematicVersion; if (lastVersionIndex > 0) { Version storage lastVersion = versions[lastVersionIndex]; lastSematicVersion = lastVersion.semanticVersion; if (contractAddress == address(0)) { contractAddress = lastVersion.contractAddress; } // Only allows smart contract change on major version bumps require( lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0], ERROR_INVALID_VERSION ); } require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP); uint256 versionId = versionsNextIndex++; versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI); versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId; latestVersionIdForContract[contractAddress] = versionId; emit NewVersion(versionId, _newSemanticVersion); } function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionsNextIndex - 1); } function getLatestForContractAddress(address _contractAddress) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(latestVersionIdForContract[_contractAddress]); } function getBySemanticVersion(uint16[3] _semanticVersion) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]); } function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION); Version storage version = versions[_versionId]; return (version.semanticVersion, version.contractAddress, version.contentURI); } function getVersionsCount() public view returns (uint256) { return versionsNextIndex - 1; } function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) { bool hasBumped; uint i = 0; while (i < 3) { if (hasBumped) { if (_newVersion[i] != 0) { return false; } } else if (_newVersion[i] != _oldVersion[i]) { if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) { return false; } hasBumped = true; } i++; } return hasBumped; } function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) { return keccak256(abi.encodePacked(version[0], version[1], version[2])); } } // File: @aragon/os/contracts/apm/APMNamehash.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract APMNamehash { /* Hardcoded constants to save gas bytes32 internal constant APM_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, keccak256(abi.encodePacked("aragonpm")))); */ bytes32 internal constant APM_NODE = 0x9065c3e7f7b7ef1ef4e53d2d0b8e0cef02874ab020c1ece79d5f0d3d0111c0ba; function apmNamehash(string name) internal pure returns (bytes32) { return keccak256(abi.encodePacked(APM_NODE, keccak256(bytes(name)))); } } // File: @aragon/os/contracts/kernel/KernelStorage.sol pragma solidity 0.4.24; contract KernelStorage { // namespace => app id => address mapping (bytes32 => mapping (bytes32 => address)) public apps; bytes32 public recoveryVaultAppId; } // File: @aragon/os/contracts/lib/misc/ERCProxy.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ERCProxy { uint256 internal constant FORWARDING = 1; uint256 internal constant UPGRADEABLE = 2; function proxyType() public pure returns (uint256 proxyTypeId); function implementation() public view returns (address codeAddr); } // File: @aragon/os/contracts/common/DelegateProxy.sol pragma solidity 0.4.24; contract DelegateProxy is ERCProxy, IsContract { uint256 internal constant FWD_GAS_LIMIT = 10000; /** * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) * @param _dst Destination address to perform the delegatecall * @param _calldata Calldata for the delegatecall */ function delegatedFwd(address _dst, bytes _calldata) internal { require(isContract(_dst)); uint256 fwdGasLimit = FWD_GAS_LIMIT; assembly { let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File: @aragon/os/contracts/common/DepositableDelegateProxy.sol pragma solidity 0.4.24; contract DepositableDelegateProxy is DepositableStorage, DelegateProxy { event ProxyDeposit(address sender, uint256 value); function () external payable { // send / transfer if (gasleft() < FWD_GAS_LIMIT) { require(msg.value > 0 && msg.data.length == 0); require(isDepositable()); emit ProxyDeposit(msg.sender, msg.value); } else { // all calls except for send or transfer address target = implementation(); delegatedFwd(target, msg.data); } } } // File: @aragon/os/contracts/apps/AppProxyBase.sol pragma solidity 0.4.24; contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants { /** * @dev Initialize AppProxy * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public { setKernel(_kernel); setAppId(_appId); // Implicit check that kernel is actually a Kernel // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on // it. address appCode = getAppBase(_appId); // If initialize payload is provided, it will be executed if (_initializePayload.length > 0) { require(isContract(appCode)); // Cannot make delegatecall as a delegateproxy.delegatedFwd as it // returns ending execution context and halts contract deployment require(appCode.delegatecall(_initializePayload)); } } function getAppBase(bytes32 _appId) internal view returns (address) { return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId); } } // File: @aragon/os/contracts/apps/AppProxyUpgradeable.sol pragma solidity 0.4.24; contract AppProxyUpgradeable is AppProxyBase { /** * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { // solium-disable-previous-line no-empty-blocks } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return getAppBase(appId()); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } } // File: @aragon/os/contracts/apps/AppProxyPinned.sol pragma solidity 0.4.24; contract AppProxyPinned is IsContract, AppProxyBase { using UnstructuredStorage for bytes32; // keccak256("aragonOS.appStorage.pinnedCode") bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e; /** * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { setPinnedCode(getAppBase(_appId)); require(isContract(pinnedCode())); } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return pinnedCode(); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return FORWARDING; } function setPinnedCode(address _pinnedCode) internal { PINNED_CODE_POSITION.setStorageAddress(_pinnedCode); } function pinnedCode() internal view returns (address) { return PINNED_CODE_POSITION.getStorageAddress(); } } // File: @aragon/os/contracts/factory/AppProxyFactory.sol pragma solidity 0.4.24; contract AppProxyFactory { event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId); /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) { return newAppProxy(_kernel, _appId, new bytes(0)); } /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) { AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), true, _appId); return proxy; } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) { return newAppProxyPinned(_kernel, _appId, new bytes(0)); } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @param _initializePayload Proxy initialization payload * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) { AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), false, _appId); return proxy; } } // File: @aragon/os/contracts/kernel/Kernel.sol pragma solidity 0.4.24; // solium-disable-next-line max-len contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar { /* Hardcoded constants to save gas bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE"); */ bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0; string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT"; string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE"; string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED"; /** * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately. * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized */ constructor(bool _shouldPetrify) public { if (_shouldPetrify) { petrify(); } } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions * @param _baseAcl Address of base ACL app * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit { initialized(); // Set ACL base _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl); // Create ACL instance and attach it as the default ACL app IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID)); acl.initialize(_permissionsCreator); _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl); recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID; } /** * @dev Create a new instance of an app linked to this kernel * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new instance of an app linked to this kernel and set its base * implementation if it was not already set * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxy(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Create a new pinned instance of an app linked to this kernel * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newPinnedAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new pinned instance of an app linked to this kernel and set * its base implementation if it was not already set * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxyPinned(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Set the resolving address of an app instance or base implementation * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app` * @param _namespace App namespace to use * @param _appId Identifier for app * @param _app Address of the app instance or base implementation * @return ID of app */ function setApp(bytes32 _namespace, bytes32 _appId, address _app) public auth(APP_MANAGER_ROLE, arr(_namespace, _appId)) { _setApp(_namespace, _appId, _app); } /** * @dev Set the default vault id for the escape hatch mechanism * @param _recoveryVaultAppId Identifier of the recovery vault app */ function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId)) { recoveryVaultAppId = _recoveryVaultAppId; } // External access to default app id and namespace constants to mimic default getters for constants /* solium-disable function-order, mixedcase */ function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; } function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; } function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; } function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; } function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; } /* solium-enable function-order, mixedcase */ /** * @dev Get the address of an app instance or base implementation * @param _namespace App namespace to use * @param _appId Identifier for app * @return Address of the app */ function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) { return apps[_namespace][_appId]; } /** * @dev Get the address of the recovery Vault instance (to recover funds) * @return Address of the Vault */ function getRecoveryVault() public view returns (address) { return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId]; } /** * @dev Get the installed ACL app * @return ACL app */ function acl() public view returns (IACL) { return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID)); } /** * @dev Function called by apps to check ACL on kernel or to check permission status * @param _who Sender of the original call * @param _where Address of the app * @param _what Identifier for a group of actions in app * @param _how Extra data for ACL auth * @return Boolean indicating whether the ACL allows the role or not. * Always returns false if the kernel hasn't been initialized yet. */ function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) { IACL defaultAcl = acl(); return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas) defaultAcl.hasPermission(_who, _where, _what, _how); } function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal { require(isContract(_app), ERROR_APP_NOT_CONTRACT); apps[_namespace][_appId] = _app; emit SetApp(_namespace, _appId, _app); } function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal { address app = getApp(_namespace, _appId); if (app != address(0)) { // The only way to set an app is if it passes the isContract check, so no need to check it again require(app == _app, ERROR_INVALID_APP_CHANGE); } else { _setApp(_namespace, _appId, _app); } } modifier auth(bytes32 _role, uint256[] memory _params) { require( hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)), ERROR_AUTH_FAILED ); _; } } // File: @aragon/os/contracts/lib/ens/AbstractENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol pragma solidity ^0.4.15; interface AbstractENS { function owner(bytes32 _node) public constant returns (address); function resolver(bytes32 _node) public constant returns (address); function ttl(bytes32 _node) public constant returns (uint64); function setOwner(bytes32 _node, address _owner) public; function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public; function setResolver(bytes32 _node, address _resolver) public; function setTTL(bytes32 _node, uint64 _ttl) public; // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed _node, address _owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed _node, address _resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed _node, uint64 _ttl); } // File: @aragon/os/contracts/lib/ens/ENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol pragma solidity ^0.4.0; /** * The ENS registry contract. */ contract ENS is AbstractENS { struct Record { address owner; address resolver; uint64 ttl; } mapping(bytes32=>Record) records; // Permits modifications only by the owner of the specified node. modifier only_owner(bytes32 node) { if (records[node].owner != msg.sender) throw; _; } /** * Constructs a new ENS registrar. */ function ENS() public { records[0].owner = msg.sender; } /** * Returns the address that owns the specified node. */ function owner(bytes32 node) public constant returns (address) { return records[node].owner; } /** * Returns the address of the resolver for the specified node. */ function resolver(bytes32 node) public constant returns (address) { return records[node].resolver; } /** * Returns the TTL of a node, and any records associated with it. */ function ttl(bytes32 node) public constant returns (uint64) { return records[node].ttl; } /** * Transfers ownership of a node to a new address. May only be called by the current * owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) only_owner(node) public { Transfer(node, owner); records[node].owner = owner; } /** * Transfers ownership of a subnode keccak256(node, label) to a new address. May only be * called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) public { var subnode = keccak256(node, label); NewOwner(node, label, owner); records[subnode].owner = owner; } /** * Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) only_owner(node) public { NewResolver(node, resolver); records[node].resolver = resolver; } /** * Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) only_owner(node) public { NewTTL(node, ttl); records[node].ttl = ttl; } } // File: @aragon/os/contracts/lib/ens/PublicResolver.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol pragma solidity ^0.4.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; bytes4 constant NAME_INTERFACE_ID = 0x691f3431; bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); struct PublicKey { bytes32 x; bytes32 y; } struct Record { address addr; bytes32 content; string name; PublicKey pubkey; mapping(string=>string) text; mapping(uint256=>bytes) abis; } AbstractENS ens; mapping(bytes32=>Record) records; modifier only_owner(bytes32 node) { if (ens.owner(node) != msg.sender) throw; _; } /** * Constructor. * @param ensAddr The ENS registrar contract. */ function PublicResolver(AbstractENS ensAddr) public { ens = ensAddr; } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == CONTENT_INTERFACE_ID || interfaceID == NAME_INTERFACE_ID || interfaceID == ABI_INTERFACE_ID || interfaceID == PUBKEY_INTERFACE_ID || interfaceID == TEXT_INTERFACE_ID || interfaceID == INTERFACE_META_ID; } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public constant returns (address ret) { ret = records[node].addr; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) only_owner(node) public { records[node].addr = addr; AddrChanged(node, addr); } /** * Returns the content hash associated with an ENS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) public constant returns (bytes32 ret) { ret = records[node].content; } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) only_owner(node) public { records[node].content = hash; ContentChanged(node, hash); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) public constant returns (string ret) { ret = records[node].name; } /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string name) only_owner(node) public { records[node].name = name; NameChanged(node, name); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) { var record = records[node]; for(contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { data = record.abis[contentType]; return; } } contentType = 0; } /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public { // Content types must be powers of 2 if (((contentType - 1) & contentType) != 0) throw; records[node].abis[contentType] = data; ABIChanged(node, contentType); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); } /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public { records[node].pubkey = PublicKey(x, y); PubkeyChanged(node, x, y); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string key) public constant returns (string ret) { ret = records[node].text[key]; } /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string key, string value) only_owner(node) public { records[node].text[key] = value; TextChanged(node, key, key); } } // File: @aragon/os/contracts/kernel/KernelProxy.sol pragma solidity 0.4.24; contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy { /** * @dev KernelProxy is a proxy contract to a kernel implementation. The implementation * can update the reference, which effectively upgrades the contract * @param _kernelImpl Address of the contract used as implementation for kernel */ constructor(IKernel _kernelImpl) public { require(isContract(address(_kernelImpl))); apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl; // Note that emitting this event is important for verifying that a KernelProxy instance // was never upgraded to a malicious Kernel logic contract over its lifespan. // This starts the "chain of trust", that can be followed through later SetApp() events // emitted during kernel upgrades. emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID]; } } // File: @aragon/os/contracts/evmscript/ScriptHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library ScriptHelpers { function getSpecId(bytes _script) internal pure returns (uint32) { return uint32At(_script, 0); } function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := mload(add(_data, add(0x20, _location))) } } function addressAt(bytes _data, uint256 _location) internal pure returns (address result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000), 0x1000000000000000000000000) } } function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000), 0x100000000000000000000000000000000000000000000000000000000) } } function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := add(_data, add(0x20, _location)) } } function toBytes(bytes4 _sig) internal pure returns (bytes) { bytes memory payload = new bytes(4); assembly { mstore(add(payload, 0x20), _sig) } return payload; } } // File: @aragon/os/contracts/evmscript/EVMScriptRegistry.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE"); bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE"); */ bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2; // WARN: Manager can censor all votes and the like happening in an org bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3; uint256 internal constant SCRIPT_START_LOCATION = 4; string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR"; string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED"; string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED"; string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT"; struct ExecutorEntry { IEVMScriptExecutor executor; bool enabled; } uint256 private executorsNextIndex; mapping (uint256 => ExecutorEntry) public executors; event EnableExecutor(uint256 indexed executorId, address indexed executorAddress); event DisableExecutor(uint256 indexed executorId, address indexed executorAddress); modifier executorExists(uint256 _executorId) { require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR); _; } /** * @notice Initialize the registry */ function initialize() public onlyInit { initialized(); // Create empty record to begin executor IDs at 1 executorsNextIndex = 1; } /** * @notice Add a new script executor with address `_executor` to the registry * @param _executor Address of the IEVMScriptExecutor that will be added to the registry * @return id Identifier of the executor in the registry */ function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) { uint256 executorId = executorsNextIndex++; executors[executorId] = ExecutorEntry(_executor, true); emit EnableExecutor(executorId, _executor); return executorId; } /** * @notice Disable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function disableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) { // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage executorEntry = executors[_executorId]; require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED); executorEntry.enabled = false; emit DisableExecutor(_executorId, executorEntry.executor); } /** * @notice Enable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function enableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) executorExists(_executorId) { ExecutorEntry storage executorEntry = executors[_executorId]; require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED); executorEntry.enabled = true; emit EnableExecutor(_executorId, executorEntry.executor); } /** * @dev Get the script executor that can execute a particular script based on its first 4 bytes * @param _script EVMScript being inspected */ function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT); uint256 id = _script.getSpecId(); // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage entry = executors[id]; return entry.enabled ? entry.executor : IEVMScriptExecutor(0); } } // File: @aragon/os/contracts/evmscript/executors/BaseEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified { uint256 internal constant SCRIPT_START_LOCATION = 4; } // File: @aragon/os/contracts/evmscript/executors/CallsScript.sol pragma solidity 0.4.24; // Inspired by https://github.com/reverendus/tx-manager contract CallsScript is BaseEVMScriptExecutor { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT"); */ bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302; string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL"; string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH"; /* This is manually crafted in assembly string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED"; */ event LogScriptCall(address indexed sender, address indexed src, address indexed dst); /** * @notice Executes a number of call scripts * @param _script [ specId (uint32) ] many calls with this structure -> * [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ] * @param _blacklist Addresses the script cannot call to, or will revert. * @return Always returns empty byte array */ function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) { uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id while (location < _script.length) { // Check there's at least address + calldataLength available require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH); address contractAddress = _script.addressAt(location); // Check address being called is not blacklist for (uint256 i = 0; i < _blacklist.length; i++) { require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL); } // logged before execution to ensure event ordering in receipt // if failed entire execution is reverted regardless emit LogScriptCall(msg.sender, address(this), contractAddress); uint256 calldataLength = uint256(_script.uint32At(location + 0x14)); uint256 startOffset = location + 0x14 + 0x04; uint256 calldataStart = _script.locationOf(startOffset); // compute end of script / next location location = startOffset + calldataLength; require(location <= _script.length, ERROR_INVALID_LENGTH); bool success; assembly { success := call( sub(gas, 5000), // forward gas left - 5000 contractAddress, // address 0, // no value calldataStart, // calldata start calldataLength, // calldata length 0, // don't write output 0 // don't write output ) switch success case 0 { let ptr := mload(0x40) switch returndatasize case 0 { // No error data was returned, revert with "EVMCALLS_CALL_REVERTED" // See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in // this memory layout mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Forward the full error data returndatacopy(ptr, 0, returndatasize) revert(ptr, returndatasize) } } default { } } } // No need to allocate empty bytes for the return as this can only be called via an delegatecall // (due to the isInitialized modifier) } function executorType() external pure returns (bytes32) { return EXECUTOR_TYPE; } } // File: @aragon/os/contracts/factory/EVMScriptRegistryFactory.sol pragma solidity 0.4.24; contract EVMScriptRegistryFactory is EVMScriptRegistryConstants { EVMScriptRegistry public baseReg; IEVMScriptExecutor public baseCallScript; /** * @notice Create a new EVMScriptRegistryFactory. */ constructor() public { baseReg = new EVMScriptRegistry(); baseCallScript = IEVMScriptExecutor(new CallsScript()); } /** * @notice Install a new pinned instance of EVMScriptRegistry on `_dao`. * @param _dao Kernel * @return Installed EVMScriptRegistry */ function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) { bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector); reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true)); ACL acl = ACL(_dao.acl()); acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this); reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript // Clean up the permissions acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); return reg; } } // File: @aragon/os/contracts/factory/DAOFactory.sol pragma solidity 0.4.24; contract DAOFactory { IKernel public baseKernel; IACL public baseACL; EVMScriptRegistryFactory public regFactory; event DeployDAO(address dao); event DeployEVMScriptRegistry(address reg); /** * @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`. * @param _baseKernel Base Kernel * @param _baseACL Base ACL * @param _regFactory EVMScriptRegistry factory */ constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public { // No need to init as it cannot be killed by devops199 if (address(_regFactory) != address(0)) { regFactory = _regFactory; } baseKernel = _baseKernel; baseACL = _baseACL; } /** * @notice Create a new DAO with `_root` set as the initial admin * @param _root Address that will be granted control to setup DAO permissions * @return Newly created DAO */ function newDAO(address _root) public returns (Kernel) { Kernel dao = Kernel(new KernelProxy(baseKernel)); if (address(regFactory) == address(0)) { dao.initialize(baseACL, _root); } else { dao.initialize(baseACL, this); ACL acl = ACL(dao.acl()); bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); bytes32 appManagerRole = dao.APP_MANAGER_ROLE(); acl.grantPermission(regFactory, acl, permRole); acl.createPermission(regFactory, dao, appManagerRole, this); EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao); emit DeployEVMScriptRegistry(address(reg)); // Clean up permissions // First, completely reset the APP_MANAGER_ROLE acl.revokePermission(regFactory, dao, appManagerRole); acl.removePermissionManager(dao, appManagerRole); // Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE acl.revokePermission(regFactory, acl, permRole); acl.revokePermission(this, acl, permRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(_root, acl, permRole); } emit DeployDAO(address(dao)); return dao; } } // File: @aragon/id/contracts/ens/IPublicResolver.sol pragma solidity ^0.4.0; interface IPublicResolver { function supportsInterface(bytes4 interfaceID) constant returns (bool); function addr(bytes32 node) constant returns (address ret); function setAddr(bytes32 node, address addr); function hash(bytes32 node) constant returns (bytes32 ret); function setHash(bytes32 node, bytes32 hash); } // File: @aragon/id/contracts/IFIFSResolvingRegistrar.sol pragma solidity 0.4.24; interface IFIFSResolvingRegistrar { function register(bytes32 _subnode, address _owner) external; function registerWithResolver(bytes32 _subnode, address _owner, IPublicResolver _resolver) public; } // File: @aragon/templates-shared/contracts/BaseTemplate.sol pragma solidity 0.4.24; contract BaseTemplate is APMNamehash, IsContract { using Uint256Helpers for uint256; /* Hardcoded constant to save gas * bytes32 constant internal AGENT_APP_ID = apmNamehash("agent"); // agent.aragonpm.eth * bytes32 constant internal VAULT_APP_ID = apmNamehash("vault"); // vault.aragonpm.eth * bytes32 constant internal VOTING_APP_ID = apmNamehash("voting"); // voting.aragonpm.eth * bytes32 constant internal SURVEY_APP_ID = apmNamehash("survey"); // survey.aragonpm.eth * bytes32 constant internal PAYROLL_APP_ID = apmNamehash("payroll"); // payroll.aragonpm.eth * bytes32 constant internal FINANCE_APP_ID = apmNamehash("finance"); // finance.aragonpm.eth * bytes32 constant internal TOKEN_MANAGER_APP_ID = apmNamehash("token-manager"); // token-manager.aragonpm.eth */ bytes32 constant internal AGENT_APP_ID = 0x9ac98dc5f995bf0211ed589ef022719d1487e5cb2bab505676f0d084c07cf89a; bytes32 constant internal VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; bytes32 constant internal VOTING_APP_ID = 0x9fa3927f639745e587912d4b0fea7ef9013bf93fb907d29faeab57417ba6e1d4; bytes32 constant internal PAYROLL_APP_ID = 0x463f596a96d808cb28b5d080181e4a398bc793df2c222f6445189eb801001991; bytes32 constant internal FINANCE_APP_ID = 0xbf8491150dafc5dcaee5b861414dca922de09ccffa344964ae167212e8c673ae; bytes32 constant internal TOKEN_MANAGER_APP_ID = 0x6b20a3010614eeebf2138ccec99f028a61c811b3b1a3343b6ff635985c75c91f; bytes32 constant internal SURVEY_APP_ID = 0x030b2ab880b88e228f2da5a3d19a2a31bc10dbf91fb1143776a6de489389471e; string constant private ERROR_ENS_NOT_CONTRACT = "TEMPLATE_ENS_NOT_CONTRACT"; string constant private ERROR_DAO_FACTORY_NOT_CONTRACT = "TEMPLATE_DAO_FAC_NOT_CONTRACT"; string constant private ERROR_ARAGON_ID_NOT_PROVIDED = "TEMPLATE_ARAGON_ID_NOT_PROVIDED"; string constant private ERROR_ARAGON_ID_NOT_CONTRACT = "TEMPLATE_ARAGON_ID_NOT_CONTRACT"; string constant private ERROR_MINIME_FACTORY_NOT_PROVIDED = "TEMPLATE_MINIME_FAC_NOT_PROVIDED"; string constant private ERROR_MINIME_FACTORY_NOT_CONTRACT = "TEMPLATE_MINIME_FAC_NOT_CONTRACT"; string constant private ERROR_CANNOT_CAST_VALUE_TO_ADDRESS = "TEMPLATE_CANNOT_CAST_VALUE_TO_ADDRESS"; string constant private ERROR_INVALID_ID = "TEMPLATE_INVALID_ID"; ENS internal ens; DAOFactory internal daoFactory; MiniMeTokenFactory internal miniMeFactory; IFIFSResolvingRegistrar internal aragonID; event DeployDao(address dao); event SetupDao(address dao); event DeployToken(address token); event InstalledApp(address appProxy, bytes32 appId); constructor(DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID) public { require(isContract(address(_ens)), ERROR_ENS_NOT_CONTRACT); require(isContract(address(_daoFactory)), ERROR_DAO_FACTORY_NOT_CONTRACT); ens = _ens; aragonID = _aragonID; daoFactory = _daoFactory; miniMeFactory = _miniMeFactory; } /** * @dev Create a DAO using the DAO Factory and grant the template root permissions so it has full * control during setup. Once the DAO setup has finished, it is recommended to call the * `_transferRootPermissionsFromTemplateAndFinalizeDAO()` helper to transfer the root * permissions to the end entity in control of the organization. */ function _createDAO() internal returns (Kernel dao, ACL acl) { dao = daoFactory.newDAO(this); emit DeployDao(address(dao)); acl = ACL(dao.acl()); _createPermissionForTemplate(acl, dao, dao.APP_MANAGER_ROLE()); } /* ACL */ function _createPermissions(ACL _acl, address[] memory _grantees, address _app, bytes32 _permission, address _manager) internal { _acl.createPermission(_grantees[0], _app, _permission, address(this)); for (uint256 i = 1; i < _grantees.length; i++) { _acl.grantPermission(_grantees[i], _app, _permission); } _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } function _createPermissionForTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.createPermission(address(this), _app, _permission, address(this)); } function _removePermissionFromTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.revokePermission(address(this), _app, _permission); _acl.removePermissionManager(_app, _permission); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to) internal { _transferRootPermissionsFromTemplateAndFinalizeDAO(_dao, _to, _to); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to, address _manager) internal { ACL _acl = ACL(_dao.acl()); _transferPermissionFromTemplate(_acl, _dao, _to, _dao.APP_MANAGER_ROLE(), _manager); _transferPermissionFromTemplate(_acl, _acl, _to, _acl.CREATE_PERMISSIONS_ROLE(), _manager); emit SetupDao(_dao); } function _transferPermissionFromTemplate(ACL _acl, address _app, address _to, bytes32 _permission, address _manager) internal { _acl.grantPermission(_to, _app, _permission); _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } /* AGENT */ function _installDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); Agent agent = Agent(_installDefaultApp(_dao, AGENT_APP_ID, initializeData)); // We assume that installing the Agent app as a default app means the DAO should have its // Vault replaced by the Agent. Thus, we also set the DAO's recovery app to the Agent. _dao.setRecoveryVaultAppId(AGENT_APP_ID); return agent; } function _installNonDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); return Agent(_installNonDefaultApp(_dao, AGENT_APP_ID, initializeData)); } function _createAgentPermissions(ACL _acl, Agent _agent, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _agent, _agent.EXECUTE_ROLE(), _manager); _acl.createPermission(_grantee, _agent, _agent.RUN_SCRIPT_ROLE(), _manager); } /* VAULT */ function _installVaultApp(Kernel _dao) internal returns (Vault) { bytes memory initializeData = abi.encodeWithSelector(Vault(0).initialize.selector); return Vault(_installDefaultApp(_dao, VAULT_APP_ID, initializeData)); } function _createVaultPermissions(ACL _acl, Vault _vault, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _vault, _vault.TRANSFER_ROLE(), _manager); } /* VOTING */ function _installVotingApp(Kernel _dao, MiniMeToken _token, uint64[3] memory _votingSettings) internal returns (Voting) { return _installVotingApp(_dao, _token, _votingSettings[0], _votingSettings[1], _votingSettings[2]); } function _installVotingApp( Kernel _dao, MiniMeToken _token, uint64 _support, uint64 _acceptance, uint64 _duration ) internal returns (Voting) { bytes memory initializeData = abi.encodeWithSelector(Voting(0).initialize.selector, _token, _support, _acceptance, _duration); return Voting(_installNonDefaultApp(_dao, VOTING_APP_ID, initializeData)); } function _createVotingPermissions( ACL _acl, Voting _voting, address _settingsGrantee, address _createVotesGrantee, address _manager ) internal { _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_QUORUM_ROLE(), _manager); _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_SUPPORT_ROLE(), _manager); _acl.createPermission(_createVotesGrantee, _voting, _voting.CREATE_VOTES_ROLE(), _manager); } /* SURVEY */ function _installSurveyApp(Kernel _dao, MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime) internal returns (Survey) { bytes memory initializeData = abi.encodeWithSelector(Survey(0).initialize.selector, _token, _minParticipationPct, _surveyTime); return Survey(_installNonDefaultApp(_dao, SURVEY_APP_ID, initializeData)); } function _createSurveyPermissions(ACL _acl, Survey _survey, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _survey, _survey.CREATE_SURVEYS_ROLE(), _manager); _acl.createPermission(_grantee, _survey, _survey.MODIFY_PARTICIPATION_ROLE(), _manager); } /* PAYROLL */ function _installPayrollApp( Kernel _dao, Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime ) internal returns (Payroll) { bytes memory initializeData = abi.encodeWithSelector( Payroll(0).initialize.selector, _finance, _denominationToken, _priceFeed, _rateExpiryTime ); return Payroll(_installNonDefaultApp(_dao, PAYROLL_APP_ID, initializeData)); } /** * @dev Internal function to configure payroll permissions. Note that we allow defining different managers for * payroll since it may be useful to have one control the payroll settings (rate expiration, price feed, * and allowed tokens), and another one to control the employee functionality (bonuses, salaries, * reimbursements, employees, etc). * @param _acl ACL instance being configured * @param _acl Payroll app being configured * @param _employeeManager Address that will receive permissions to handle employee payroll functionality * @param _settingsManager Address that will receive permissions to manage payroll settings * @param _permissionsManager Address that will be the ACL manager for the payroll permissions */ function _createPayrollPermissions( ACL _acl, Payroll _payroll, address _employeeManager, address _settingsManager, address _permissionsManager ) internal { _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_BONUS_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_REIMBURSEMENT_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.TERMINATE_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.SET_EMPLOYEE_SALARY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_PRICE_FEED_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_RATE_EXPIRY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MANAGE_ALLOWED_TOKENS_ROLE(), _permissionsManager); } function _unwrapPayrollSettings( uint256[4] memory _payrollSettings ) internal pure returns (address denominationToken, IFeed priceFeed, uint64 rateExpiryTime, address employeeManager) { denominationToken = _toAddress(_payrollSettings[0]); priceFeed = IFeed(_toAddress(_payrollSettings[1])); rateExpiryTime = _payrollSettings[2].toUint64(); employeeManager = _toAddress(_payrollSettings[3]); } /* FINANCE */ function _installFinanceApp(Kernel _dao, Vault _vault, uint64 _periodDuration) internal returns (Finance) { bytes memory initializeData = abi.encodeWithSelector(Finance(0).initialize.selector, _vault, _periodDuration); return Finance(_installNonDefaultApp(_dao, FINANCE_APP_ID, initializeData)); } function _createFinancePermissions(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.EXECUTE_PAYMENTS_ROLE(), _manager); _acl.createPermission(_grantee, _finance, _finance.MANAGE_PAYMENTS_ROLE(), _manager); } function _createFinanceCreatePaymentsPermission(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.CREATE_PAYMENTS_ROLE(), _manager); } function _grantCreatePaymentPermission(ACL _acl, Finance _finance, address _to) internal { _acl.grantPermission(_to, _finance, _finance.CREATE_PAYMENTS_ROLE()); } function _transferCreatePaymentManagerFromTemplate(ACL _acl, Finance _finance, address _manager) internal { _acl.setPermissionManager(_manager, _finance, _finance.CREATE_PAYMENTS_ROLE()); } /* TOKEN MANAGER */ function _installTokenManagerApp( Kernel _dao, MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) internal returns (TokenManager) { TokenManager tokenManager = TokenManager(_installNonDefaultApp(_dao, TOKEN_MANAGER_APP_ID)); _token.changeController(tokenManager); tokenManager.initialize(_token, _transferable, _maxAccountTokens); return tokenManager; } function _createTokenManagerPermissions(ACL _acl, TokenManager _tokenManager, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _tokenManager, _tokenManager.MINT_ROLE(), _manager); _acl.createPermission(_grantee, _tokenManager, _tokenManager.BURN_ROLE(), _manager); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256[] memory _stakes) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stakes[i]); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stake); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address _holder, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); _tokenManager.mint(_holder, _stake); _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } /* EVM SCRIPTS */ function _createEvmScriptsRegistryPermissions(ACL _acl, address _grantee, address _manager) internal { EVMScriptRegistry registry = EVMScriptRegistry(_acl.getEVMScriptRegistry()); _acl.createPermission(_grantee, registry, registry.REGISTRY_MANAGER_ROLE(), _manager); _acl.createPermission(_grantee, registry, registry.REGISTRY_ADD_EXECUTOR_ROLE(), _manager); } /* APPS */ function _installNonDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installNonDefaultApp(_dao, _appId, new bytes(0)); } function _installNonDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, false); } function _installDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installDefaultApp(_dao, _appId, new bytes(0)); } function _installDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, true); } function _installApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData, bool _setDefault) internal returns (address) { address latestBaseAppAddress = _latestVersionAppBase(_appId); address instance = address(_dao.newAppInstance(_appId, latestBaseAppAddress, _initializeData, _setDefault)); emit InstalledApp(instance, _appId); return instance; } function _latestVersionAppBase(bytes32 _appId) internal view returns (address base) { Repo repo = Repo(PublicResolver(ens.resolver(_appId)).addr(_appId)); (,base,) = repo.getLatest(); } /* TOKEN */ function _createToken(string memory _name, string memory _symbol, uint8 _decimals) internal returns (MiniMeToken) { require(address(miniMeFactory) != address(0), ERROR_MINIME_FACTORY_NOT_PROVIDED); MiniMeToken token = miniMeFactory.createCloneToken(MiniMeToken(address(0)), 0, _name, _decimals, _symbol, true); emit DeployToken(address(token)); return token; } function _ensureMiniMeFactoryIsValid(address _miniMeFactory) internal view { require(isContract(address(_miniMeFactory)), ERROR_MINIME_FACTORY_NOT_CONTRACT); } /* IDS */ function _validateId(string memory _id) internal pure { require(bytes(_id).length > 0, ERROR_INVALID_ID); } function _registerID(string memory _name, address _owner) internal { require(address(aragonID) != address(0), ERROR_ARAGON_ID_NOT_PROVIDED); aragonID.register(keccak256(abi.encodePacked(_name)), _owner); } function _ensureAragonIdIsValid(address _aragonID) internal view { require(isContract(address(_aragonID)), ERROR_ARAGON_ID_NOT_CONTRACT); } /* HELPERS */ function _toAddress(uint256 _value) private pure returns (address) { require(_value <= uint160(-1), ERROR_CANNOT_CAST_VALUE_TO_ADDRESS); return address(_value); } } // File: @ablack/fundraising-bancor-formula/contracts/interfaces/IBancorFormula.sol pragma solidity 0.4.24; /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256); function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } // File: @ablack/fundraising-bancor-formula/contracts/utility/Utils.sol pragma solidity 0.4.24; /* Utilities & Common Modifiers */ contract Utils { /** constructor */ constructor() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } } // File: @ablack/fundraising-bancor-formula/contracts/BancorFormula.sol pragma solidity 0.4.24; contract BancorFormula is IBancorFormula, Utils { using SafeMath for uint256; string public version = '0.3'; uint256 private constant ONE = 1; uint32 private constant MAX_WEIGHT = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; /** Auto-generated via 'PrintIntScalingFactors.py' */ uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; /** Auto-generated via 'PrintLn2ScalingFactors.py' */ uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; /** Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py' */ uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; /** Auto-generated via 'PrintFunctionConstructor.py' */ uint256[128] private maxExpArray; constructor() public { // maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff; // maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff; // maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff; // maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff; // maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff; // maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff; // maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff; // maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff; // maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff; // maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff; // maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff; // maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff; // maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff; // maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff; // maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff; // maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff; // maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff; // maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff; // maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff; // maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff; // maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff; // maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff; // maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff; // maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff; // maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff; // maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff; // maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff; // maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff; // maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff; // maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff; // maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff; // maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff; maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } /** @dev given a token supply, connector balance, weight and a deposit amount (in the connector token), calculates the return for a given conversion (in the main token) Formula: Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1) @param _supply token total supply @param _connectorBalance total connector balance @param _connectorWeight connector weight, represented in ppm, 1-1000000 @param _depositAmount deposit amount, in connector token @return purchase return amount */ function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT); // special case for 0 deposit amount if (_depositAmount == 0) return 0; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _supply.mul(_depositAmount) / _connectorBalance; uint256 result; uint8 precision; uint256 baseN = _depositAmount.add(_connectorBalance); (result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** @dev given a token supply, connector balance, weight and a sell amount (in the main token), calculates the return for a given conversion (in the connector token) Formula: Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000))) @param _supply token total supply @param _connectorBalance total connector @param _connectorWeight constant connector Weight, represented in ppm, 1-1000000 @param _sellAmount sell amount, in the token itself @return sale return amount */ function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply); // special case for 0 sell amount if (_sellAmount == 0) return 0; // special case for selling the entire supply if (_sellAmount == _supply) return _connectorBalance; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _connectorBalance.mul(_sellAmount) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _sellAmount; (result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight); uint256 temp1 = _connectorBalance.mul(result); uint256 temp2 = _connectorBalance << precision; return (temp1 - temp2) / result; } /** @dev given two connector balances/weights and a sell amount (in the first connector token), calculates the return for a conversion from the first connector token to the second connector token (in the second connector token) Formula: Return = _toConnectorBalance * (1 - (_fromConnectorBalance / (_fromConnectorBalance + _amount)) ^ (_fromConnectorWeight / _toConnectorWeight)) @param _fromConnectorBalance input connector balance @param _fromConnectorWeight input connector weight, represented in ppm, 1-1000000 @param _toConnectorBalance output connector balance @param _toConnectorWeight output connector weight, represented in ppm, 1-1000000 @param _amount input connector amount @return second connector amount */ function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256) { // validate input require(_fromConnectorBalance > 0 && _fromConnectorWeight > 0 && _fromConnectorWeight <= MAX_WEIGHT && _toConnectorBalance > 0 && _toConnectorWeight > 0 && _toConnectorWeight <= MAX_WEIGHT); // special case for equal weights if (_fromConnectorWeight == _toConnectorWeight) return _toConnectorBalance.mul(_amount) / _fromConnectorBalance.add(_amount); uint256 result; uint8 precision; uint256 baseN = _fromConnectorBalance.add(_amount); (result, precision) = power(baseN, _fromConnectorBalance, _fromConnectorWeight, _toConnectorWeight); uint256 temp1 = _toConnectorBalance.mul(result); uint256 temp2 = _toConnectorBalance << precision; return (temp1 - temp2) / result; } /** General Description: Determine a value of precision. Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision. Return the result along with the precision used. Detailed Description: Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)". The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision". The larger "precision" is, the more accurately this value represents the real value. However, the larger "precision" is, the more bits are required in order to store this value. And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x"). This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations. This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". */ function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM); uint256 baseLog; uint256 base = _baseN * FIXED_1 / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = baseLog * _expN / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision); } } /** Compute log(x / FIXED_1) * FIXED_1. This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); } } } return res * LN2_NUMERATOR / LN2_DENOMINATOR; } /** Compute the largest integer smaller than or equal to the binary logarithm of the input. */ function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (ONE << s)) { _n >>= s; res |= s; } } } return res; } /** The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] */ function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) { uint8 lo = MIN_PRECISION; uint8 hi = MAX_PRECISION; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) return hi; if (maxExpArray[lo] >= _x) return lo; require(false); return 0; } /** This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy. The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1". The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". */ function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** Return log(x / FIXED_1) * FIXED_1 Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalLog.py' Detailed description: - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2 - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1 - The natural logarithm of the input is calculated by summing up the intermediate results above - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859) */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1 if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2 if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3 if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4 if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5 if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6 if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7 if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8 z = y = x - FIXED_1; w = y * y / FIXED_1; res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02 res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04 res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06 res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08 res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10 res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12 res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14 res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 return res; } /** Return e ^ (x / FIXED_1) * FIXED_1 Input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalExp.py' Detailed description: - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible - The exponentiation of each binary exponent is given (pre-calculated) - The exponentiation of r is calculated via Taylor series for e^x, where x = r - The exponentiation of the input is calculated by multiplying the intermediate results above - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } } // File: @ablack/fundraising-shared-interfaces/contracts/IAragonFundraisingController.sol pragma solidity 0.4.24; contract IAragonFundraisingController { function openTrading() external; function updateTappedAmount(address _token) external; function collateralsToBeClaimed(address _collateral) public view returns (uint256); function balanceOf(address _who, address _token) public view returns (uint256); } // File: @ablack/fundraising-batched-bancor-market-maker/contracts/BatchedBancorMarketMaker.sol pragma solidity 0.4.24; contract BatchedBancorMarketMaker is EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant UPDATE_FORMULA_ROLE = keccak256("UPDATE_FORMULA_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant UPDATE_FORMULA_ROLE = 0xbfb76d8d43f55efe58544ea32af187792a7bdb983850d8fed33478266eec3cbb; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 uint32 public constant PPM = 1000000; string private constant ERROR_CONTRACT_IS_EOA = "MM_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "MM_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "MM_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_PERCENTAGE = "MM_INVALID_PERCENTAGE"; string private constant ERROR_INVALID_RESERVE_RATIO = "MM_INVALID_RESERVE_RATIO"; string private constant ERROR_INVALID_TM_SETTING = "MM_INVALID_TM_SETTING"; string private constant ERROR_INVALID_COLLATERAL = "MM_INVALID_COLLATERAL"; string private constant ERROR_INVALID_COLLATERAL_VALUE = "MM_INVALID_COLLATERAL_VALUE"; string private constant ERROR_INVALID_BOND_AMOUNT = "MM_INVALID_BOND_AMOUNT"; string private constant ERROR_ALREADY_OPEN = "MM_ALREADY_OPEN"; string private constant ERROR_NOT_OPEN = "MM_NOT_OPEN"; string private constant ERROR_COLLATERAL_ALREADY_WHITELISTED = "MM_COLLATERAL_ALREADY_WHITELISTED"; string private constant ERROR_COLLATERAL_NOT_WHITELISTED = "MM_COLLATERAL_NOT_WHITELISTED"; string private constant ERROR_NOTHING_TO_CLAIM = "MM_NOTHING_TO_CLAIM"; string private constant ERROR_BATCH_NOT_OVER = "MM_BATCH_NOT_OVER"; string private constant ERROR_BATCH_CANCELLED = "MM_BATCH_CANCELLED"; string private constant ERROR_BATCH_NOT_CANCELLED = "MM_BATCH_NOT_CANCELLED"; string private constant ERROR_SLIPPAGE_EXCEEDS_LIMIT = "MM_SLIPPAGE_EXCEEDS_LIMIT"; string private constant ERROR_INSUFFICIENT_POOL_BALANCE = "MM_INSUFFICIENT_POOL_BALANCE"; string private constant ERROR_TRANSFER_FROM_FAILED = "MM_TRANSFER_FROM_FAILED"; struct Collateral { bool whitelisted; uint256 virtualSupply; uint256 virtualBalance; uint32 reserveRatio; uint256 slippage; } struct MetaBatch { bool initialized; uint256 realSupply; uint256 buyFeePct; uint256 sellFeePct; IBancorFormula formula; mapping(address => Batch) batches; } struct Batch { bool initialized; bool cancelled; uint256 supply; uint256 balance; uint32 reserveRatio; uint256 slippage; uint256 totalBuySpend; uint256 totalBuyReturn; uint256 totalSellSpend; uint256 totalSellReturn; mapping(address => uint256) buyers; mapping(address => uint256) sellers; } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; Vault public reserve; address public beneficiary; IBancorFormula public formula; uint256 public batchBlocks; uint256 public buyFeePct; uint256 public sellFeePct; bool public isOpen; uint256 public tokensToBeMinted; mapping(address => uint256) public collateralsToBeClaimed; mapping(address => Collateral) public collaterals; mapping(uint256 => MetaBatch) public metaBatches; event UpdateBeneficiary (address indexed beneficiary); event UpdateFormula (address indexed formula); event UpdateFees (uint256 buyFeePct, uint256 sellFeePct); event NewMetaBatch (uint256 indexed id, uint256 supply, uint256 buyFeePct, uint256 sellFeePct, address formula); event NewBatch ( uint256 indexed id, address indexed collateral, uint256 supply, uint256 balance, uint32 reserveRatio, uint256 slippage) ; event CancelBatch (uint256 indexed id, address indexed collateral); event AddCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event RemoveCollateralToken (address indexed collateral); event UpdateCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event Open (); event OpenBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event OpenSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event ClaimCancelledBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 value); event ClaimCancelledSellOrder(address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event UpdatePricing ( uint256 indexed batchId, address indexed collateral, uint256 totalBuySpend, uint256 totalBuyReturn, uint256 totalSellSpend, uint256 totalSellReturn ); /***** external function *****/ /** * @notice Initialize market maker * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded token] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom fees are to be sent] * @param _formula The address of the BancorFormula [computation] contract * @param _batchBlocks The number of blocks batches are to last * @param _buyFeePct The fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The fee to be deducted from sell orders [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, IBancorFormula _formula, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _buyFeePct, uint256 _sellFeePct ) external onlyInit { initialized(); require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_formula), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks > 0, ERROR_INVALID_BATCH_BLOCKS); require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); require(_tokenManagerSettingIsValid(_tokenManager), ERROR_INVALID_TM_SETTING); controller = _controller; tokenManager = _tokenManager; token = ERC20(tokenManager.token()); formula = _formula; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; } /* generic settings related function */ /** * @notice Open market making [enabling users to open buy and sell orders] */ function open() external auth(OPEN_ROLE) { require(!isOpen, ERROR_ALREADY_OPEN); _open(); } /** * @notice Update formula to `_formula` * @param _formula The address of the new BancorFormula [computation] contract */ function updateFormula(IBancorFormula _formula) external auth(UPDATE_FORMULA_ROLE) { require(isContract(_formula), ERROR_CONTRACT_IS_EOA); _updateFormula(_formula); } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom fees are to be sent] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); _updateFees(_buyFeePct, _sellFeePct); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(ADD_COLLATERAL_TOKEN_ROLE) { require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL); require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); _removeCollateralToken(_collateral); } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* market making related functions */ /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _buyer The address of the buyer * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _buyer, address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE); _openBuyOrder(_buyer, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _seller The address of the seller * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _seller, address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_bondAmountIsValid(_seller, _amount), ERROR_INVALID_BOND_AMOUNT); _openSellOrder(_seller, _collateral, _amount); } /** * @notice Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_seller`'s `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimSellOrder(_seller, _batchId, _collateral); } /** * @notice Claim the investments of `_buyer`'s `_collateral.symbol(): string` buy orders from cancelled batch #`_batchId` * @param _buyer The address of the user whose cancelled buy orders are to be claimed * @param _batchId The id of the batch in which cancelled buy orders are to be claimed * @param _collateral The address of the collateral token against which cancelled buy orders are to be claimed */ function claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimCancelledBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the investments of `_seller`'s `_collateral.symbol(): string` sell orders from cancelled batch #`_batchId` * @param _seller The address of the user whose cancelled sell orders are to be claimed * @param _batchId The id of the batch in which cancelled sell orders are to be claimed * @param _collateral The address of the collateral token against which cancelled sell orders are to be claimed */ function claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimCancelledSellOrder(_seller, _batchId, _collateral); } /***** public view functions *****/ function getCurrentBatchId() public view isInitialized returns (uint256) { return _currentBatchId(); } function getCollateralToken(address _collateral) public view isInitialized returns (bool, uint256, uint256, uint32, uint256) { Collateral storage collateral = collaterals[_collateral]; return (collateral.whitelisted, collateral.virtualSupply, collateral.virtualBalance, collateral.reserveRatio, collateral.slippage); } function getBatch(uint256 _batchId, address _collateral) public view isInitialized returns (bool, bool, uint256, uint256, uint32, uint256, uint256, uint256, uint256, uint256) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return ( batch.initialized, batch.cancelled, batch.supply, batch.balance, batch.reserveRatio, batch.slippage, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn ); } function getStaticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) public view isInitialized returns (uint256) { return _staticPricePPM(_supply, _balance, _reserveRatio); } /***** internal functions *****/ /* computation functions */ function _staticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) internal pure returns (uint256) { return uint256(PPM).mul(uint256(PPM)).mul(_balance).div(_supply.mul(uint256(_reserveRatio))); } function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _feeIsValid(uint256 _fee) internal pure returns (bool) { return _fee < PCT_BASE; } function _reserveRatioIsValid(uint32 _reserveRatio) internal pure returns (bool) { return _reserveRatio <= PPM; } function _tokenManagerSettingIsValid(TokenManager _tokenManager) internal view returns (bool) { return _tokenManager.maxAccountTokens() == uint256(-1); } function _collateralValueIsValid(address _buyer, address _collateral, uint256 _value, uint256 _msgValue) internal view returns (bool) { if (_value == 0) { return false; } if (_collateral == ETH) { return _msgValue == _value; } return ( _msgValue == 0 && controller.balanceOf(_buyer, _collateral) >= _value && ERC20(_collateral).allowance(_buyer, address(this)) >= _value ); } function _bondAmountIsValid(address _seller, uint256 _amount) internal view returns (bool) { return _amount != 0 && tokenManager.spendableBalanceOf(_seller) >= _amount; } function _collateralIsWhitelisted(address _collateral) internal view returns (bool) { return collaterals[_collateral].whitelisted; } function _batchIsOver(uint256 _batchId) internal view returns (bool) { return _batchId < _currentBatchId(); } function _batchIsCancelled(uint256 _batchId, address _collateral) internal view returns (bool) { return metaBatches[_batchId].batches[_collateral].cancelled; } function _userIsBuyer(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.buyers[_user] > 0; } function _userIsSeller(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.sellers[_user] > 0; } function _poolBalanceIsSufficient(address _collateral) internal view returns (bool) { return controller.balanceOf(address(reserve), _collateral) >= collateralsToBeClaimed[_collateral]; } function _slippageIsValid(Batch storage _batch, address _collateral) internal view returns (bool) { uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio); uint256 maximumSlippage = _batch.slippage; // if static price is zero let's consider that every slippage is valid if (staticPricePPM == 0) { return true; } return _buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) && _sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage); } function _buySlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ /** * NOTE * slippage is valid if: * totalBuyReturn >= totalBuySpend / (startingPrice * (1 + maxSlippage)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (PCT + maximumSlippage) / PCT_BASE) * totalBuyReturn * startingPrice * ( PCT + maximumSlippage) >= totalBuySpend * PCT_BASE * PPM */ if ( _batch.totalBuyReturn.mul(_startingPricePPM).mul(PCT_BASE.add(_maximumSlippage)) >= _batch.totalBuySpend.mul(PCT_BASE).mul(uint256(PPM)) ) { return true; } return false; } function _sellSlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ // if allowed sell slippage >= 100% // then any sell slippage is valid if (_maximumSlippage >= PCT_BASE) { return true; } /** * NOTE * slippage is valid if * totalSellReturn >= startingPrice * (1 - maxSlippage) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (1 - maximumSlippage / PCT_BASE) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (PCT_BASE - maximumSlippage) * totalBuySpend / PCT_BASE * totalSellReturn * PCT_BASE * PPM = startingPricePPM * (PCT_BASE - maximumSlippage) * totalBuySpend */ if ( _batch.totalSellReturn.mul(PCT_BASE).mul(uint256(PPM)) >= _startingPricePPM.mul(PCT_BASE.sub(_maximumSlippage)).mul(_batch.totalSellSpend) ) { return true; } return false; } /* initialization functions */ function _currentBatch(address _collateral) internal returns (uint256, Batch storage) { uint256 batchId = _currentBatchId(); MetaBatch storage metaBatch = metaBatches[batchId]; Batch storage batch = metaBatch.batches[_collateral]; if (!metaBatch.initialized) { /** * NOTE * all collateral batches should be initialized with the same supply to * avoid price manipulation between different collaterals in the same meta-batch * we don't need to do the same with collateral balances as orders against one collateral * can't affect the pool's balance against another collateral and tap is a step-function * of the meta-batch duration */ /** * NOTE * realSupply(metaBatch) = totalSupply(metaBatchInitialization) + tokensToBeMinted(metaBatchInitialization) * 1. buy and sell orders incoming during the current meta-batch and affecting totalSupply or tokensToBeMinted * should not be taken into account in the price computation [they are already a part of the batched pricing computation] * 2. the only way for totalSupply to be modified during a meta-batch [outside of incoming buy and sell orders] * is for buy orders from previous meta-batches to be claimed [and tokens to be minted]: * as such totalSupply(metaBatch) + tokenToBeMinted(metaBatch) will always equal totalSupply(metaBatchInitialization) + tokenToBeMinted(metaBatchInitialization) */ metaBatch.realSupply = token.totalSupply().add(tokensToBeMinted); metaBatch.buyFeePct = buyFeePct; metaBatch.sellFeePct = sellFeePct; metaBatch.formula = formula; metaBatch.initialized = true; emit NewMetaBatch(batchId, metaBatch.realSupply, metaBatch.buyFeePct, metaBatch.sellFeePct, metaBatch.formula); } if (!batch.initialized) { /** * NOTE * supply(batch) = realSupply(metaBatch) + virtualSupply(batchInitialization) * virtualSupply can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ /** * NOTE * balance(batch) = poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) + virtualBalance(metaBatchInitialization) * 1. buy and sell orders incoming during the current batch and affecting poolBalance or collateralsToBeClaimed * should not be taken into account in the price computation [they are already a part of the batched price computation] * 2. the only way for poolBalance to be modified during a batch [outside of incoming buy and sell orders] * is for sell orders from previous meta-batches to be claimed [and collateral to be transfered] as the tap is a step-function of the meta-batch duration: * as such poolBalance(batch) - collateralsToBeClaimed(batch) will always equal poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) * 3. virtualBalance can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ controller.updateTappedAmount(_collateral); batch.supply = metaBatch.realSupply.add(collaterals[_collateral].virtualSupply); batch.balance = controller.balanceOf(address(reserve), _collateral).add(collaterals[_collateral].virtualBalance).sub(collateralsToBeClaimed[_collateral]); batch.reserveRatio = collaterals[_collateral].reserveRatio; batch.slippage = collaterals[_collateral].slippage; batch.initialized = true; emit NewBatch(batchId, _collateral, batch.supply, batch.balance, batch.reserveRatio, batch.slippage); } return (batchId, batch); } /* state modifiying functions */ function _open() internal { isOpen = true; emit Open(); } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateFormula(IBancorFormula _formula) internal { formula = _formula; emit UpdateFormula(address(_formula)); } function _updateFees(uint256 _buyFeePct, uint256 _sellFeePct) internal { buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; emit UpdateFees(_buyFeePct, _sellFeePct); } function _cancelCurrentBatch(address _collateral) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); if (!batch.cancelled) { batch.cancelled = true; // bought bonds are cancelled but sold bonds are due back // bought collaterals are cancelled but sold collaterals are due back tokensToBeMinted = tokensToBeMinted.sub(batch.totalBuyReturn).add(batch.totalSellSpend); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].add(batch.totalBuySpend).sub(batch.totalSellReturn); emit CancelBatch(batchId, _collateral); } } function _addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) internal { collaterals[_collateral].whitelisted = true; collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit AddCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _removeCollateralToken(address _collateral) internal { _cancelCurrentBatch(_collateral); Collateral storage collateral = collaterals[_collateral]; delete collateral.whitelisted; delete collateral.virtualSupply; delete collateral.virtualBalance; delete collateral.reserveRatio; delete collateral.slippage; emit RemoveCollateralToken(_collateral); } function _updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) internal { collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit UpdateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _openBuyOrder(address _buyer, address _collateral, uint256 _value) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // deduct fee uint256 fee = _value.mul(metaBatches[batchId].buyFeePct).div(PCT_BASE); uint256 value = _value.sub(fee); // collect fee and collateral if (fee > 0) { _transfer(_buyer, beneficiary, _collateral, fee); } _transfer(_buyer, address(reserve), _collateral, value); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalBuySpend = batch.totalBuySpend.add(value); batch.buyers[_buyer] = batch.buyers[_buyer].add(value); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); emit OpenBuyOrder(_buyer, batchId, _collateral, fee, value); } function _openSellOrder(address _seller, address _collateral, uint256 _amount) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // burn bonds tokenManager.burn(_seller, _amount); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalSellSpend = batch.totalSellSpend.add(_amount); batch.sellers[_seller] = batch.sellers[_seller].add(_amount); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); require(_poolBalanceIsSufficient(_collateral), ERROR_INSUFFICIENT_POOL_BALANCE); emit OpenSellOrder(_seller, batchId, _collateral, _amount); } function _claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 buyReturn = (batch.buyers[_buyer].mul(batch.totalBuyReturn)).div(batch.totalBuySpend); batch.buyers[_buyer] = 0; if (buyReturn > 0) { tokensToBeMinted = tokensToBeMinted.sub(buyReturn); tokenManager.mint(_buyer, buyReturn); } emit ClaimBuyOrder(_buyer, _batchId, _collateral, buyReturn); } function _claimSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 saleReturn = (batch.sellers[_seller].mul(batch.totalSellReturn)).div(batch.totalSellSpend); uint256 fee = saleReturn.mul(metaBatches[_batchId].sellFeePct).div(PCT_BASE); uint256 value = saleReturn.sub(fee); batch.sellers[_seller] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(saleReturn); reserve.transfer(_collateral, _seller, value); } if (fee > 0) { reserve.transfer(_collateral, beneficiary, fee); } emit ClaimSellOrder(_seller, _batchId, _collateral, fee, value); } function _claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 value = batch.buyers[_buyer]; batch.buyers[_buyer] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(value); reserve.transfer(_collateral, _buyer, value); } emit ClaimCancelledBuyOrder(_buyer, _batchId, _collateral, value); } function _claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 amount = batch.sellers[_seller]; batch.sellers[_seller] = 0; if (amount > 0) { tokensToBeMinted = tokensToBeMinted.sub(amount); tokenManager.mint(_seller, amount); } emit ClaimCancelledSellOrder(_seller, _batchId, _collateral, amount); } function _updatePricing(Batch storage batch, uint256 _batchId, address _collateral) internal { // the situation where there are no buy nor sell orders can't happen [keep commented] // if (batch.totalSellSpend == 0 && batch.totalBuySpend == 0) // return; // static price is the current exact price in collateral // per token according to the initial state of the batch // [expressed in PPM for precision sake] uint256 staticPricePPM = _staticPricePPM(batch.supply, batch.balance, batch.reserveRatio); // [NOTE] // if staticPrice is zero then resultOfSell [= 0] <= batch.totalBuySpend // so totalSellReturn will be zero and totalBuyReturn will be // computed normally along the formula // 1. we want to find out if buy orders are worth more sell orders [or vice-versa] // 2. we thus check the return of sell orders at the current exact price // 3. if the return of sell orders is larger than the pending buys, // there are more sells than buys [and vice-versa] uint256 resultOfSell = batch.totalSellSpend.mul(staticPricePPM).div(uint256(PPM)); if (resultOfSell > batch.totalBuySpend) { // >> sell orders are worth more than buy orders // 1. first we execute all pending buy orders at the current exact // price because there is at least one sell order for each buy order // 2. then the final sell return is the addition of this first // matched return with the remaining bonding curve return // the number of tokens bought as a result of all buy orders matched at the // current exact price [which is less than the total amount of tokens to be sold] batch.totalBuyReturn = batch.totalBuySpend.mul(uint256(PPM)).div(staticPricePPM); // the number of tokens left over to be sold along the curve which is the difference // between the original total sell order and the result of all the buy orders uint256 remainingSell = batch.totalSellSpend.sub(batch.totalBuyReturn); // the amount of collateral generated by selling tokens left over to be sold // along the bonding curve in the batch initial state [as if the buy orders // never existed and the sell order was just smaller than originally thought] uint256 remainingSellReturn = metaBatches[_batchId].formula.calculateSaleReturn(batch.supply, batch.balance, batch.reserveRatio, remainingSell); // the total result of all sells is the original amount of buys which were matched // plus the remaining sells which were executed along the bonding curve batch.totalSellReturn = batch.totalBuySpend.add(remainingSellReturn); } else { // >> buy orders are worth more than sell orders // 1. first we execute all pending sell orders at the current exact // price because there is at least one buy order for each sell order // 2. then the final buy return is the addition of this first // matched return with the remaining bonding curve return // the number of collaterals bought as a result of all sell orders matched at the // current exact price [which is less than the total amount of collateral to be spent] batch.totalSellReturn = resultOfSell; // the number of collaterals left over to be spent along the curve which is the difference // between the original total buy order and the result of all the sell orders uint256 remainingBuy = batch.totalBuySpend.sub(resultOfSell); // the amount of tokens generated by selling collaterals left over to be spent // along the bonding curve in the batch initial state [as if the sell orders // never existed and the buy order was just smaller than originally thought] uint256 remainingBuyReturn = metaBatches[_batchId].formula.calculatePurchaseReturn(batch.supply, batch.balance, batch.reserveRatio, remainingBuy); // the total result of all buys is the original amount of buys which were matched // plus the remaining buys which were executed along the bonding curve batch.totalBuyReturn = batch.totalSellSpend.add(remainingBuyReturn); } emit UpdatePricing(_batchId, _collateral, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn); } function _transfer(address _from, address _to, address _collateralToken, uint256 _amount) internal { if (_collateralToken == ETH) { _to.transfer(_amount); } else { require(ERC20(_collateralToken).safeTransferFrom(_from, _to, _amount), ERROR_TRANSFER_FROM_FAILED); } } } // File: @ablack/fundraising-shared-interfaces/contracts/IPresale.sol pragma solidity 0.4.24; contract IPresale { function open() external; function close() external; function contribute(address _contributor, uint256 _value) external payable; function refund(address _contributor, uint256 _vestedPurchaseId) external; function contributionToTokens(uint256 _value) public view returns (uint256); function contributionToken() public view returns (address); } // File: @ablack/fundraising-shared-interfaces/contracts/ITap.sol pragma solidity 0.4.24; contract ITap { function updateBeneficiary(address _beneficiary) external; function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external; function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external; function addTappedToken(address _token, uint256 _rate, uint256 _floor) external; function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external; function resetTappedToken(address _token) external; function updateTappedAmount(address _token) external; function withdraw(address _token) external; function getMaximumWithdrawal(address _token) public view returns (uint256); function rates(address _token) public view returns (uint256); } // File: @ablack/fundraising-aragon-fundraising/contracts/AragonFundraisingController.sol pragma solidity 0.4.24; contract AragonFundraisingController is EtherTokenConstant, IsContract, IAragonFundraisingController, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TOKEN_TAP_ROLE = keccak256("ADD_TOKEN_TAP_ROLE"); bytes32 public constant UPDATE_TOKEN_TAP_ROLE = keccak256("UPDATE_TOKEN_TAP_ROLE"); bytes32 public constant OPEN_PRESALE_ROLE = keccak256("OPEN_PRESALE_ROLE"); bytes32 public constant OPEN_TRADING_ROLE = keccak256("OPEN_TRADING_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TOKEN_TAP_ROLE = 0xbc9cb5e3f7ce81c4fd021d86a4bcb193dee9df315b540808c3ed59a81e596207; bytes32 public constant UPDATE_TOKEN_TAP_ROLE = 0xdb8c88bedbc61ea0f92e1ce46da0b7a915affbd46d1c76c4bbac9a209e4a8416; bytes32 public constant OPEN_PRESALE_ROLE = 0xf323aa41eef4850a8ae7ebd047d4c89f01ce49c781f3308be67303db9cdd48c2; bytes32 public constant OPEN_TRADING_ROLE = 0x26ce034204208c0bbca4c8a793d17b99e546009b1dd31d3c1ef761f66372caf6; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant TO_RESET_CAP = 10; string private constant ERROR_CONTRACT_IS_EOA = "FUNDRAISING_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_TOKENS = "FUNDRAISING_INVALID_TOKENS"; IPresale public presale; BatchedBancorMarketMaker public marketMaker; Agent public reserve; ITap public tap; address[] public toReset; /***** external functions *****/ /** * @notice Initialize Aragon Fundraising controller * @param _presale The address of the presale contract * @param _marketMaker The address of the market maker contract * @param _reserve The address of the reserve [pool] contract * @param _tap The address of the tap contract * @param _toReset The addresses of the tokens whose tap timestamps are to be reset [when presale is closed and trading is open] */ function initialize( IPresale _presale, BatchedBancorMarketMaker _marketMaker, Agent _reserve, ITap _tap, address[] _toReset ) external onlyInit { require(isContract(_presale), ERROR_CONTRACT_IS_EOA); require(isContract(_marketMaker), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(isContract(_tap), ERROR_CONTRACT_IS_EOA); require(_toReset.length < TO_RESET_CAP, ERROR_INVALID_TOKENS); initialized(); presale = _presale; marketMaker = _marketMaker; reserve = _reserve; tap = _tap; for (uint256 i = 0; i < _toReset.length; i++) { require(_tokenIsContractOrETH(_toReset[i]), ERROR_INVALID_TOKENS); toReset.push(_toReset[i]); } } /* generic settings related function */ /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { marketMaker.updateBeneficiary(_beneficiary); tap.updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { marketMaker.updateFees(_buyFeePct, _sellFeePct); } /* presale related functions */ /** * @notice Open presale */ function openPresale() external auth(OPEN_PRESALE_ROLE) { presale.open(); } /** * @notice Close presale and open trading */ function closePresale() external isInitialized { presale.close(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution token to be spent */ function contribute(uint256 _value) external payable auth(CONTRIBUTE_ROLE) { presale.contribute.value(msg.value)(msg.sender, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external isInitialized { presale.refund(_contributor, _vestedPurchaseId); } /* market making related functions */ /** * @notice Open trading [enabling users to open buy and sell orders] */ function openTrading() external auth(OPEN_TRADING_ROLE) { for (uint256 i = 0; i < toReset.length; i++) { if (tap.rates(toReset[i]) != uint256(0)) { tap.resetTappedToken(toReset[i]); } } marketMaker.open(); } /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { marketMaker.openBuyOrder.value(msg.value)(msg.sender, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { marketMaker.openSellOrder(msg.sender, _collateral, _amount); } /** * @notice Claim the results of `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimSellOrder(_seller, _batchId, _collateral); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage, uint256 _rate, uint256 _floor ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); if (_collateral != ETH) { reserve.addProtectedToken(_collateral); } if (_rate > 0) { tap.addTappedToken(_collateral, _rate, _floor); } } /** * @notice Re-add `_collateral.symbol(): string` as a whitelisted collateral token [if it has been un-whitelisted in the past] * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function reAddCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { marketMaker.removeCollateralToken(_collateral); // the token should still be tapped to avoid being locked // the token should still be protected to avoid being spent } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { marketMaker.updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* tap related functions */ /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { tap.updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { tap.updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TOKEN_TAP_ROLE) { tap.addTappedToken(_token, _rate, _floor); } /** * @notice Update tap for `_token.symbol(): string` with a rate of about `@tokenAmount(_token, 4 * 60 * 24 * 30 * _rate)` per month and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TOKEN_TAP_ROLE) { tap.updateTappedToken(_token, _rate, _floor); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { tap.updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximumWithdrawal(_token): uint256)` from the reserve to the beneficiary * @param _token The address of the token to be transfered from the reserve to the beneficiary */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { tap.withdraw(_token); } /***** public view functions *****/ function token() public view isInitialized returns (address) { return marketMaker.token(); } function contributionToken() public view isInitialized returns (address) { return presale.contributionToken(); } function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return tap.getMaximumWithdrawal(_token); } function collateralsToBeClaimed(address _collateral) public view isInitialized returns (uint256) { return marketMaker.collateralsToBeClaimed(_collateral); } function balanceOf(address _who, address _token) public view isInitialized returns (uint256) { uint256 balance = _token == ETH ? _who.balance : ERC20(_token).staticBalanceOf(_who); if (_who == address(reserve)) { return balance.sub(tap.getMaximumWithdrawal(_token)); } else { return balance; } } /***** internal functions *****/ function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } } // File: @ablack/fundraising-presale/contracts/Presale.sol pragma solidity ^0.4.24; contract Presale is IPresale, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; using SafeMath64 for uint64; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; uint256 public constant PPM = 1000000; // 0% = 0 * 10 ** 4; 1% = 1 * 10 ** 4; 100% = 100 * 10 ** 4 string private constant ERROR_CONTRACT_IS_EOA = "PRESALE_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "PRESALE_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_CONTRIBUTE_TOKEN = "PRESALE_INVALID_CONTRIBUTE_TOKEN"; string private constant ERROR_INVALID_GOAL = "PRESALE_INVALID_GOAL"; string private constant ERROR_INVALID_EXCHANGE_RATE = "PRESALE_INVALID_EXCHANGE_RATE"; string private constant ERROR_INVALID_TIME_PERIOD = "PRESALE_INVALID_TIME_PERIOD"; string private constant ERROR_INVALID_PCT = "PRESALE_INVALID_PCT"; string private constant ERROR_INVALID_STATE = "PRESALE_INVALID_STATE"; string private constant ERROR_INVALID_CONTRIBUTE_VALUE = "PRESALE_INVALID_CONTRIBUTE_VALUE"; string private constant ERROR_INSUFFICIENT_BALANCE = "PRESALE_INSUFFICIENT_BALANCE"; string private constant ERROR_INSUFFICIENT_ALLOWANCE = "PRESALE_INSUFFICIENT_ALLOWANCE"; string private constant ERROR_NOTHING_TO_REFUND = "PRESALE_NOTHING_TO_REFUND"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "PRESALE_TOKEN_TRANSFER_REVERTED"; enum State { Pending, // presale is idle and pending to be started Funding, // presale has started and contributors can purchase tokens Refunding, // presale has not reached goal within period and contributors can claim refunds GoalReached, // presale has reached goal within period and trading is ready to be open Closed // presale has reached goal within period, has been closed and trading has been open } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; address public reserve; address public beneficiary; address public contributionToken; uint256 public goal; uint64 public period; uint256 public exchangeRate; uint64 public vestingCliffPeriod; uint64 public vestingCompletePeriod; uint256 public supplyOfferedPct; uint256 public fundingForBeneficiaryPct; uint64 public openDate; bool public isClosed; uint64 public vestingCliffDate; uint64 public vestingCompleteDate; uint256 public totalRaised; mapping(address => mapping(uint256 => uint256)) public contributions; // contributor => (vestedPurchaseId => tokensSpent) event SetOpenDate (uint64 date); event Close (); event Contribute (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); event Refund (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); /***** external function *****/ /** * @notice Initialize presale * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom a percentage of the raised funds is be to be sent] * @param _contributionToken The address of the token to be used to contribute * @param _goal The goal to be reached by the end of that presale [in contribution token wei] * @param _period The period within which to accept contribution for that presale * @param _exchangeRate The exchangeRate [= 1/price] at which [bonded] tokens are to be purchased for that presale [in PPM] * @param _vestingCliffPeriod The period during which purchased [bonded] tokens are to be cliffed * @param _vestingCompletePeriod The complete period during which purchased [bonded] tokens are to be vested * @param _supplyOfferedPct The percentage of the initial supply of [bonded] tokens to be offered during that presale [in PPM] * @param _fundingForBeneficiaryPct The percentage of the raised contribution tokens to be sent to the beneficiary [instead of the fundraising reserve] when that presale is closed [in PPM] * @param _openDate The date upon which that presale is to be open [ignored if 0] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, address _reserve, address _beneficiary, address _contributionToken, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiary != address(0), ERROR_INVALID_BENEFICIARY); require(isContract(_contributionToken) || _contributionToken == ETH, ERROR_INVALID_CONTRIBUTE_TOKEN); require(_goal > 0, ERROR_INVALID_GOAL); require(_period > 0, ERROR_INVALID_TIME_PERIOD); require(_exchangeRate > 0, ERROR_INVALID_EXCHANGE_RATE); require(_vestingCliffPeriod > _period, ERROR_INVALID_TIME_PERIOD); require(_vestingCompletePeriod > _vestingCliffPeriod, ERROR_INVALID_TIME_PERIOD); require(_supplyOfferedPct > 0 && _supplyOfferedPct <= PPM, ERROR_INVALID_PCT); require(_fundingForBeneficiaryPct >= 0 && _fundingForBeneficiaryPct <= PPM, ERROR_INVALID_PCT); initialized(); controller = _controller; tokenManager = _tokenManager; token = ERC20(_tokenManager.token()); reserve = _reserve; beneficiary = _beneficiary; contributionToken = _contributionToken; goal = _goal; period = _period; exchangeRate = _exchangeRate; vestingCliffPeriod = _vestingCliffPeriod; vestingCompletePeriod = _vestingCompletePeriod; supplyOfferedPct = _supplyOfferedPct; fundingForBeneficiaryPct = _fundingForBeneficiaryPct; if (_openDate != 0) { _setOpenDate(_openDate); } } /** * @notice Open presale [enabling users to contribute] */ function open() external auth(OPEN_ROLE) { require(state() == State.Pending, ERROR_INVALID_STATE); require(openDate == 0, ERROR_INVALID_STATE); _open(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _contributor The address of the contributor * @param _value The amount of contribution token to be spent */ function contribute(address _contributor, uint256 _value) external payable nonReentrant auth(CONTRIBUTE_ROLE) { require(state() == State.Funding, ERROR_INVALID_STATE); require(_value != 0, ERROR_INVALID_CONTRIBUTE_VALUE); if (contributionToken == ETH) { require(msg.value == _value, ERROR_INVALID_CONTRIBUTE_VALUE); } else { require(msg.value == 0, ERROR_INVALID_CONTRIBUTE_VALUE); } _contribute(_contributor, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external nonReentrant isInitialized { require(state() == State.Refunding, ERROR_INVALID_STATE); _refund(_contributor, _vestedPurchaseId); } /** * @notice Close presale and open trading */ function close() external nonReentrant isInitialized { require(state() == State.GoalReached, ERROR_INVALID_STATE); _close(); } /***** public view functions *****/ /** * @notice Computes the amount of [bonded] tokens that would be purchased for `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution tokens to be used in that computation */ function contributionToTokens(uint256 _value) public view isInitialized returns (uint256) { return _value.mul(exchangeRate).div(PPM); } function contributionToken() public view isInitialized returns (address) { return contributionToken; } /** * @notice Returns the current state of that presale */ function state() public view isInitialized returns (State) { if (openDate == 0 || openDate > getTimestamp64()) { return State.Pending; } if (totalRaised >= goal) { if (isClosed) { return State.Closed; } else { return State.GoalReached; } } if (_timeSinceOpen() < period) { return State.Funding; } else { return State.Refunding; } } /***** internal functions *****/ function _timeSinceOpen() internal view returns (uint64) { if (openDate == 0) { return 0; } else { return getTimestamp64().sub(openDate); } } function _setOpenDate(uint64 _date) internal { require(_date >= getTimestamp64(), ERROR_INVALID_TIME_PERIOD); openDate = _date; _setVestingDatesWhenOpenDateIsKnown(); emit SetOpenDate(_date); } function _setVestingDatesWhenOpenDateIsKnown() internal { vestingCliffDate = openDate.add(vestingCliffPeriod); vestingCompleteDate = openDate.add(vestingCompletePeriod); } function _open() internal { _setOpenDate(getTimestamp64()); } function _contribute(address _contributor, uint256 _value) internal { uint256 value = totalRaised.add(_value) > goal ? goal.sub(totalRaised) : _value; if (contributionToken == ETH && _value > value) { msg.sender.transfer(_value.sub(value)); } // (contributor) ~~~> contribution tokens ~~~> (presale) if (contributionToken != ETH) { require(ERC20(contributionToken).balanceOf(_contributor) >= value, ERROR_INSUFFICIENT_BALANCE); require(ERC20(contributionToken).allowance(_contributor, address(this)) >= value, ERROR_INSUFFICIENT_ALLOWANCE); _transfer(contributionToken, _contributor, address(this), value); } // (mint ✨) ~~~> project tokens ~~~> (contributor) uint256 tokensToSell = contributionToTokens(value); tokenManager.issue(tokensToSell); uint256 vestedPurchaseId = tokenManager.assignVested( _contributor, tokensToSell, openDate, vestingCliffDate, vestingCompleteDate, true /* revokable */ ); totalRaised = totalRaised.add(value); // register contribution tokens spent in this purchase for a possible upcoming refund contributions[_contributor][vestedPurchaseId] = value; emit Contribute(_contributor, value, tokensToSell, vestedPurchaseId); } function _refund(address _contributor, uint256 _vestedPurchaseId) internal { // recall how much contribution tokens are to be refund for this purchase uint256 tokensToRefund = contributions[_contributor][_vestedPurchaseId]; require(tokensToRefund > 0, ERROR_NOTHING_TO_REFUND); contributions[_contributor][_vestedPurchaseId] = 0; // (presale) ~~~> contribution tokens ~~~> (contributor) _transfer(contributionToken, address(this), _contributor, tokensToRefund); /** * NOTE * the following lines assume that _contributor has not transfered any of its vested tokens * for now TokenManager does not handle switching the transferrable status of its underlying token * there is thus no way to enforce non-transferrability during the presale phase only * this will be updated in a later version */ // (contributor) ~~~> project tokens ~~~> (token manager) (uint256 tokensSold,,,,) = tokenManager.getVesting(_contributor, _vestedPurchaseId); tokenManager.revokeVesting(_contributor, _vestedPurchaseId); // (token manager) ~~~> project tokens ~~~> (burn 💥) tokenManager.burn(address(tokenManager), tokensSold); emit Refund(_contributor, tokensToRefund, tokensSold, _vestedPurchaseId); } function _close() internal { isClosed = true; // (presale) ~~~> contribution tokens ~~~> (beneficiary) uint256 fundsForBeneficiary = totalRaised.mul(fundingForBeneficiaryPct).div(PPM); if (fundsForBeneficiary > 0) { _transfer(contributionToken, address(this), beneficiary, fundsForBeneficiary); } // (presale) ~~~> contribution tokens ~~~> (reserve) uint256 tokensForReserve = contributionToken == ETH ? address(this).balance : ERC20(contributionToken).balanceOf(address(this)); _transfer(contributionToken, address(this), reserve, tokensForReserve); // (mint ✨) ~~~> project tokens ~~~> (beneficiary) uint256 tokensForBeneficiary = token.totalSupply().mul(PPM.sub(supplyOfferedPct)).div(supplyOfferedPct); tokenManager.issue(tokensForBeneficiary); tokenManager.assignVested( beneficiary, tokensForBeneficiary, openDate, vestingCliffDate, vestingCompleteDate, false /* revokable */ ); // open trading controller.openTrading(); emit Close(); } function _transfer(address _token, address _from, address _to, uint256 _amount) internal { if (_token == ETH) { require(_from == address(this), ERROR_TOKEN_TRANSFER_REVERTED); require(_to != address(this), ERROR_TOKEN_TRANSFER_REVERTED); _to.transfer(_amount); } else { if (_from == address(this)) { require(ERC20(_token).safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } else { require(ERC20(_token).safeTransferFrom(_from, _to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } } } } // File: @ablack/fundraising-tap/contracts/Tap.sol pragma solidity 0.4.24; contract Tap is ITap, TimeHelpers, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_CONTROLLER_ROLE = keccak256("UPDATE_CONTROLLER_ROLE"); bytes32 public constant UPDATE_RESERVE_ROLE = keccak256("UPDATE_RESERVE_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TAPPED_TOKEN_ROLE = keccak256("ADD_TAPPED_TOKEN_ROLE"); bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = keccak256("REMOVE_TAPPED_TOKEN_ROLE"); bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = keccak256("UPDATE_TAPPED_TOKEN_ROLE"); bytes32 public constant RESET_TAPPED_TOKEN_ROLE = keccak256("RESET_TAPPED_TOKEN_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_CONTROLLER_ROLE = 0x454b5d0dbb74f012faf1d3722ea441689f97dc957dd3ca5335b4969586e5dc30; bytes32 public constant UPDATE_RESERVE_ROLE = 0x7984c050833e1db850f5aa7476710412fd2983fcec34da049502835ad7aed4f7; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TAPPED_TOKEN_ROLE = 0x5bc3b608e6be93b75a1c472a4a5bea3d31eabae46bf968e4bc4c7701562114dc; bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = 0xd76960be78bfedc5b40ce4fa64a2f8308f39dd2cbb1f9676dbc4ce87b817befd; bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = 0x83201394534c53ae0b4696fd49a933082d3e0525aa5a3d0a14a2f51e12213288; bytes32 public constant RESET_TAPPED_TOKEN_ROLE = 0x294bf52c518669359157a9fe826e510dfc3dbd200d44bf77ec9536bff34bc29e; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 string private constant ERROR_CONTRACT_IS_EOA = "TAP_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "TAP_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "TAP_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_FLOOR_DECREASE_PCT = "TAP_INVALID_FLOOR_DECREASE_PCT"; string private constant ERROR_INVALID_TOKEN = "TAP_INVALID_TOKEN"; string private constant ERROR_INVALID_TAP_RATE = "TAP_INVALID_TAP_RATE"; string private constant ERROR_INVALID_TAP_UPDATE = "TAP_INVALID_TAP_UPDATE"; string private constant ERROR_TOKEN_ALREADY_TAPPED = "TAP_TOKEN_ALREADY_TAPPED"; string private constant ERROR_TOKEN_NOT_TAPPED = "TAP_TOKEN_NOT_TAPPED"; string private constant ERROR_WITHDRAWAL_AMOUNT_ZERO = "TAP_WITHDRAWAL_AMOUNT_ZERO"; IAragonFundraisingController public controller; Vault public reserve; address public beneficiary; uint256 public batchBlocks; uint256 public maximumTapRateIncreasePct; uint256 public maximumTapFloorDecreasePct; mapping (address => uint256) public tappedAmounts; mapping (address => uint256) public rates; mapping (address => uint256) public floors; mapping (address => uint256) public lastTappedAmountUpdates; // batch ids [block numbers] mapping (address => uint256) public lastTapUpdates; // timestamps event UpdateBeneficiary (address indexed beneficiary); event UpdateMaximumTapRateIncreasePct (uint256 maximumTapRateIncreasePct); event UpdateMaximumTapFloorDecreasePct(uint256 maximumTapFloorDecreasePct); event AddTappedToken (address indexed token, uint256 rate, uint256 floor); event RemoveTappedToken (address indexed token); event UpdateTappedToken (address indexed token, uint256 rate, uint256 floor); event ResetTappedToken (address indexed token); event UpdateTappedAmount (address indexed token, uint256 tappedAmount); event Withdraw (address indexed token, uint256 amount); /***** external functions *****/ /** * @notice Initialize tap * @param _controller The address of the controller contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom funds are to be withdrawn] * @param _batchBlocks The number of blocks batches are to last * @param _maximumTapRateIncreasePct The maximum tap rate increase percentage allowed [in PCT_BASE] * @param _maximumTapFloorDecreasePct The maximum tap floor decrease percentage allowed [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _maximumTapRateIncreasePct, uint256 _maximumTapFloorDecreasePct ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks != 0, ERROR_INVALID_BATCH_BLOCKS); require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); initialized(); controller = _controller; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; maximumTapRateIncreasePct = _maximumTapRateIncreasePct; maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom funds are to be withdrawn] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { _updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); _updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TAPPED_TOKEN_ROLE) { require(_tokenIsContractOrETH(_token), ERROR_INVALID_TOKEN); require(!_tokenIsTapped(_token), ERROR_TOKEN_ALREADY_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); _addTappedToken(_token, _rate, _floor); } /** * @notice Remove tap for `_token.symbol(): string` * @param _token The address of the token to be un-tapped */ function removeTappedToken(address _token) external auth(REMOVE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _removeTappedToken(_token); } /** * @notice Update tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); require(_tapUpdateIsValid(_token, _rate, _floor), ERROR_INVALID_TAP_UPDATE); _updateTappedToken(_token, _rate, _floor); } /** * @notice Reset tap timestamps for `_token.symbol(): string` * @param _token The address of the token whose tap timestamps are to be reset */ function resetTappedToken(address _token) external auth(RESET_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _resetTappedToken(_token); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximalWithdrawal(_token): uint256)` from `self.reserve()` to `self.beneficiary()` * @param _token The address of the token to be transfered */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); uint256 amount = _updateTappedAmount(_token); require(amount > 0, ERROR_WITHDRAWAL_AMOUNT_ZERO); _withdraw(_token, amount); } /***** public view functions *****/ function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return _tappedAmount(_token); } function rates(address _token) public view isInitialized returns (uint256) { return rates[_token]; } /***** internal functions *****/ /* computation functions */ function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } function _tappedAmount(address _token) internal view returns (uint256) { uint256 toBeKept = controller.collateralsToBeClaimed(_token).add(floors[_token]); uint256 balance = _token == ETH ? address(reserve).balance : ERC20(_token).staticBalanceOf(reserve); uint256 flow = (_currentBatchId().sub(lastTappedAmountUpdates[_token])).mul(rates[_token]); uint256 tappedAmount = tappedAmounts[_token].add(flow); /** * whatever happens enough collateral should be * kept in the reserve pool to guarantee that * its balance is kept above the floor once * all pending sell orders are claimed */ /** * the reserve's balance is already below the balance to be kept * the tapped amount should be reset to zero */ if (balance <= toBeKept) { return 0; } /** * the reserve's balance minus the upcoming tap flow would be below the balance to be kept * the flow should be reduced to balance - toBeKept */ if (balance <= toBeKept.add(tappedAmount)) { return balance.sub(toBeKept); } /** * the reserve's balance minus the upcoming flow is above the balance to be kept * the flow can be added to the tapped amount */ return tappedAmount; } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _maximumTapFloorDecreasePctIsValid(uint256 _maximumTapFloorDecreasePct) internal pure returns (bool) { return _maximumTapFloorDecreasePct <= PCT_BASE; } function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } function _tokenIsTapped(address _token) internal view returns (bool) { return rates[_token] != uint256(0); } function _tapRateIsValid(uint256 _rate) internal pure returns (bool) { return _rate != 0; } function _tapUpdateIsValid(address _token, uint256 _rate, uint256 _floor) internal view returns (bool) { return _tapRateUpdateIsValid(_token, _rate) && _tapFloorUpdateIsValid(_token, _floor); } function _tapRateUpdateIsValid(address _token, uint256 _rate) internal view returns (bool) { uint256 rate = rates[_token]; if (_rate <= rate) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (_rate.mul(PCT_BASE) <= rate.mul(PCT_BASE.add(maximumTapRateIncreasePct))) { return true; } return false; } function _tapFloorUpdateIsValid(address _token, uint256 _floor) internal view returns (bool) { uint256 floor = floors[_token]; if (_floor >= floor) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (maximumTapFloorDecreasePct >= PCT_BASE) { return true; } if (_floor.mul(PCT_BASE) >= floor.mul(PCT_BASE.sub(maximumTapFloorDecreasePct))) { return true; } return false; } /* state modifying functions */ function _updateTappedAmount(address _token) internal returns (uint256) { uint256 tappedAmount = _tappedAmount(_token); lastTappedAmountUpdates[_token] = _currentBatchId(); tappedAmounts[_token] = tappedAmount; emit UpdateTappedAmount(_token, tappedAmount); return tappedAmount; } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) internal { maximumTapRateIncreasePct = _maximumTapRateIncreasePct; emit UpdateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } function _updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) internal { maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; emit UpdateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } function _addTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * 1. if _token is tapped in the middle of a batch it will * reach the next batch faster than what it normally takes * to go through a batch [e.g. one block later] * 2. this will allow for a higher withdrawal than expected * a few blocks after _token is tapped * 3. this is not a problem because this extra amount is * static [at most rates[_token] * batchBlocks] and does * not increase in time */ rates[_token] = _rate; floors[_token] = _floor; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit AddTappedToken(_token, _rate, _floor); } function _removeTappedToken(address _token) internal { delete tappedAmounts[_token]; delete rates[_token]; delete floors[_token]; delete lastTappedAmountUpdates[_token]; delete lastTapUpdates[_token]; emit RemoveTappedToken(_token); } function _updateTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * withdraw before updating to keep the reserve * actual balance [balance - virtual withdrawal] * continuous in time [though a floor update can * still break this continuity] */ uint256 amount = _updateTappedAmount(_token); if (amount > 0) { _withdraw(_token, amount); } rates[_token] = _rate; floors[_token] = _floor; lastTapUpdates[_token] = getTimestamp(); emit UpdateTappedToken(_token, _rate, _floor); } function _resetTappedToken(address _token) internal { tappedAmounts[_token] = 0; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit ResetTappedToken(_token); } function _withdraw(address _token, uint256 _amount) internal { tappedAmounts[_token] = tappedAmounts[_token].sub(_amount); reserve.transfer(_token, beneficiary, _amount); // vault contract's transfer method already reverts on error emit Withdraw(_token, _amount); } } // File: contracts/AavegotchiTBCTemplate.sol pragma solidity 0.4.24; contract AavegotchiTBCTemplate is EtherTokenConstant, BaseTemplate { string private constant ERROR_BAD_SETTINGS = "FM_BAD_SETTINGS"; string private constant ERROR_MISSING_CACHE = "FM_MISSING_CACHE"; bool private constant BOARD_TRANSFERABLE = false; uint8 private constant BOARD_TOKEN_DECIMALS = uint8(0); uint256 private constant BOARD_MAX_PER_ACCOUNT = uint256(1); bool private constant SHARE_TRANSFERABLE = true; uint8 private constant SHARE_TOKEN_DECIMALS = uint8(18); uint256 private constant SHARE_MAX_PER_ACCOUNT = uint256(0); uint64 private constant DEFAULT_FINANCE_PERIOD = uint64(30 days); uint256 private constant BUY_FEE_PCT = 0; uint256 private constant SELL_FEE_PCT = 0; uint32 private constant DAI_RESERVE_RATIO = 333333; // 33% uint32 private constant ANT_RESERVE_RATIO = 10000; // 1% bytes32 private constant BANCOR_FORMULA_ID = 0xd71dde5e4bea1928026c1779bde7ed27bd7ef3d0ce9802e4117631eb6fa4ed7d; bytes32 private constant PRESALE_ID = 0x5de9bbdeaf6584c220c7b7f1922383bcd8bbcd4b48832080afd9d5ebf9a04df5; bytes32 private constant MARKET_MAKER_ID = 0xc2bb88ab974c474221f15f691ed9da38be2f5d37364180cec05403c656981bf0; bytes32 private constant ARAGON_FUNDRAISING_ID = 0x668ac370eed7e5861234d1c0a1e512686f53594fcb887e5bcecc35675a4becac; bytes32 private constant TAP_ID = 0x82967efab7144b764bc9bca2f31a721269b6618c0ff4e50545737700a5e9c9dc; struct Cache { address dao; address boardTokenManager; address boardVoting; address vault; address finance; address shareVoting; address shareTokenManager; address reserve; address presale; address marketMaker; address tap; address controller; } address[] public collaterals; mapping (address => Cache) private cache; constructor( DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID, address _dai, address _ant ) BaseTemplate(_daoFactory, _ens, _miniMeFactory, _aragonID) public { _ensureAragonIdIsValid(_aragonID); _ensureMiniMeFactoryIsValid(_miniMeFactory); require(isContract(_dai), ERROR_BAD_SETTINGS); require(isContract(_ant), ERROR_BAD_SETTINGS); require(_dai != _ant, ERROR_BAD_SETTINGS); collaterals.push(_dai); collaterals.push(_ant); } /***** external functions *****/ function prepareInstance( string _boardTokenName, string _boardTokenSymbol, address[] _boardMembers, uint64[3] _boardVotingSettings, uint64 _financePeriod ) external { require(_boardMembers.length > 0, ERROR_BAD_SETTINGS); require(_boardVotingSettings.length == 3, ERROR_BAD_SETTINGS); // deploy DAO (Kernel dao, ACL acl) = _createDAO(); // deploy board token MiniMeToken boardToken = _createToken(_boardTokenName, _boardTokenSymbol, BOARD_TOKEN_DECIMALS); // install board apps TokenManager tm = _installBoardApps(dao, boardToken, _boardVotingSettings, _financePeriod); // mint board tokens _mintTokens(acl, tm, _boardMembers, 1); // cache DAO _cacheDao(dao); } function installShareApps( string _shareTokenName, string _shareTokenSymbol, uint64[3] _shareVotingSettings ) external { require(_shareVotingSettings.length == 3, ERROR_BAD_SETTINGS); _ensureBoardAppsCache(); Kernel dao = _daoCache(); // deploy share token MiniMeToken shareToken = _createToken(_shareTokenName, _shareTokenSymbol, SHARE_TOKEN_DECIMALS); // install share apps _installShareApps(dao, shareToken, _shareVotingSettings); // setup board apps permissions [now that share apps have been installed] _setupBoardPermissions(dao); } function installFundraisingApps( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) external { _ensureShareAppsCache(); Kernel dao = _daoCache(); // install fundraising apps _installFundraisingApps( dao, _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct ); // setup share apps permissions [now that fundraising apps have been installed] _setupSharePermissions(dao); // setup fundraising apps permissions _setupFundraisingPermissions(dao); } function finalizeInstance( string _id, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) external { require(bytes(_id).length > 0, ERROR_BAD_SETTINGS); require(_virtualSupplies.length == 2, ERROR_BAD_SETTINGS); require(_virtualBalances.length == 2, ERROR_BAD_SETTINGS); require(_slippages.length == 2, ERROR_BAD_SETTINGS); _ensureFundraisingAppsCache(); Kernel dao = _daoCache(); ACL acl = ACL(dao.acl()); (, Voting shareVoting) = _shareAppsCache(); // setup collaterals _setupCollaterals(dao, _virtualSupplies, _virtualBalances, _slippages, _rateDAI, _floorDAI); // setup EVM script registry permissions _createEvmScriptsRegistryPermissions(acl, shareVoting, shareVoting); // clear DAO permissions _transferRootPermissionsFromTemplateAndFinalizeDAO(dao, shareVoting, shareVoting); // register id _registerID(_id, address(dao)); // clear cache _clearCache(); } /***** internal apps installation functions *****/ function _installBoardApps(Kernel _dao, MiniMeToken _token, uint64[3] _votingSettings, uint64 _financePeriod) internal returns (TokenManager) { TokenManager tm = _installTokenManagerApp(_dao, _token, BOARD_TRANSFERABLE, BOARD_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _token, _votingSettings); Vault vault = _installVaultApp(_dao); Finance finance = _installFinanceApp(_dao, vault, _financePeriod == 0 ? DEFAULT_FINANCE_PERIOD : _financePeriod); _cacheBoardApps(tm, voting, vault, finance); return tm; } function _installShareApps(Kernel _dao, MiniMeToken _shareToken, uint64[3] _shareVotingSettings) internal { TokenManager tm = _installTokenManagerApp(_dao, _shareToken, SHARE_TRANSFERABLE, SHARE_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _shareToken, _shareVotingSettings); _cacheShareApps(tm, voting); } function _installFundraisingApps( Kernel _dao, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) internal { _proxifyFundraisingApps(_dao); _initializePresale( _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); _initializeMarketMaker(_batchBlocks); _initializeTap(_batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); _initializeController(); } function _proxifyFundraisingApps(Kernel _dao) internal { Agent reserve = _installNonDefaultAgentApp(_dao); Presale presale = Presale(_registerApp(_dao, PRESALE_ID)); BatchedBancorMarketMaker marketMaker = BatchedBancorMarketMaker(_registerApp(_dao, MARKET_MAKER_ID)); Tap tap = Tap(_registerApp(_dao, TAP_ID)); AragonFundraisingController controller = AragonFundraisingController(_registerApp(_dao, ARAGON_FUNDRAISING_ID)); _cacheFundraisingApps(reserve, presale, marketMaker, tap, controller); } /***** internal apps initialization functions *****/ function _initializePresale( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) internal { _presaleCache().initialize( _controllerCache(), _shareTMCache(), _reserveCache(), _vaultCache(), collaterals[0], _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); } function _initializeMarketMaker(uint256 _batchBlocks) internal { IBancorFormula bancorFormula = IBancorFormula(_latestVersionAppBase(BANCOR_FORMULA_ID)); (,, Vault beneficiary,) = _boardAppsCache(); (TokenManager shareTM,) = _shareAppsCache(); (Agent reserve,, BatchedBancorMarketMaker marketMaker,, AragonFundraisingController controller) = _fundraisingAppsCache(); marketMaker.initialize(controller, shareTM, bancorFormula, reserve, beneficiary, _batchBlocks, BUY_FEE_PCT, SELL_FEE_PCT); } function _initializeTap(uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct) internal { (,, Vault beneficiary,) = _boardAppsCache(); (Agent reserve,,, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); tap.initialize(controller, reserve, beneficiary, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); } function _initializeController() internal { (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); address[] memory toReset = new address[](1); toReset[0] = collaterals[0]; controller.initialize(presale, marketMaker, reserve, tap, toReset); } /***** internal setup functions *****/ function _setupCollaterals( Kernel _dao, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) internal { ACL acl = ACL(_dao.acl()); (, Voting shareVoting) = _shareAppsCache(); (,,,, AragonFundraisingController controller) = _fundraisingAppsCache(); // create and grant ADD_COLLATERAL_TOKEN_ROLE to this template _createPermissionForTemplate(acl, address(controller), controller.ADD_COLLATERAL_TOKEN_ROLE()); // add DAI both as a protected collateral and a tapped token controller.addCollateralToken( collaterals[0], _virtualSupplies[0], _virtualBalances[0], DAI_RESERVE_RATIO, _slippages[0], _rateDAI, _floorDAI ); // add ANT as a protected collateral [but not as a tapped token] controller.addCollateralToken( collaterals[1], _virtualSupplies[1], _virtualBalances[1], ANT_RESERVE_RATIO, _slippages[1], 0, 0 ); // transfer ADD_COLLATERAL_TOKEN_ROLE _transferPermissionFromTemplate(acl, controller, shareVoting, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); } /***** internal permissions functions *****/ function _setupBoardPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); // token manager _createTokenManagerPermissions(acl, boardTM, boardVoting, shareVoting); // voting _createVotingPermissions(acl, boardVoting, boardVoting, boardTM, shareVoting); // vault _createVaultPermissions(acl, vault, finance, shareVoting); // finance _createFinancePermissions(acl, finance, boardVoting, shareVoting); _createFinanceCreatePaymentsPermission(acl, finance, boardVoting, shareVoting); } function _setupSharePermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM,,,) = _boardAppsCache(); (TokenManager shareTM, Voting shareVoting) = _shareAppsCache(); (, Presale presale, BatchedBancorMarketMaker marketMaker,,) = _fundraisingAppsCache(); // token manager address[] memory grantees = new address[](2); grantees[0] = address(marketMaker); grantees[1] = address(presale); acl.createPermission(marketMaker, shareTM, shareTM.MINT_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ISSUE_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ASSIGN_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.REVOKE_VESTINGS_ROLE(), shareVoting); _createPermissions(acl, grantees, shareTM, shareTM.BURN_ROLE(), shareVoting); // voting _createVotingPermissions(acl, shareVoting, shareVoting, boardTM, shareVoting); } function _setupFundraisingPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (, Voting boardVoting,,) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); // reserve address[] memory grantees = new address[](2); grantees[0] = address(tap); grantees[1] = address(marketMaker); acl.createPermission(shareVoting, reserve, reserve.SAFE_EXECUTE_ROLE(), shareVoting); acl.createPermission(controller, reserve, reserve.ADD_PROTECTED_TOKEN_ROLE(), shareVoting); _createPermissions(acl, grantees, reserve, reserve.TRANSFER_ROLE(), shareVoting); // presale acl.createPermission(controller, presale, presale.OPEN_ROLE(), shareVoting); acl.createPermission(controller, presale, presale.CONTRIBUTE_ROLE(), shareVoting); // market maker acl.createPermission(controller, marketMaker, marketMaker.OPEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_FEES_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_SELL_ORDER_ROLE(), shareVoting); // tap acl.createPermission(controller, tap, tap.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.ADD_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.RESET_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.WITHDRAW_ROLE(), shareVoting); // controller // ADD_COLLATERAL_TOKEN_ROLE is handled later [after collaterals have been added] acl.createPermission(shareVoting, controller, controller.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_FEES_ROLE(), shareVoting); // acl.createPermission(shareVoting, controller, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.ADD_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(boardVoting, controller, controller.OPEN_PRESALE_ROLE(), shareVoting); acl.createPermission(presale, controller, controller.OPEN_TRADING_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.CONTRIBUTE_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_SELL_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.WITHDRAW_ROLE(), shareVoting); } /***** internal cache functions *****/ function _cacheDao(Kernel _dao) internal { Cache storage c = cache[msg.sender]; c.dao = address(_dao); } function _cacheBoardApps(TokenManager _boardTM, Voting _boardVoting, Vault _vault, Finance _finance) internal { Cache storage c = cache[msg.sender]; c.boardTokenManager = address(_boardTM); c.boardVoting = address(_boardVoting); c.vault = address(_vault); c.finance = address(_finance); } function _cacheShareApps(TokenManager _shareTM, Voting _shareVoting) internal { Cache storage c = cache[msg.sender]; c.shareTokenManager = address(_shareTM); c.shareVoting = address(_shareVoting); } function _cacheFundraisingApps(Agent _reserve, Presale _presale, BatchedBancorMarketMaker _marketMaker, Tap _tap, AragonFundraisingController _controller) internal { Cache storage c = cache[msg.sender]; c.reserve = address(_reserve); c.presale = address(_presale); c.marketMaker = address(_marketMaker); c.tap = address(_tap); c.controller = address(_controller); } function _daoCache() internal view returns (Kernel dao) { Cache storage c = cache[msg.sender]; dao = Kernel(c.dao); } function _boardAppsCache() internal view returns (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) { Cache storage c = cache[msg.sender]; boardTM = TokenManager(c.boardTokenManager); boardVoting = Voting(c.boardVoting); vault = Vault(c.vault); finance = Finance(c.finance); } function _shareAppsCache() internal view returns (TokenManager shareTM, Voting shareVoting) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); shareVoting = Voting(c.shareVoting); } function _fundraisingAppsCache() internal view returns ( Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller ) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); presale = Presale(c.presale); marketMaker = BatchedBancorMarketMaker(c.marketMaker); tap = Tap(c.tap); controller = AragonFundraisingController(c.controller); } function _clearCache() internal { Cache storage c = cache[msg.sender]; delete c.dao; delete c.boardTokenManager; delete c.boardVoting; delete c.vault; delete c.finance; delete c.shareVoting; delete c.shareTokenManager; delete c.reserve; delete c.presale; delete c.marketMaker; delete c.tap; delete c.controller; } /** * NOTE * the following functions are only needed for the presale * initialization function [which we can't compile otherwise * because of a `stack too deep` error] */ function _vaultCache() internal view returns (Vault vault) { Cache storage c = cache[msg.sender]; vault = Vault(c.vault); } function _shareTMCache() internal view returns (TokenManager shareTM) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); } function _reserveCache() internal view returns (Agent reserve) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); } function _presaleCache() internal view returns (Presale presale) { Cache storage c = cache[msg.sender]; presale = Presale(c.presale); } function _controllerCache() internal view returns (AragonFundraisingController controller) { Cache storage c = cache[msg.sender]; controller = AragonFundraisingController(c.controller); } /***** internal check functions *****/ function _ensureBoardAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.boardTokenManager != address(0) && c.boardVoting != address(0) && c.vault != address(0) && c.finance != address(0), ERROR_MISSING_CACHE ); } function _ensureShareAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.shareTokenManager != address(0) && c.shareVoting != address(0), ERROR_MISSING_CACHE ); } function _ensureFundraisingAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.reserve != address(0) && c.presale != address(0) && c.marketMaker != address(0) && c.tap != address(0) && c.controller != address(0), ERROR_MISSING_CACHE ); } /***** internal utils functions *****/ function _registerApp(Kernel _dao, bytes32 _appId) internal returns (address) { address proxy = _dao.newAppInstance(_appId, _latestVersionAppBase(_appId)); emit InstalledApp(proxy, _appId); return proxy; } }
Tell whether an employee is still active or not _employee Employee struct in storage return True if the employee exists and has an end date that has not been reached yet, false otherwise/
function _isEmployeeActive(Employee storage _employee) internal view returns (bool) { return _employee.endDate >= getTimestamp64(); }
451,209
./partial_match/4/0x8045138934d51A3B6F95B846b59BD81e63238ab1/sources/animalMain.sol
TO DO 請使用require判斷要轉的動物id是不是轉移者的增加受贈者的擁有動物數量減少轉出者的擁有動物數量動物所有權轉移
function transfer(address _to, uint256 _tokenId) public { require(animalToOwner[_tokenId]==msg.sender); ownerAnimalCount[_to]=ownerAnimalCount[_to].add(1); ownerAnimalCount[msg.sender]=ownerAnimalCount[msg.sender].sub(1); animalToOwner[_tokenId] = _to; emit Transfer(msg.sender, _to, _tokenId); }
8,739,830
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import {MemberToken} from "@orcaprotocol/contracts/contracts/MemberToken.sol"; import {ControllerV1} from "@orcaprotocol/contracts/contracts/ControllerV1.sol"; import {TimelockController} from "@openzeppelin/contracts/governance/TimelockController.sol"; import {CoreRef} from "../refs/CoreRef.sol"; import {ICore} from "../core/ICore.sol"; import {Core} from "../core/Core.sol"; import {TribeRoles} from "../core/TribeRoles.sol"; import {IPodAdminGateway} from "./interfaces/IPodAdminGateway.sol"; import {IPodFactory} from "./interfaces/IPodFactory.sol"; /// @title PodAdminGateway for TRIBE Governance pods /// @notice Acts as a gateway for admin functionality and vetos in the TRIBE governance pod system /// @dev Contract is intended to be set as the podAdmin for all deployed Orca pods. Specifically enables: /// 1. Adding a member to a pod /// 2. Removing a member from a pod /// 3. Transferring a pod member /// 4. Toggling a pod membership transfer switch /// 5. Vetoing a pod proposal contract PodAdminGateway is CoreRef, IPodAdminGateway { /// @notice Orca membership token for the pods. Handles permissioning pod members MemberToken private immutable memberToken; /// @notice Pod factory which creates optimistic pods and acts as a source of information IPodFactory public immutable podFactory; constructor( address _core, address _memberToken, address _podFactory ) CoreRef(_core) { memberToken = MemberToken(_memberToken); podFactory = IPodFactory(_podFactory); } //////////////////////// GETTERS //////////////////////////////// /// @notice Calculate the specific pod admin role identifier /// @dev This role is able to add pod members, remove pod members, lock and unlock transfers and veto /// proposals function getSpecificPodAdminRole(uint256 _podId) public pure override returns (bytes32) { return keccak256(abi.encode(_podId, "_ORCA_POD", "_ADMIN")); } /// @notice Calculate the specific pod guardian role identifier /// @dev This role is able to remove pod members and veto pod proposals function getSpecificPodGuardianRole(uint256 _podId) public pure override returns (bytes32) { return keccak256(abi.encode(_podId, "_ORCA_POD", "_GUARDIAN")); } ///////////////////////// ADMIN PRIVILEDGES //////////////////////////// /// @notice Admin functionality to add a member to a pod /// @dev Permissioned to GOVERNOR, POD_ADMIN and POD_ADD_MEMBER_ROLE function addPodMember(uint256 _podId, address _member) external override hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId)) { _addMemberToPod(_podId, _member); } /// @notice Internal method to add a member to a pod function _addMemberToPod(uint256 _podId, address _member) internal { emit AddPodMember(_podId, _member); memberToken.mint(_member, _podId, bytes("")); } /// @notice Admin functionality to batch add a member to a pod /// @dev Permissioned to GOVERNOR, POD_ADMIN and POD_ADMIN_REMOVE_MEMBER function batchAddPodMember(uint256 _podId, address[] calldata _members) external override hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId)) { uint256 numMembers = _members.length; for (uint256 i = 0; i < numMembers; ) { _addMemberToPod(_podId, _members[i]); // i is constrained by being < _members.length unchecked { i += 1; } } } /// @notice Admin functionality to remove a member from a pod. /// @dev Permissioned to GOVERNOR, POD_ADMIN, GUARDIAN and POD_ADMIN_REMOVE_MEMBER function removePodMember(uint256 _podId, address _member) external override hasAnyOfFiveRoles( TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, TribeRoles.GUARDIAN, getSpecificPodGuardianRole(_podId), getSpecificPodAdminRole(_podId) ) { _removePodMember(_podId, _member); } /// @notice Internal method to remove a member from a pod function _removePodMember(uint256 _podId, address _member) internal { emit RemovePodMember(_podId, _member); memberToken.burn(_member, _podId); } /// @notice Admin functionality to batch remove a member from a pod /// @dev Permissioned to GOVERNOR, POD_ADMIN, GUARDIAN and POD_ADMIN_REMOVE_MEMBER function batchRemovePodMember(uint256 _podId, address[] calldata _members) external override hasAnyOfFiveRoles( TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, TribeRoles.GUARDIAN, getSpecificPodGuardianRole(_podId), getSpecificPodAdminRole(_podId) ) { uint256 numMembers = _members.length; for (uint256 i = 0; i < numMembers; ) { _removePodMember(_podId, _members[i]); // i is constrained by being < _members.length unchecked { i += 1; } } } /// @notice Admin functionality to turn off pod membership transfer /// @dev Permissioned to GOVERNOR, POD_ADMIN and the specific pod admin role function lockMembershipTransfers(uint256 _podId) external override hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId)) { _setMembershipTransferLock(_podId, true); } /// @notice Admin functionality to turn on pod membership transfers /// @dev Permissioned to GOVERNOR, POD_ADMIN and the specific pod admin role function unlockMembershipTransfers(uint256 _podId) external override hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId)) { _setMembershipTransferLock(_podId, false); } /// @notice Internal method to toggle a pod membership transfer lock function _setMembershipTransferLock(uint256 _podId, bool _lock) internal { ControllerV1 podController = ControllerV1(memberToken.memberController(_podId)); podController.setPodTransferLock(_podId, _lock); emit PodMembershipTransferLock(_podId, _lock); } /// @notice Transfer the admin of a pod to a new address /// @dev Permissioned to GOVERNOR, POD_ADMIN and the specific pod admin role function transferAdmin(uint256 _podId, address _newAdmin) external hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId)) { ControllerV1 podController = ControllerV1(memberToken.memberController(_podId)); address oldPodAdmin = podController.podAdmin(_podId); podController.updatePodAdmin(_podId, _newAdmin); emit UpdatePodAdmin(_podId, oldPodAdmin, _newAdmin); } /////////////// VETO CONTROLLER ///////////////// /// @notice Allow a proposal to be vetoed in a pod timelock /// @dev Permissioned to GOVERNOR, POD_VETO_ADMIN, GUARDIAN, POD_ADMIN and the specific /// pod admin and guardian roles function veto(uint256 _podId, bytes32 _proposalId) external override hasAnyOfSixRoles( TribeRoles.GOVERNOR, TribeRoles.POD_VETO_ADMIN, TribeRoles.GUARDIAN, TribeRoles.POD_ADMIN, getSpecificPodGuardianRole(_podId), getSpecificPodAdminRole(_podId) ) { address _podTimelock = podFactory.getPodTimelock(_podId); emit VetoTimelock(_podId, _podTimelock, _proposalId); TimelockController(payable(_podTimelock)).cancel(_proposalId); } } pragma solidity 0.8.7; /* solhint-disable indent */ import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; import "./interfaces/IControllerRegistry.sol"; import "./interfaces/IControllerBase.sol"; contract MemberToken is ERC1155Supply, Ownable { using Address for address; IControllerRegistry public controllerRegistry; mapping(uint256 => address) public memberController; uint256 public nextAvailablePodId = 0; string public _contractURI = "https://orcaprotocol-nft.vercel.app/assets/contract-metadata"; event MigrateMemberController(uint256 podId, address newController); /** * @param _controllerRegistry The address of the ControllerRegistry contract */ constructor(address _controllerRegistry, string memory uri) ERC1155(uri) { require(_controllerRegistry != address(0), "Invalid address"); controllerRegistry = IControllerRegistry(_controllerRegistry); } // Provides metadata value for the opensea wallet. Must be set at construct time // Source: https://www.reddit.com/r/ethdev/comments/q4j5bf/contracturi_not_reflected_in_opensea/ function contractURI() public view returns (string memory) { return _contractURI; } // Note that OpenSea does not currently update contract metadata when this value is changed. - Nov 2021 function setContractURI(string memory newContractURI) public onlyOwner { _contractURI = newContractURI; } /** * @param _podId The pod id number * @param _newController The address of the new controller */ function migrateMemberController(uint256 _podId, address _newController) external { require(_newController != address(0), "Invalid address"); require( msg.sender == memberController[_podId], "Invalid migrate controller" ); require( controllerRegistry.isRegistered(_newController), "Controller not registered" ); memberController[_podId] = _newController; emit MigrateMemberController(_podId, _newController); } function getNextAvailablePodId() external view returns (uint256) { return nextAvailablePodId; } function setUri(string memory uri) external onlyOwner { _setURI(uri); } /** * @param _account The account address to assign the membership token to * @param _id The membership token id to mint * @param data Passes a flag for initial creation event */ function mint( address _account, uint256 _id, bytes memory data ) external { _mint(_account, _id, 1, data); } /** * @param _accounts The account addresses to assign the membership tokens to * @param _id The membership token id to mint * @param data Passes a flag for an initial creation event */ function mintSingleBatch( address[] memory _accounts, uint256 _id, bytes memory data ) public { for (uint256 index = 0; index < _accounts.length; index += 1) { _mint(_accounts[index], _id, 1, data); } } /** * @param _accounts The account addresses to burn the membership tokens from * @param _id The membership token id to burn */ function burnSingleBatch(address[] memory _accounts, uint256 _id) public { for (uint256 index = 0; index < _accounts.length; index += 1) { _burn(_accounts[index], _id, 1); } } function createPod(address[] memory _accounts, bytes memory data) external returns (uint256) { uint256 id = nextAvailablePodId; nextAvailablePodId += 1; require( controllerRegistry.isRegistered(msg.sender), "Controller not registered" ); memberController[id] = msg.sender; if (_accounts.length != 0) { mintSingleBatch(_accounts, id, data); } return id; } /** * @param _account The account address holding the membership token to destroy * @param _id The id of the membership token to destroy */ function burn(address _account, uint256 _id) external { _burn(_account, _id, 1); } // this hook gets called before every token event including mint and burn /** * @param operator The account address that initiated the action * @param from The account address recieveing the membership token * @param to The account address sending the membership token * @param ids An array of membership token ids to be transfered * @param amounts The amount of each membership token type to transfer * @param data Passes a flag for an initial creation event */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { // use first id to lookup controller address controller = memberController[ids[0]]; require(controller != address(0), "Pod doesn't exist"); for (uint256 i = 0; i < ids.length; i += 1) { // check if recipient is already member if (to != address(0)) { require(balanceOf(to, ids[i]) == 0, "User is already member"); } // verify all ids use same controller require( memberController[ids[i]] == controller, "Ids have different controllers" ); } // perform orca token transfer validations IControllerBase(controller).beforeTokenTransfer( operator, from, to, ids, amounts, data ); } } pragma solidity 0.8.7; /* solhint-disable indent */ import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./interfaces/IControllerV1.sol"; import "./interfaces/IMemberToken.sol"; import "./interfaces/IControllerRegistry.sol"; import "./SafeTeller.sol"; import "./ens/IPodEnsRegistrar.sol"; contract ControllerV1 is IControllerV1, SafeTeller, Ownable { event CreatePod(uint256 podId, address safe, address admin, string ensName); event UpdatePodAdmin(uint256 podId, address admin); IMemberToken public immutable memberToken; IControllerRegistry public immutable controllerRegistry; IPodEnsRegistrar public podEnsRegistrar; string public constant VERSION = "1.2.0"; mapping(address => uint256) public safeToPodId; mapping(uint256 => address) public podIdToSafe; mapping(uint256 => address) public podAdmin; mapping(uint256 => bool) public isTransferLocked; uint8 internal constant CREATE_EVENT = 0x01; /** * @dev Will instantiate safe teller with gnosis master and proxy addresses * @param _memberToken The address of the MemberToken contract * @param _controllerRegistry The address of the ControllerRegistry contract * @param _proxyFactoryAddress The proxy factory address * @param _gnosisMasterAddress The gnosis master address */ constructor( address _memberToken, address _controllerRegistry, address _proxyFactoryAddress, address _gnosisMasterAddress, address _podEnsRegistrar, address _fallbackHandlerAddress ) SafeTeller( _proxyFactoryAddress, _gnosisMasterAddress, _fallbackHandlerAddress ) { require(_memberToken != address(0), "Invalid address"); require(_controllerRegistry != address(0), "Invalid address"); require(_proxyFactoryAddress != address(0), "Invalid address"); require(_gnosisMasterAddress != address(0), "Invalid address"); require(_podEnsRegistrar != address(0), "Invalid address"); require(_fallbackHandlerAddress != address(0), "Invalid address"); memberToken = IMemberToken(_memberToken); controllerRegistry = IControllerRegistry(_controllerRegistry); podEnsRegistrar = IPodEnsRegistrar(_podEnsRegistrar); } function updatePodEnsRegistrar(address _podEnsRegistrar) external override onlyOwner { require(_podEnsRegistrar != address(0), "Invalid address"); podEnsRegistrar = IPodEnsRegistrar(_podEnsRegistrar); } /** * @param _members The addresses of the members of the pod * @param threshold The number of members that are required to sign a transaction * @param _admin The address of the pod admin * @param _label label hash of pod name (i.e labelhash('mypod')) * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function createPod( address[] memory _members, uint256 threshold, address _admin, bytes32 _label, string memory _ensString, uint256 expectedPodId, string memory _imageUrl ) external override { address safe = createSafe(_members, threshold); _createPod( _members, safe, _admin, _label, _ensString, expectedPodId, _imageUrl ); } /** * @dev Used to create a pod with an existing safe * @dev Will automatically distribute membership NFTs to current safe members * @param _admin The address of the pod admin * @param _safe The address of existing safe * @param _label label hash of pod name (i.e labelhash('mypod')) * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function createPodWithSafe( address _admin, address _safe, bytes32 _label, string memory _ensString, uint256 expectedPodId, string memory _imageUrl ) external override { require(_safe != address(0), "invalid safe address"); require(safeToPodId[_safe] == 0, "safe already in use"); require(isSafeModuleEnabled(_safe), "safe module must be enabled"); require( isSafeMember(_safe, msg.sender) || msg.sender == _safe, "caller must be safe or member" ); address[] memory members = getSafeMembers(_safe); _createPod( members, _safe, _admin, _label, _ensString, expectedPodId, _imageUrl ); } /** * @param _members The addresses of the members of the pod * @param _admin The address of the pod admin * @param _safe The address of existing safe * @param _label label hash of pod name (i.e labelhash('mypod')) * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function _createPod( address[] memory _members, address _safe, address _admin, bytes32 _label, string memory _ensString, uint256 expectedPodId, string memory _imageUrl ) private { // add create event flag to token data bytes memory data = new bytes(1); data[0] = bytes1(uint8(CREATE_EVENT)); uint256 podId = memberToken.createPod(_members, data); // The imageUrl has an expected pod ID, but we need to make sure it aligns with the actual pod ID require(podId == expectedPodId, "pod id didn't match, try again"); emit CreatePod(podId, _safe, _admin, _ensString); emit UpdatePodAdmin(podId, _admin); if (_admin != address(0)) { // will lock safe modules if admin exists setModuleLock(_safe, true); podAdmin[podId] = _admin; } podIdToSafe[podId] = _safe; safeToPodId[_safe] = podId; // setup pod ENS address reverseRegistrar = podEnsRegistrar.registerPod( _label, _safe, msg.sender ); setupSafeReverseResolver(_safe, reverseRegistrar, _ensString); // Node is how ENS identifies names, we need that to setText bytes32 node = podEnsRegistrar.getEnsNode(_label); podEnsRegistrar.setText(node, "avatar", _imageUrl); podEnsRegistrar.setText(node, "podId", Strings.toString(podId)); } /** * @dev Allows admin to unlock the safe modules and allow them to be edited by members * @param _podId The id number of the pod * @param _isLocked true - pod modules cannot be added/removed */ function setPodModuleLock(uint256 _podId, bool _isLocked) external override { require( msg.sender == podAdmin[_podId], "Must be admin to set module lock" ); setModuleLock(podIdToSafe[_podId], _isLocked); } /** * @param _podId The id number of the pod * @param _newAdmin The address of the new pod admin */ function updatePodAdmin(uint256 _podId, address _newAdmin) external override { address admin = podAdmin[_podId]; address safe = podIdToSafe[_podId]; require(safe != address(0), "Pod doesn't exist"); // if there is no admin it can only be added by safe if (admin == address(0)) { require(msg.sender == safe, "Only safe can add new admin"); } else { require(msg.sender == admin, "Only admin can update admin"); } // set module lock to true for non zero _newAdmin setModuleLock(safe, _newAdmin != address(0)); podAdmin[_podId] = _newAdmin; emit UpdatePodAdmin(_podId, _newAdmin); } /** * @param _podId The id number of the pod * @param _isTransferLocked The address of the new pod admin */ function setPodTransferLock(uint256 _podId, bool _isTransferLocked) external override { address admin = podAdmin[_podId]; address safe = podIdToSafe[_podId]; // if no pod admin it can only be set by safe if (admin == address(0)) { require(msg.sender == safe, "Only safe can set transfer lock"); } else { // if admin then it can be set by admin or safe require( msg.sender == admin || msg.sender == safe, "Only admin or safe can set transfer lock" ); } // set podid to transfer lock bool isTransferLocked[_podId] = _isTransferLocked; } /** * @dev This will nullify all pod state on this controller * @dev Update state on _newController * @dev Update controller to _newController in Safe and MemberToken * @param _podId The id number of the pod * @param _newController The address of the new pod controller * @param _prevModule The module that points to the orca module in the safe's ModuleManager linked list */ function migratePodController( uint256 _podId, address _newController, address _prevModule ) external override { require(_newController != address(0), "Invalid address"); require( controllerRegistry.isRegistered(_newController), "Controller not registered" ); address admin = podAdmin[_podId]; address safe = podIdToSafe[_podId]; require( msg.sender == admin || msg.sender == safe, "User not authorized" ); IControllerBase newController = IControllerBase(_newController); // nullify current pod state podAdmin[_podId] = address(0); podIdToSafe[_podId] = address(0); safeToPodId[safe] = 0; // update controller in MemberToken memberToken.migrateMemberController(_podId, _newController); // update safe module to _newController migrateSafeTeller(safe, _newController, _prevModule); // update pod state in _newController newController.updatePodState(_podId, admin, safe); } /** * @dev This is called by another version of controller to migrate a pod to this version * @dev Will only accept calls from registered controllers * @dev Can only be called once. * @param _podId The id number of the pod * @param _podAdmin The address of the pod admin * @param _safeAddress The address of the safe */ function updatePodState( uint256 _podId, address _podAdmin, address _safeAddress ) external override { require(_safeAddress != address(0), "Invalid address"); require( controllerRegistry.isRegistered(msg.sender), "Controller not registered" ); require( podAdmin[_podId] == address(0) && podIdToSafe[_podId] == address(0) && safeToPodId[_safeAddress] == 0, "Pod already exists" ); // if there is a pod admin, set state and lock modules if (_podAdmin != address(0)) { podAdmin[_podId] = _podAdmin; setModuleLock(_safeAddress, true); } podIdToSafe[_podId] = _safeAddress; safeToPodId[_safeAddress] = _podId; setSafeTellerAsGuard(_safeAddress); emit UpdatePodAdmin(_podId, _podAdmin); } /** * @param operator The address that initiated the action * @param from The address sending the membership token * @param to The address recieveing the membership token * @param ids An array of membership token ids to be transfered * @param data Passes a flag for an initial creation event */ function beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory, bytes memory data ) external override { require(msg.sender == address(memberToken), "Not Authorized"); // if create event than side effects have been pre-handled // only recognise data flags from this controller if (operator == address(this) && uint8(data[0]) == CREATE_EVENT) return; for (uint256 i = 0; i < ids.length; i += 1) { uint256 podId = ids[i]; address safe = podIdToSafe[podId]; address admin = podAdmin[podId]; if (from == address(0)) { // mint event // there are no rules operator must be admin, safe or controller require( operator == safe || operator == admin || operator == address(this), "No Rules Set" ); onMint(to, safe); } else if (to == address(0)) { // burn event // there are no rules operator must be admin, safe or controller require( operator == safe || operator == admin || operator == address(this), "No Rules Set" ); onBurn(from, safe); } else { // pod cannot be locked require( isTransferLocked[podId] == false, "Pod Is Transfer Locked" ); // transfer event onTransfer(from, to, safe); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (governance/TimelockController.sol) pragma solidity ^0.8.0; import "../access/AccessControl.sol"; import "../token/ERC721/IERC721Receiver.sol"; import "../token/ERC1155/IERC1155Receiver.sol"; /** * @dev Contract module which acts as a timelocked controller. When set as the * owner of an `Ownable` smart contract, it enforces a timelock on all * `onlyOwner` maintenance operations. This gives time for users of the * controlled contract to exit before a potentially dangerous maintenance * operation is applied. * * By default, this contract is self administered, meaning administration tasks * have to go through the timelock process. The proposer (resp executor) role * is in charge of proposing (resp executing) operations. A common use case is * to position this {TimelockController} as the owner of a smart contract, with * a multisig or a DAO as the sole proposer. * * _Available since v3.3._ */ contract TimelockController is AccessControl, IERC721Receiver, IERC1155Receiver { bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE"); bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE"); bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE"); bytes32 public constant CANCELLER_ROLE = keccak256("CANCELLER_ROLE"); uint256 internal constant _DONE_TIMESTAMP = uint256(1); mapping(bytes32 => uint256) private _timestamps; uint256 private _minDelay; /** * @dev Emitted when a call is scheduled as part of operation `id`. */ event CallScheduled( bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay ); /** * @dev Emitted when a call is performed as part of operation `id`. */ event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data); /** * @dev Emitted when operation `id` is cancelled. */ event Cancelled(bytes32 indexed id); /** * @dev Emitted when the minimum delay for future operations is modified. */ event MinDelayChange(uint256 oldDuration, uint256 newDuration); /** * @dev Initializes the contract with a given `minDelay`, and a list of * initial proposers and executors. The proposers receive both the * proposer and the canceller role (for backward compatibility). The * executors receive the executor role. * * NOTE: At construction, both the deployer and the timelock itself are * administrators. This helps further configuration of the timelock by the * deployer. After configuration is done, it is recommended that the * deployer renounces its admin position and relies on timelocked * operations to perform future maintenance. */ constructor( uint256 minDelay, address[] memory proposers, address[] memory executors ) { _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE); // deployer + self administration _setupRole(TIMELOCK_ADMIN_ROLE, _msgSender()); _setupRole(TIMELOCK_ADMIN_ROLE, address(this)); // register proposers and cancellers for (uint256 i = 0; i < proposers.length; ++i) { _setupRole(PROPOSER_ROLE, proposers[i]); _setupRole(CANCELLER_ROLE, proposers[i]); } // register executors for (uint256 i = 0; i < executors.length; ++i) { _setupRole(EXECUTOR_ROLE, executors[i]); } _minDelay = minDelay; emit MinDelayChange(0, minDelay); } /** * @dev Modifier to make a function callable only by a certain role. In * addition to checking the sender's role, `address(0)` 's role is also * considered. Granting a role to `address(0)` is equivalent to enabling * this role for everyone. */ modifier onlyRoleOrOpenRole(bytes32 role) { if (!hasRole(role, address(0))) { _checkRole(role, _msgSender()); } _; } /** * @dev Contract might receive/hold ETH as part of the maintenance process. */ receive() external payable {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AccessControl) returns (bool) { return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns whether an id correspond to a registered operation. This * includes both Pending, Ready and Done operations. */ function isOperation(bytes32 id) public view virtual returns (bool pending) { return getTimestamp(id) > 0; } /** * @dev Returns whether an operation is pending or not. */ function isOperationPending(bytes32 id) public view virtual returns (bool pending) { return getTimestamp(id) > _DONE_TIMESTAMP; } /** * @dev Returns whether an operation is ready or not. */ function isOperationReady(bytes32 id) public view virtual returns (bool ready) { uint256 timestamp = getTimestamp(id); return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp; } /** * @dev Returns whether an operation is done or not. */ function isOperationDone(bytes32 id) public view virtual returns (bool done) { return getTimestamp(id) == _DONE_TIMESTAMP; } /** * @dev Returns the timestamp at with an operation becomes ready (0 for * unset operations, 1 for done operations). */ function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) { return _timestamps[id]; } /** * @dev Returns the minimum delay for an operation to become valid. * * This value can be changed by executing an operation that calls `updateDelay`. */ function getMinDelay() public view virtual returns (uint256 duration) { return _minDelay; } /** * @dev Returns the identifier of an operation containing a single * transaction. */ function hashOperation( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt ) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(target, value, data, predecessor, salt)); } /** * @dev Returns the identifier of an operation containing a batch of * transactions. */ function hashOperationBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt ) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(targets, values, payloads, predecessor, salt)); } /** * @dev Schedule an operation containing a single transaction. * * Emits a {CallScheduled} event. * * Requirements: * * - the caller must have the 'proposer' role. */ function schedule( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay ) public virtual onlyRole(PROPOSER_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _schedule(id, delay); emit CallScheduled(id, 0, target, value, data, predecessor, delay); } /** * @dev Schedule an operation containing a batch of transactions. * * Emits one {CallScheduled} event per transaction in the batch. * * Requirements: * * - the caller must have the 'proposer' role. */ function scheduleBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt, uint256 delay ) public virtual onlyRole(PROPOSER_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == payloads.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt); _schedule(id, delay); for (uint256 i = 0; i < targets.length; ++i) { emit CallScheduled(id, i, targets[i], values[i], payloads[i], predecessor, delay); } } /** * @dev Schedule an operation that is to becomes valid after a given delay. */ function _schedule(bytes32 id, uint256 delay) private { require(!isOperation(id), "TimelockController: operation already scheduled"); require(delay >= getMinDelay(), "TimelockController: insufficient delay"); _timestamps[id] = block.timestamp + delay; } /** * @dev Cancel an operation. * * Requirements: * * - the caller must have the 'canceller' role. */ function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) { require(isOperationPending(id), "TimelockController: operation cannot be cancelled"); delete _timestamps[id]; emit Cancelled(id); } /** * @dev Execute an (ready) operation containing a single transaction. * * Emits a {CallExecuted} event. * * Requirements: * * - the caller must have the 'executor' role. */ // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending, // thus any modifications to the operation during reentrancy should be caught. // slither-disable-next-line reentrancy-eth function execute( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _beforeCall(id, predecessor); _call(id, 0, target, value, data); _afterCall(id); } /** * @dev Execute an (ready) operation containing a batch of transactions. * * Emits one {CallExecuted} event per transaction in the batch. * * Requirements: * * - the caller must have the 'executor' role. */ function executeBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == payloads.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt); _beforeCall(id, predecessor); for (uint256 i = 0; i < targets.length; ++i) { _call(id, i, targets[i], values[i], payloads[i]); } _afterCall(id); } /** * @dev Checks before execution of an operation's calls. */ function _beforeCall(bytes32 id, bytes32 predecessor) private view { require(isOperationReady(id), "TimelockController: operation is not ready"); require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency"); } /** * @dev Checks after execution of an operation's calls. */ function _afterCall(bytes32 id) private { require(isOperationReady(id), "TimelockController: operation is not ready"); _timestamps[id] = _DONE_TIMESTAMP; } /** * @dev Execute an operation's call. * * Emits a {CallExecuted} event. */ function _call( bytes32 id, uint256 index, address target, uint256 value, bytes calldata data ) private { (bool success, ) = target.call{value: value}(data); require(success, "TimelockController: underlying transaction reverted"); emit CallExecuted(id, index, target, value, data); } /** * @dev Changes the minimum timelock duration for future operations. * * Emits a {MinDelayChange} event. * * Requirements: * * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing * an operation where the timelock is the target and the data is the ABI-encoded call to this function. */ function updateDelay(uint256 newDelay) external virtual { require(msg.sender == address(this), "TimelockController: caller must be timelock"); emit MinDelayChange(_minDelay, newDelay); _minDelay = newDelay; } /** * @dev See {IERC721Receiver-onERC721Received}. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } /** * @dev See {IERC1155Receiver-onERC1155Received}. */ function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } /** * @dev See {IERC1155Receiver-onERC1155BatchReceived}. */ function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./ICoreRef.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title A Reference to Core /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core abstract contract CoreRef is ICoreRef, Pausable { ICore private immutable _core; IFei private immutable _fei; IERC20 private immutable _tribe; /// @notice a role used with a subset of governor permissions for this contract only bytes32 public override CONTRACT_ADMIN_ROLE; constructor(address coreAddress) { _core = ICore(coreAddress); _fei = ICore(coreAddress).fei(); _tribe = ICore(coreAddress).tribe(); _setContractAdminRole(ICore(coreAddress).GOVERN_ROLE()); } function _initialize(address) internal {} // no-op for backward compatibility modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require(_core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller"); _; } modifier onlyGovernorOrAdmin() { require( _core.isGovernor(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not a governor or contract admin" ); _; } modifier onlyGovernor() { require(_core.isGovernor(msg.sender), "CoreRef: Caller is not a governor"); _; } modifier onlyGuardianOrGovernor() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender), "CoreRef: Caller is not a guardian or governor" ); _; } modifier isGovernorOrGuardianOrAdmin() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not governor or guardian or admin" ); _; } // Named onlyTribeRole to prevent collision with OZ onlyRole modifier modifier onlyTribeRole(bytes32 role) { require(_core.hasRole(role, msg.sender), "UNAUTHORIZED"); _; } // Modifiers to allow any combination of roles modifier hasAnyOfTwoRoles(bytes32 role1, bytes32 role2) { require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender), "UNAUTHORIZED"); _; } modifier hasAnyOfThreeRoles( bytes32 role1, bytes32 role2, bytes32 role3 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfFourRoles( bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfFiveRoles( bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4, bytes32 role5 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender) || _core.hasRole(role5, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfSixRoles( bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4, bytes32 role5, bytes32 role6 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender) || _core.hasRole(role5, msg.sender) || _core.hasRole(role6, msg.sender), "UNAUTHORIZED" ); _; } modifier onlyFei() { require(msg.sender == address(_fei), "CoreRef: Caller is not FEI"); _; } /// @notice sets a new admin role for this contract function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor { _setContractAdminRole(newContractAdminRole); } /// @notice returns whether a given address has the admin role for this contract function isContractAdmin(address _admin) public view override returns (bool) { return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin); } /// @notice set pausable methods to paused function pause() public override onlyGuardianOrGovernor { _pause(); } /// @notice set pausable methods to unpaused function unpause() public override onlyGuardianOrGovernor { _unpause(); } /// @notice address of the Core contract referenced /// @return ICore implementation address function core() public view override returns (ICore) { return _core; } /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function fei() public view override returns (IFei) { return _fei; } /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function tribe() public view override returns (IERC20) { return _tribe; } /// @notice fei balance of contract /// @return fei amount held function feiBalance() public view override returns (uint256) { return _fei.balanceOf(address(this)); } /// @notice tribe balance of contract /// @return tribe amount held function tribeBalance() public view override returns (uint256) { return _tribe.balanceOf(address(this)); } function _burnFeiHeld() internal { _fei.burn(feiBalance()); } function _mintFei(address to, uint256 amount) internal virtual { if (amount != 0) { _fei.mint(to, amount); } } function _setContractAdminRole(bytes32 newContractAdminRole) internal { bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE; CONTRACT_ADMIN_ROLE = newContractAdminRole; emit ContractAdminRoleUpdate(oldContractAdminRole, newContractAdminRole); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IPermissions.sol"; import "../fei/IFei.sol"; /// @title Core Interface /// @author Fei Protocol interface ICore is IPermissions { // ----------- Events ----------- event FeiUpdate(address indexed _fei); event TribeUpdate(address indexed _tribe); event GenesisGroupUpdate(address indexed _genesisGroup); event TribeAllocation(address indexed _to, uint256 _amount); event GenesisPeriodComplete(uint256 _timestamp); // ----------- Governor only state changing api ----------- function init() external; // ----------- Governor only state changing api ----------- function setFei(address token) external; function setTribe(address token) external; function allocateTribe(address to, uint256 amount) external; // ----------- Getters ----------- function fei() external view returns (IFei); function tribe() external view returns (IERC20); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "./Permissions.sol"; import "./ICore.sol"; import "../fei/Fei.sol"; import "../tribe/Tribe.sol"; /// @title Source of truth for Fei Protocol /// @author Fei Protocol /// @notice maintains roles, access control, fei, tribe, genesisGroup, and the TRIBE treasury contract Core is ICore, Permissions, Initializable { /// @notice the address of the FEI contract IFei public override fei; /// @notice the address of the TRIBE contract IERC20 public override tribe; function init() external override initializer { _setupGovernor(msg.sender); Fei _fei = new Fei(address(this)); _setFei(address(_fei)); Tribe _tribe = new Tribe(address(this), msg.sender); _setTribe(address(_tribe)); } /// @notice sets Fei address to a new address /// @param token new fei address function setFei(address token) external override onlyGovernor { _setFei(token); } /// @notice sets Tribe address to a new address /// @param token new tribe address function setTribe(address token) external override onlyGovernor { _setTribe(token); } /// @notice sends TRIBE tokens from treasury to an address /// @param to the address to send TRIBE to /// @param amount the amount of TRIBE to send function allocateTribe(address to, uint256 amount) external override onlyGovernor { IERC20 _tribe = tribe; require(_tribe.balanceOf(address(this)) >= amount, "Core: Not enough Tribe"); _tribe.transfer(to, amount); emit TribeAllocation(to, amount); } function _setFei(address token) internal { fei = IFei(token); emit FeiUpdate(token); } function _setTribe(address token) internal { tribe = IERC20(token); emit TribeUpdate(token); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /** @title Tribe DAO ACL Roles @notice Holds a complete list of all roles which can be held by contracts inside Tribe DAO. Roles are broken up into 3 categories: * Major Roles - the most powerful roles in the Tribe DAO which should be carefully managed. * Admin Roles - roles with management capability over critical functionality. Should only be held by automated or optimistic mechanisms * Minor Roles - operational roles. May be held or managed by shorter optimistic timelocks or trusted multisigs. */ library TribeRoles { /*/////////////////////////////////////////////////////////////// Major Roles //////////////////////////////////////////////////////////////*/ /// @notice the ultimate role of Tribe. Controls all other roles and protocol functionality. bytes32 internal constant GOVERNOR = keccak256("GOVERN_ROLE"); /// @notice the protector role of Tribe. Admin of pause, veto, revoke, and minor roles bytes32 internal constant GUARDIAN = keccak256("GUARDIAN_ROLE"); /// @notice the role which can arbitrarily move PCV in any size from any contract bytes32 internal constant PCV_CONTROLLER = keccak256("PCV_CONTROLLER_ROLE"); /// @notice can mint FEI arbitrarily bytes32 internal constant MINTER = keccak256("MINTER_ROLE"); /// @notice Manages lower level - Admin and Minor - roles. Able to grant and revoke these bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); /*/////////////////////////////////////////////////////////////// Admin Roles //////////////////////////////////////////////////////////////*/ /// @notice has access to all admin functionality on pods bytes32 internal constant POD_ADMIN = keccak256("POD_ADMIN"); /// @notice capable of granting and revoking other TribeRoles from having veto power over a pod bytes32 internal constant POD_VETO_ADMIN = keccak256("POD_VETO_ADMIN"); /// @notice can manage the majority of Tribe protocol parameters. Sets boundaries for MINOR_PARAM_ROLE. bytes32 internal constant PARAMETER_ADMIN = keccak256("PARAMETER_ADMIN"); /// @notice manages the Collateralization Oracle as well as other protocol oracles. bytes32 internal constant ORACLE_ADMIN = keccak256("ORACLE_ADMIN_ROLE"); /// @notice manages TribalChief incentives and related functionality. bytes32 internal constant TRIBAL_CHIEF_ADMIN = keccak256("TRIBAL_CHIEF_ADMIN_ROLE"); /// @notice admin of PCVGuardian bytes32 internal constant PCV_GUARDIAN_ADMIN = keccak256("PCV_GUARDIAN_ADMIN_ROLE"); /// @notice admin of all Minor Roles bytes32 internal constant MINOR_ROLE_ADMIN = keccak256("MINOR_ROLE_ADMIN"); /// @notice admin of the Fuse protocol bytes32 internal constant FUSE_ADMIN = keccak256("FUSE_ADMIN"); /// @notice capable of vetoing DAO votes or optimistic timelocks bytes32 internal constant VETO_ADMIN = keccak256("VETO_ADMIN"); /// @notice capable of setting FEI Minters within global rate limits and caps bytes32 internal constant MINTER_ADMIN = keccak256("MINTER_ADMIN"); /// @notice manages the constituents of Optimistic Timelocks, including Proposers and Executors bytes32 internal constant OPTIMISTIC_ADMIN = keccak256("OPTIMISTIC_ADMIN"); /// @notice manages meta-governance actions, like voting & delegating. /// Also used to vote for gauge weights & similar liquid governance things. bytes32 internal constant METAGOVERNANCE_VOTE_ADMIN = keccak256("METAGOVERNANCE_VOTE_ADMIN"); /// @notice allows to manage locking of vote-escrowed tokens, and staking/unstaking /// governance tokens from a pre-defined contract in order to eventually allow voting. /// Examples: ANGLE <> veANGLE, AAVE <> stkAAVE, CVX <> vlCVX, CRV > cvxCRV. bytes32 internal constant METAGOVERNANCE_TOKEN_STAKING = keccak256("METAGOVERNANCE_TOKEN_STAKING"); /// @notice manages whitelisting of gauges where the protocol's tokens can be staked bytes32 internal constant METAGOVERNANCE_GAUGE_ADMIN = keccak256("METAGOVERNANCE_GAUGE_ADMIN"); /*/////////////////////////////////////////////////////////////// Minor Roles //////////////////////////////////////////////////////////////*/ bytes32 internal constant POD_METADATA_REGISTER_ROLE = keccak256("POD_METADATA_REGISTER_ROLE"); /// @notice capable of poking existing LBP auctions to exchange tokens. bytes32 internal constant LBP_SWAP_ROLE = keccak256("SWAP_ADMIN_ROLE"); /// @notice capable of engaging with Votium for voting incentives. bytes32 internal constant VOTIUM_ROLE = keccak256("VOTIUM_ADMIN_ROLE"); /// @notice capable of adding an address to multi rate limited bytes32 internal constant ADD_MINTER_ROLE = keccak256("ADD_MINTER_ROLE"); /// @notice capable of changing parameters within non-critical ranges bytes32 internal constant MINOR_PARAM_ROLE = keccak256("MINOR_PARAM_ROLE"); /// @notice capable of changing PCV Deposit and Global Rate Limited Minter in the PSM bytes32 internal constant PSM_ADMIN_ROLE = keccak256("PSM_ADMIN_ROLE"); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; interface IPodAdminGateway { event AddPodMember(uint256 indexed podId, address member); event RemovePodMember(uint256 indexed podId, address member); event UpdatePodAdmin(uint256 indexed podId, address oldPodAdmin, address newPodAdmin); event PodMembershipTransferLock(uint256 indexed podId, bool lock); // Veto functionality event VetoTimelock(uint256 indexed podId, address indexed timelock, bytes32 proposalId); function getSpecificPodAdminRole(uint256 _podId) external pure returns (bytes32); function getSpecificPodGuardianRole(uint256 _podId) external pure returns (bytes32); function addPodMember(uint256 _podId, address _member) external; function batchAddPodMember(uint256 _podId, address[] calldata _members) external; function removePodMember(uint256 _podId, address _member) external; function batchRemovePodMember(uint256 _podId, address[] calldata _members) external; function lockMembershipTransfers(uint256 _podId) external; function unlockMembershipTransfers(uint256 _podId) external; function veto(uint256 _podId, bytes32 proposalId) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import {ControllerV1} from "@orcaprotocol/contracts/contracts/ControllerV1.sol"; import {MemberToken} from "@orcaprotocol/contracts/contracts/MemberToken.sol"; interface IPodFactory { /// @notice Configuration used when creating a pod /// @param members List of members to be added to the pod /// @param threshold Number of members that need to approve a transaction on the Gnosis safe /// @param label Metadata, Human readable label for the pod /// @param ensString Metadata, ENS name of the pod /// @param imageUrl Metadata, URL to a image to represent the pod in frontends /// @param minDelay Delay on the timelock struct PodConfig { address[] members; uint256 threshold; bytes32 label; string ensString; string imageUrl; address admin; uint256 minDelay; } event CreatePod(uint256 indexed podId, address indexed safeAddress, address indexed timelock); event CreateTimelock(address indexed timelock); event UpdatePodController(address indexed oldController, address indexed newController); event UpdateDefaultPodController(address indexed oldController, address indexed newController); function deployCouncilPod(PodConfig calldata _config) external returns ( uint256, address, address ); function defaultPodController() external view returns (ControllerV1); function getMemberToken() external view returns (MemberToken); function getPodSafeAddresses() external view returns (address[] memory); function getNumberOfPods() external view returns (uint256); function getPodController(uint256 podId) external view returns (ControllerV1); function getPodSafe(uint256 podId) external view returns (address); function getPodTimelock(uint256 podId) external view returns (address); function getNumMembers(uint256 podId) external view returns (uint256); function getPodMembers(uint256 podId) external view returns (address[] memory); function getPodThreshold(uint256 podId) external view returns (uint256); function getIsMembershipTransferLocked(uint256 podId) external view returns (bool); function getNextPodId() external view returns (uint256); function getPodAdmin(uint256 podId) external view returns (address); function createOptimisticPod(PodConfig calldata _config) external returns ( uint256, address, address ); function updateDefaultPodController(address _newDefaultController) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, from, to, ids, amounts, data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _afterTokenTransfer(operator, from, to, ids, amounts, data); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _afterTokenTransfer(operator, from, to, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _afterTokenTransfer(operator, address(0), to, ids, amounts, data); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _afterTokenTransfer(operator, address(0), to, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); _afterTokenTransfer(operator, from, address(0), ids, amounts, ""); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); _afterTokenTransfer(operator, from, address(0), ids, amounts, ""); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} /** * @dev Hook that is called after any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC1155/extensions/ERC1155Supply.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 supply = _totalSupply[id]; require(supply >= amount, "ERC1155: burn amount exceeds totalSupply"); unchecked { _totalSupply[id] = supply - amount; } } } } } pragma solidity 0.8.7; interface IControllerRegistry{ /** * @param _controller Address to check if registered as a controller * @return Boolean representing if the address is a registered as a controller */ function isRegistered(address _controller) external view returns (bool); } pragma solidity 0.8.7; interface IControllerBase { /** * @param operator The account address that initiated the action * @param from The account address sending the membership token * @param to The account address recieving the membership token * @param ids An array of membership token ids to be transfered * @param amounts The amount of each membership token type to transfer * @param data Arbitrary data */ function beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external; function updatePodState( uint256 _podId, address _podAdmin, address _safeAddress ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } pragma solidity 0.8.7; import "./IControllerBase.sol"; interface IControllerV1 is IControllerBase { function updatePodEnsRegistrar(address _podEnsRegistrar) external; /** * @param _members The addresses of the members of the pod * @param threshold The number of members that are required to sign a transaction * @param _admin The address of the pod admin * @param _label label hash of pod name (i.e labelhash('mypod')) * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function createPod( address[] memory _members, uint256 threshold, address _admin, bytes32 _label, string memory _ensString, uint256 expectedPodId, string memory _imageUrl ) external; /** * @dev Used to create a pod with an existing safe * @dev Will automatically distribute membership NFTs to current safe members * @param _admin The address of the pod admin * @param _safe The address of existing safe * @param _label label hash of pod name (i.e labelhash('mypod')) * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function createPodWithSafe( address _admin, address _safe, bytes32 _label, string memory _ensString, uint256 expectedPodId, string memory _imageUrl ) external; /** * @dev Allows admin to unlock the safe modules and allow them to be edited by members * @param _podId The id number of the pod * @param _isLocked true - pod modules cannot be added/removed */ function setPodModuleLock(uint256 _podId, bool _isLocked) external; /** * @param _podId The id number of the pod * @param _isTransferLocked The address of the new pod admin */ function setPodTransferLock(uint256 _podId, bool _isTransferLocked) external; /** * @param _podId The id number of the pod * @param _newAdmin The address of the new pod admin */ function updatePodAdmin(uint256 _podId, address _newAdmin) external; /** * @dev This will nullify all pod state on this controller * @dev Update state on _newController * @dev Update controller to _newController in Safe and MemberToken * @param _podId The id number of the pod * @param _newController The address of the new pod controller * @param _prevModule The module that points to the orca module in the safe's ModuleManager linked list */ function migratePodController( uint256 _podId, address _newController, address _prevModule ) external; } pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; interface IMemberToken is IERC1155 { /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) external view returns (uint256); /** * @dev Indicates weither any token exist with a given id, or not. */ function exists(uint256 id) external view returns (bool); function getNextAvailablePodId() external view returns (uint256); /** * @param _podId The pod id number * @param _newController The address of the new controller */ function migrateMemberController(uint256 _podId, address _newController) external; /** * @param _account The account address to transfer the membership token to * @param _id The membership token id to mint * @param data Arbitrary data */ function mint( address _account, uint256 _id, bytes memory data ) external; /** * @param _accounts The account addresses to transfer the membership tokens to * @param _id The membership token id to mint * @param data Arbitrary data */ function mintSingleBatch( address[] memory _accounts, uint256 _id, bytes memory data ) external; function createPod(address[] memory _accounts, bytes memory data) external returns (uint256); } pragma solidity 0.8.7; import "@openzeppelin/contracts/utils/Address.sol"; import "./interfaces/IGnosisSafe.sol"; import "./interfaces/IGnosisSafeProxyFactory.sol"; import "@gnosis.pm/zodiac/contracts/guard/BaseGuard.sol"; contract SafeTeller is BaseGuard { using Address for address; // mainnet: 0x76E2cFc1F5Fa8F6a5b3fC4c8F4788F0116861F9B; address public immutable proxyFactoryAddress; // mainnet: 0x34CfAC646f301356fAa8B21e94227e3583Fe3F5F; address public immutable gnosisMasterAddress; address public immutable fallbackHandlerAddress; string public constant FUNCTION_SIG_SETUP = "setup(address[],uint256,address,bytes,address,address,uint256,address)"; string public constant FUNCTION_SIG_EXEC = "execTransaction(address,uint256,bytes,uint8,uint256,uint256,uint256,address,address,bytes)"; string public constant FUNCTION_SIG_ENABLE = "delegateSetup(address)"; bytes4 public constant ENCODED_SIG_ENABLE_MOD = bytes4(keccak256("enableModule(address)")); bytes4 public constant ENCODED_SIG_DISABLE_MOD = bytes4(keccak256("disableModule(address,address)")); bytes4 public constant ENCODED_SIG_SET_GUARD = bytes4(keccak256("setGuard(address)")); address internal constant SENTINEL = address(0x1); // pods with admin have modules locked by default mapping(address => bool) public areModulesLocked; /** * @param _proxyFactoryAddress The proxy factory address * @param _gnosisMasterAddress The gnosis master address */ constructor( address _proxyFactoryAddress, address _gnosisMasterAddress, address _fallbackHanderAddress ) { proxyFactoryAddress = _proxyFactoryAddress; gnosisMasterAddress = _gnosisMasterAddress; fallbackHandlerAddress = _fallbackHanderAddress; } /** * @param _safe The address of the safe * @param _newSafeTeller The address of the new safe teller contract */ function migrateSafeTeller( address _safe, address _newSafeTeller, address _prevModule ) internal { // add new safeTeller bytes memory enableData = abi.encodeWithSignature( "enableModule(address)", _newSafeTeller ); bool enableSuccess = IGnosisSafe(_safe).execTransactionFromModule( _safe, 0, enableData, IGnosisSafe.Operation.Call ); require(enableSuccess, "Migration failed on enable"); // validate prevModule of current safe teller (address[] memory moduleBuffer, ) = IGnosisSafe(_safe) .getModulesPaginated(_prevModule, 1); require(moduleBuffer[0] == address(this), "incorrect prevModule"); // disable current safeTeller bytes memory disableData = abi.encodeWithSignature( "disableModule(address,address)", _prevModule, address(this) ); bool disableSuccess = IGnosisSafe(_safe).execTransactionFromModule( _safe, 0, disableData, IGnosisSafe.Operation.Call ); require(disableSuccess, "Migration failed on disable"); } /** * @dev sets the safeteller as safe guard, called after migration * @param _safe The address of the safe */ function setSafeTellerAsGuard(address _safe) internal { bytes memory transferData = abi.encodeWithSignature( "setGuard(address)", address(this) ); bool guardSuccess = IGnosisSafe(_safe).execTransactionFromModule( _safe, 0, transferData, IGnosisSafe.Operation.Call ); require(guardSuccess, "Could not enable guard"); } function getSafeMembers(address safe) public view returns (address[] memory) { return IGnosisSafe(safe).getOwners(); } function isSafeModuleEnabled(address safe) public view returns (bool) { return IGnosisSafe(safe).isModuleEnabled(address(this)); } function isSafeMember(address safe, address member) public view returns (bool) { return IGnosisSafe(safe).isOwner(member); } /** * @param _owners The addresses to be owners of the safe * @param _threshold The number of owners that are required to sign a transaciton * @return safeAddress The address of the new safe */ function createSafe(address[] memory _owners, uint256 _threshold) internal returns (address safeAddress) { bytes memory data = abi.encodeWithSignature( FUNCTION_SIG_ENABLE, address(this) ); // encode the setup call that will be called on the new proxy safe // from the proxy factory bytes memory setupData = abi.encodeWithSignature( FUNCTION_SIG_SETUP, _owners, _threshold, this, data, fallbackHandlerAddress, address(0), uint256(0), address(0) ); try IGnosisSafeProxyFactory(proxyFactoryAddress).createProxy( gnosisMasterAddress, setupData ) returns (address newSafeAddress) { // add safe teller as guard setSafeTellerAsGuard(newSafeAddress); return newSafeAddress; } catch (bytes memory) { revert("Create Proxy With Data Failed"); } } /** * @param to The account address to add as an owner * @param safe The address of the safe */ function onMint(address to, address safe) internal { uint256 threshold = IGnosisSafe(safe).getThreshold(); bytes memory data = abi.encodeWithSignature( "addOwnerWithThreshold(address,uint256)", to, threshold ); bool success = IGnosisSafe(safe).execTransactionFromModule( safe, 0, data, IGnosisSafe.Operation.Call ); require(success, "Module Transaction Failed"); } /** * @param from The address to be removed as an owner * @param safe The address of the safe */ function onBurn(address from, address safe) internal { uint256 threshold = IGnosisSafe(safe).getThreshold(); address[] memory owners = IGnosisSafe(safe).getOwners(); //look for the address pointing to address from address prevFrom = address(0); for (uint256 i = 0; i < owners.length; i++) { if (owners[i] == from) { if (i == 0) { prevFrom = SENTINEL; } else { prevFrom = owners[i - 1]; } } } if (owners.length - 1 < threshold) threshold -= 1; bytes memory data = abi.encodeWithSignature( "removeOwner(address,address,uint256)", prevFrom, from, threshold ); bool success = IGnosisSafe(safe).execTransactionFromModule( safe, 0, data, IGnosisSafe.Operation.Call ); require(success, "Module Transaction Failed"); } /** * @param from The address being removed as an owner * @param to The address being added as an owner * @param safe The address of the safe */ function onTransfer( address from, address to, address safe ) internal { address[] memory owners = IGnosisSafe(safe).getOwners(); //look for the address pointing to address from address prevFrom; for (uint256 i = 0; i < owners.length; i++) { if (owners[i] == from) { if (i == 0) { prevFrom = SENTINEL; } else { prevFrom = owners[i - 1]; } } } bytes memory data = abi.encodeWithSignature( "swapOwner(address,address,address)", prevFrom, from, to ); bool success = IGnosisSafe(safe).execTransactionFromModule( safe, 0, data, IGnosisSafe.Operation.Call ); require(success, "Module Transaction Failed"); } /** * @dev This will execute a tx from the safe that will update the safe's ENS in the reverse resolver * @param safe safe address * @param reverseRegistrar The ENS default reverseRegistar * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function setupSafeReverseResolver( address safe, address reverseRegistrar, string memory _ensString ) internal { bytes memory data = abi.encodeWithSignature( "setName(string)", _ensString ); bool success = IGnosisSafe(safe).execTransactionFromModule( reverseRegistrar, 0, data, IGnosisSafe.Operation.Call ); require(success, "Module Transaction Failed"); } /** * @dev This will be called by the safe at tx time and prevent module disable on pods with admins * @param safe safe address * @param isLocked safe address */ function setModuleLock(address safe, bool isLocked) internal { areModulesLocked[safe] = isLocked; } /** * @dev This will be called by the safe at execution time time * @param to Destination address of Safe transaction. * @param value Ether value of Safe transaction. * @param data Data payload of Safe transaction. * @param operation Operation type of Safe transaction. * @param safeTxGas Gas that should be used for the Safe transaction. * @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund) * @param gasPrice Gas price that should be used for the payment calculation. * @param gasToken Token address (or 0 if ETH) that is used for the payment. * @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). * @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v}) * @param msgSender Account executing safe transaction */ function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external view override { address safe = msg.sender; // if safe isn't locked return if (!areModulesLocked[safe]) return; if (data.length >= 4) { require( bytes4(data) != ENCODED_SIG_ENABLE_MOD, "Cannot Enable Modules" ); require( bytes4(data) != ENCODED_SIG_DISABLE_MOD, "Cannot Disable Modules" ); require( bytes4(data) != ENCODED_SIG_SET_GUARD, "Cannot Change Guard" ); } } function checkAfterExecution(bytes32, bool) external view override {} // TODO: move to library // Used in a delegate call to enable module add on setup function enableModule(address module) external { require(module == address(0)); } function delegateSetup(address _context) external { this.enableModule(_context); } } pragma solidity 0.8.7; interface IPodEnsRegistrar { function getRootNode() external view returns (bytes32); function registerPod( bytes32 label, address podSafe, address podCreator ) external returns (address); function register(bytes32 label, address owner) external; function setText( bytes32 node, string calldata key, string calldata value ) external; function addressToNode(address input) external returns (bytes32); function getEnsNode(bytes32 label) external view returns (bytes32); } pragma solidity 0.8.7; interface IGnosisSafe { enum Operation {Call, DelegateCall} /// @dev Allows a Module to execute a Safe transaction without any further confirmations. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModule( address to, uint256 value, bytes calldata data, Operation operation ) external returns (bool success); /// @dev Returns array of owners. /// @return Array of Safe owners. function getOwners() external view returns (address[] memory); function isOwner(address owner) external view returns (bool); function getThreshold() external returns (uint256); /// @dev Returns array of modules. /// @param start Start of the page. /// @param pageSize Maximum number of modules that should be returned. /// @return array Array of modules. /// @return next Start of the next page. function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next); /// @dev Returns if an module is enabled /// @return True if the module is enabled function isModuleEnabled(address module) external view returns (bool); /// @dev Set a guard that checks transactions before execution /// @param guard The address of the guard to be used or the 0 address to disable the guard function setGuard(address guard) external; } pragma solidity 0.8.7; interface IGnosisSafeProxyFactory { /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction. /// @param singleton Address of singleton contract. /// @param data Payload for message call sent to new proxy contract. function createProxy(address singleton, bytes memory data) external returns (address); } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import "../interfaces/IGuard.sol"; abstract contract BaseGuard is IERC165 { function supportsInterface(bytes4 interfaceId) external pure override returns (bool) { return interfaceId == type(IGuard).interfaceId || // 0xe6d7a83a interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7 } /// @dev Module transactions only use the first four parameters: to, value, data, and operation. /// Module.sol hardcodes the remaining parameters as 0 since they are not used for module transactions. /// @notice This interface is used to maintain compatibilty with Gnosis Safe transaction guards. function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external virtual; function checkAfterExecution(bytes32 txHash, bool success) external virtual; } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title Enum - Collection of enums /// @author Richard Meissner - <[email protected]> contract Enum { enum Operation {Call, DelegateCall} } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; interface IGuard { function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external; function checkAfterExecution(bytes32 txHash, bool success) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `_msgSender()` is missing `role`. * Overriding this function changes the behavior of the {onlyRole} modifier. * * Format of the revert message is described in {_checkRole}. * * _Available since v4.6._ */ function _checkRole(bytes32 role) internal view virtual { _checkRole(role, _msgSender()); } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../core/ICore.sol"; /// @title CoreRef interface /// @author Fei Protocol interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed oldCore, address indexed newCore); event ContractAdminRoleUpdate(bytes32 indexed oldContractAdminRole, bytes32 indexed newContractAdminRole); // ----------- Governor only state changing api ----------- function setContractAdminRole(bytes32 newContractAdminRole) external; // ----------- Governor or Guardian only state changing api ----------- function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function fei() external view returns (IFei); function tribe() external view returns (IERC20); function feiBalance() external view returns (uint256); function tribeBalance() external view returns (uint256); function CONTRACT_ADMIN_ROLE() external view returns (bytes32); function isContractAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./IPermissionsRead.sol"; /// @title Permissions interface /// @author Fei Protocol interface IPermissions is IAccessControl, IPermissionsRead { // ----------- Governor only state changing api ----------- function createRole(bytes32 role, bytes32 adminRole) external; function grantMinter(address minter) external; function grantBurner(address burner) external; function grantPCVController(address pcvController) external; function grantGovernor(address governor) external; function grantGuardian(address guardian) external; function revokeMinter(address minter) external; function revokeBurner(address burner) external; function revokePCVController(address pcvController) external; function revokeGovernor(address governor) external; function revokeGuardian(address guardian) external; // ----------- Revoker only state changing api ----------- function revokeOverride(bytes32 role, address account) external; // ----------- Getters ----------- function GUARDIAN_ROLE() external view returns (bytes32); function GOVERN_ROLE() external view returns (bytes32); function BURNER_ROLE() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function PCV_CONTROLLER_ROLE() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title FEI stablecoin interface /// @author Fei Protocol interface IFei is IERC20 { // ----------- Events ----------- event Minting(address indexed _to, address indexed _minter, uint256 _amount); event Burning(address indexed _to, address indexed _burner, uint256 _amount); event IncentiveContractUpdate(address indexed _incentivized, address indexed _incentiveContract); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Burner only state changing api ----------- function burnFrom(address account, uint256 amount) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; // ----------- Governor only state changing api ----------- function setIncentiveContract(address account, address incentive) external; // ----------- Getters ----------- function incentiveContract(address account) external view returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title Permissions Read interface /// @author Fei Protocol interface IPermissionsRead { // ----------- Getters ----------- function isBurner(address _address) external view returns (bool); function isMinter(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isGuardian(address _address) external view returns (bool); function isPCVController(address _address) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ``` * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`. */ modifier initializer() { bool isTopLevelCall = _setInitializedVersion(1); if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original * initialization step. This is essential to configure modules that are added through upgrades and that require * initialization. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. */ modifier reinitializer(uint8 version) { bool isTopLevelCall = _setInitializedVersion(version); if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(version); } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. */ function _disableInitializers() internal virtual { _setInitializedVersion(type(uint8).max); } function _setInitializedVersion(uint8 version) private returns (bool) { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, and for the lowest level // of initializers, because in other contexts the contract may have been reentered. if (_initializing) { require( version == 1 && !Address.isContract(address(this)), "Initializable: contract is already initialized" ); return false; } else { require(_initialized < version, "Initializable: contract is already initialized"); _initialized = version; return true; } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "./IPermissions.sol"; /// @title Access control module for Core /// @author Fei Protocol contract Permissions is IPermissions, AccessControlEnumerable { bytes32 public constant override BURNER_ROLE = keccak256("BURNER_ROLE"); bytes32 public constant override MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant override PCV_CONTROLLER_ROLE = keccak256("PCV_CONTROLLER_ROLE"); bytes32 public constant override GOVERN_ROLE = keccak256("GOVERN_ROLE"); bytes32 public constant override GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); constructor() { // Appointed as a governor so guardian can have indirect access to revoke ability _setupGovernor(address(this)); _setRoleAdmin(MINTER_ROLE, GOVERN_ROLE); _setRoleAdmin(BURNER_ROLE, GOVERN_ROLE); _setRoleAdmin(PCV_CONTROLLER_ROLE, GOVERN_ROLE); _setRoleAdmin(GOVERN_ROLE, GOVERN_ROLE); _setRoleAdmin(GUARDIAN_ROLE, GOVERN_ROLE); } modifier onlyGovernor() { require(isGovernor(msg.sender), "Permissions: Caller is not a governor"); _; } modifier onlyGuardian() { require(isGuardian(msg.sender), "Permissions: Caller is not a guardian"); _; } /// @notice creates a new role to be maintained /// @param role the new role id /// @param adminRole the admin role id for `role` /// @dev can also be used to update admin of existing role function createRole(bytes32 role, bytes32 adminRole) external override onlyGovernor { _setRoleAdmin(role, adminRole); } /// @notice grants minter role to address /// @param minter new minter function grantMinter(address minter) external override onlyGovernor { grantRole(MINTER_ROLE, minter); } /// @notice grants burner role to address /// @param burner new burner function grantBurner(address burner) external override onlyGovernor { grantRole(BURNER_ROLE, burner); } /// @notice grants controller role to address /// @param pcvController new controller function grantPCVController(address pcvController) external override onlyGovernor { grantRole(PCV_CONTROLLER_ROLE, pcvController); } /// @notice grants governor role to address /// @param governor new governor function grantGovernor(address governor) external override onlyGovernor { grantRole(GOVERN_ROLE, governor); } /// @notice grants guardian role to address /// @param guardian new guardian function grantGuardian(address guardian) external override onlyGovernor { grantRole(GUARDIAN_ROLE, guardian); } /// @notice revokes minter role from address /// @param minter ex minter function revokeMinter(address minter) external override onlyGovernor { revokeRole(MINTER_ROLE, minter); } /// @notice revokes burner role from address /// @param burner ex burner function revokeBurner(address burner) external override onlyGovernor { revokeRole(BURNER_ROLE, burner); } /// @notice revokes pcvController role from address /// @param pcvController ex pcvController function revokePCVController(address pcvController) external override onlyGovernor { revokeRole(PCV_CONTROLLER_ROLE, pcvController); } /// @notice revokes governor role from address /// @param governor ex governor function revokeGovernor(address governor) external override onlyGovernor { revokeRole(GOVERN_ROLE, governor); } /// @notice revokes guardian role from address /// @param guardian ex guardian function revokeGuardian(address guardian) external override onlyGovernor { revokeRole(GUARDIAN_ROLE, guardian); } /// @notice revokes a role from address /// @param role the role to revoke /// @param account the address to revoke the role from function revokeOverride(bytes32 role, address account) external override onlyGuardian { require(role != GOVERN_ROLE, "Permissions: Guardian cannot revoke governor"); // External call because this contract is appointed as a governor and has access to revoke this.revokeRole(role, account); } /// @notice checks if address is a minter /// @param _address address to check /// @return true _address is a minter function isMinter(address _address) external view override returns (bool) { return hasRole(MINTER_ROLE, _address); } /// @notice checks if address is a burner /// @param _address address to check /// @return true _address is a burner function isBurner(address _address) external view override returns (bool) { return hasRole(BURNER_ROLE, _address); } /// @notice checks if address is a controller /// @param _address address to check /// @return true _address is a controller function isPCVController(address _address) external view override returns (bool) { return hasRole(PCV_CONTROLLER_ROLE, _address); } /// @notice checks if address is a governor /// @param _address address to check /// @return true _address is a governor // only virtual for testing mock override function isGovernor(address _address) public view virtual override returns (bool) { return hasRole(GOVERN_ROLE, _address); } /// @notice checks if address is a guardian /// @param _address address to check /// @return true _address is a guardian function isGuardian(address _address) public view override returns (bool) { return hasRole(GUARDIAN_ROLE, _address); } function _setupGovernor(address governor) internal { _setupRole(GOVERN_ROLE, governor); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "./IIncentive.sol"; import "../refs/CoreRef.sol"; /// @title FEI stablecoin /// @author Fei Protocol contract Fei is IFei, ERC20Burnable, CoreRef { /// @notice get associated incentive contract, 0 address if N/A mapping(address => address) public override incentiveContract; // solhint-disable-next-line var-name-mixedcase bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public nonces; /// @notice Fei token constructor /// @param core Fei Core address to reference constructor(address core) ERC20("Fei USD", "FEI") CoreRef(core) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), keccak256(bytes("1")), chainId, address(this) ) ); } /// @param account the account to incentivize /// @param incentive the associated incentive contract function setIncentiveContract(address account, address incentive) external override onlyGovernor { incentiveContract[account] = incentive; emit IncentiveContractUpdate(account, incentive); } /// @notice mint FEI tokens /// @param account the account to mint to /// @param amount the amount to mint function mint(address account, uint256 amount) external override onlyMinter whenNotPaused { _mint(account, amount); emit Minting(account, msg.sender, amount); } /// @notice burn FEI tokens from caller /// @param amount the amount to burn function burn(uint256 amount) public override(IFei, ERC20Burnable) { super.burn(amount); emit Burning(msg.sender, msg.sender, amount); } /// @notice burn FEI tokens from specified account /// @param account the account to burn from /// @param amount the amount to burn function burnFrom(address account, uint256 amount) public override(IFei, ERC20Burnable) onlyBurner whenNotPaused { _burn(account, amount); emit Burning(account, msg.sender, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal override { super._transfer(sender, recipient, amount); _checkAndApplyIncentives(sender, recipient, amount); } function _checkAndApplyIncentives( address sender, address recipient, uint256 amount ) internal { // incentive on sender address senderIncentive = incentiveContract[sender]; if (senderIncentive != address(0)) { IIncentive(senderIncentive).incentivize(sender, recipient, msg.sender, amount); } // incentive on recipient address recipientIncentive = incentiveContract[recipient]; if (recipientIncentive != address(0)) { IIncentive(recipientIncentive).incentivize(sender, recipient, msg.sender, amount); } // incentive on operator address operatorIncentive = incentiveContract[msg.sender]; if (msg.sender != sender && msg.sender != recipient && operatorIncentive != address(0)) { IIncentive(operatorIncentive).incentivize(sender, recipient, msg.sender, amount); } // all incentive, if active applies to every transfer address allIncentive = incentiveContract[address(0)]; if (allIncentive != address(0)) { IIncentive(allIncentive).incentivize(sender, recipient, msg.sender, amount); } } /// @notice permit spending of FEI /// @param owner the FEI holder /// @param spender the approved operator /// @param value the amount approved /// @param deadline the deadline after which the approval is no longer valid function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(deadline >= block.timestamp, "Fei: EXPIRED"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "Fei: INVALID_SIGNATURE"); _approve(owner, spender, value); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; // Forked from Uniswap's UNI // Reference: https://etherscan.io/address/0x1f9840a85d5af5bf1d1762f925bdaddc4201f984#code contract Tribe { /// @notice EIP-20 token name for this token // solhint-disable-next-line const-name-snakecase string public constant name = "Tribe"; /// @notice EIP-20 token symbol for this token // solhint-disable-next-line const-name-snakecase string public constant symbol = "TRIBE"; /// @notice EIP-20 token decimals for this token // solhint-disable-next-line const-name-snakecase uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation // solhint-disable-next-line const-name-snakecase uint256 public totalSupply = 1_000_000_000e18; // 1 billion Tribe /// @notice Address which may mint new tokens address public minter; /// @notice Allowance amounts on behalf of others mapping(address => mapping(address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping(address => uint96) internal balances; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice An event thats emitted when the minter address is changed event MinterChanged(address minter, address newMinter); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Tribe token * @param account The initial account to grant all the tokens * @param minter_ The account with minting ability */ constructor(address account, address minter_) { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); minter = minter_; emit MinterChanged(address(0), minter); } /** * @notice Change the minter address * @param minter_ The address of the new minter */ function setMinter(address minter_) external { require(msg.sender == minter, "Tribe: only the minter can change the minter address"); emit MinterChanged(minter, minter_); minter = minter_; } /** * @notice Mint new tokens * @param dst The address of the destination account * @param rawAmount The number of tokens to be minted */ function mint(address dst, uint256 rawAmount) external { require(msg.sender == minter, "Tribe: only the minter can mint"); require(dst != address(0), "Tribe: cannot transfer to the zero address"); // mint the amount uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); uint96 safeSupply = safe96(totalSupply, "Tribe: totalSupply exceeds 96 bits"); totalSupply = add96(safeSupply, amount, "Tribe: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "Tribe: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint256) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; } else { amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit( address owner, address spender, uint256 rawAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; } else { amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)) ); bytes32 structHash = keccak256( abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline) ); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Tribe: invalid signature"); require(signatory == owner, "Tribe: unauthorized"); require(block.timestamp <= deadline, "Tribe: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint256) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 rawAmount ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); if (spender != src && spenderAllowance != type(uint96).max) { uint96 newAllowance = sub96(spenderAllowance, amount, "Tribe: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 domainSeparator = keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)) ); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Tribe: invalid signature"); require(nonce == nonces[signatory]++, "Tribe: invalid nonce"); require(block.timestamp <= expiry, "Tribe: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Tribe: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens( address src, address dst, uint96 amount ) internal { require(src != address(0), "Tribe: cannot transfer from the zero address"); require(dst != address(0), "Tribe: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Tribe: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Tribe: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Tribe: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Tribe: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "Tribe: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal view returns (uint256) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastValue; // Update the index for the moved value set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { _spendAllowance(account, _msgSender(), amount); _burn(account, amount); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title incentive contract interface /// @author Fei Protocol /// @notice Called by FEI token contract when transferring with an incentivized address /// @dev should be appointed as a Minter or Burner as needed interface IIncentive { // ----------- Fei only state changing api ----------- /// @notice apply incentives on transfer /// @param sender the sender address of the FEI /// @param receiver the receiver address of the FEI /// @param operator the operator (msg.sender) of the transfer /// @param amount the amount of FEI transferred function incentivize( address sender, address receiver, address operator, uint256 amount ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
FEI stablecoin interface Fei Protocol ----------- Events ----------- ----------- State changing api ----------- ----------- Burner only state changing api ----------- ----------- Minter only state changing api ----------- ----------- Governor only state changing api ----------- ----------- Getters -----------
interface IFei is IERC20 { event Minting(address indexed _to, address indexed _minter, uint256 _amount); event Burning(address indexed _to, address indexed _burner, uint256 _amount); event IncentiveContractUpdate(address indexed _incentivized, address indexed _incentiveContract); function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function burnFrom(address account, uint256 amount) external; function mint(address account, uint256 amount) external; function setIncentiveContract(address account, address incentive) external; function incentiveContract(address account) external view returns (address); pragma solidity ^0.8.4; }
9,856,194
/* * Contract code of paper "Spass: Spectrum Sensing as a Service via Smart Contracts", S. Bayhan, A. Zubow, and A. Wolisz, IEEE DYSPAN, 2018. * * @author Zubow, 2018 */ pragma solidity ^0.4.0; contract SSaaS { struct Helper { // relevant parameter to identify a helper uint id; // helper address uint p_f; // false alarm probability / 1000 uint p_d; // detection probability / 1000 uint priceSenseBit; // set by the helper uint last_report_seq; // seq. number of reported sensing data bytes data; // sensing data as byte array bool toBlock; // whether this helper will be blocked in next round } address public owner; // of this contract -> the SU mapping(address => Helper) shMap; address[] shLst; mapping (address => uint) public pendingWithdrawals; /* Service configuration set by contract owner */ uint sens_f; // sensing sampling, i.e. readings per second uint round_s; // helpers report their sensing once per round uint data_b; // size of sensing report in bytes send per round to contract uint max_p_f; // per 1000; set by regulator uint min_p_d; // per 1000; set by regulator uint curr_seq; // the current expected seq event Debug0(string msg); event Debug1(string msg, uint v); /* Create new SSaaS contract, specifies the address of the owner */ constructor () public { owner = msg.sender; } modifier ownerOnly { if (msg.sender != owner) { revert(); } _; } /* Called by the owner (=SU) of this contract to initialize it */ function init(uint _sens_f, uint _round_s, uint _cp_f, uint _max_p_f, uint _min_p_d) public ownerOnly returns(bool) { if (!check_args(_sens_f, _round_s, _cp_f, _max_p_f, _min_p_d)) { emit Debug0("incorrect arguments!"); return false; } sens_f = _sens_f; round_s = _round_s; max_p_f = _max_p_f; min_p_d = _min_p_d; data_b = _round_s * _sens_f / _cp_f / 8 + 1; curr_seq = 1; } /* Add new helper to the contract; called by H (helpers) */ function registerSensingHelper(address _sHelper, uint _id, uint _priceSenseBit, uint _p_f, uint _p_d) public returns(bool) { if (shMap[_sHelper].priceSenseBit != 0) { emit Debug0("Helper already registered."); return false; // sensingHelper with that address was already registered } if (rejectHelper(_priceSenseBit, _p_f, _p_d)) { emit Debug0("Helper rejected; high price or bad sensing accuracy."); return false; // helper rejected due to e.g. high price } shMap[_sHelper] = Helper({id: _id, p_f: _p_f, p_d: _p_d, priceSenseBit: _priceSenseBit, last_report_seq: 0, data: new bytes(data_b), toBlock: false }); shLst.push(_sHelper); return true; } /* Check if sufficient Hs available; called by H */ function waitForOtherHelpers() public returns(bool) { if (sufficientRegisteredHelpers()) { return false; // wait for other helpers } return true; } /* Periodically called by helpers (H) to report sensing data */ function reportSensingData(address _sHelper, uint _id, uint _seq, bytes _data) public returns(bool) { if (shMap[_sHelper].priceSenseBit == 0) { emit Debug0("Unknown sensing helper; please register first."); return false; // sensing data from unknown helper; ignore } if ( (shMap[_sHelper].last_report_seq + 1) != _seq) { emit Debug0("Ignoring outdated sensing data."); return false; // ignore outdated sensing data } if (_data.length != data_b) { emit Debug0("Report has incorrect size."); return false; // incorrect report size } // copy new data for (uint i=0; i<data_b; i++) { shMap[_sHelper].data[i] = _data[i]; } shMap[_sHelper].last_report_seq = _seq; return true; } /* At end of each round contract owner (SU) makes payments to helpers */ function clearing(uint _seq) public ownerOnly returns(bool) { if (curr_seq != _seq) { emit Debug0("Clearing incorrect round (seq. number)."); return false; } /* run malicious node detection; mark helpers accordingly */ markMaliciousNodes(); // mark cheaters for (uint i=0; i<shLst.length; i++) { if (shMap[shLst[i]].toBlock == true) { blockSensingHelper(shLst[i]); // block malicious helpers } else { notifyPayment(shLst[i]); // notify honest helpers of payment } } curr_seq++; /* go to next round */ return true; } /* Notify H of its credit for amount of sensing. */ function notifyPayment(address _sHelper) ownerOnly private returns(bool) { if (shMap[_sHelper].priceSenseBit == 0 || shMap[_sHelper].toBlock) { emit Debug0("Sensing helper blocked; no withdrawal possible."); return false; } uint payment = shMap[_sHelper].priceSenseBit * (round_s * sens_f); // pay agreed price pendingWithdrawals[_sHelper] += payment; emit Debug1("Payment made to helper:", payment); return true; } /* Allows helper (H) to withdraw any outstanding credit */ function withdraw() public returns(bool) { uint amount = pendingWithdrawals[msg.sender]; if (amount <= 0) { emit Debug0("Nothing to withdraw."); return false; } pendingWithdrawals[msg.sender] = 0; if (msg.sender.send(amount)) { return true; // TX ok } else { emit Debug0("Failed to withdraw."); pendingWithdrawals[msg.sender] = amount; return false; } return true; } /* Transfer ether to the contract so that helpers can withdraw funds to receive payment for the sensing they performed. */ function increaseFunds() public payable {} /* block a helper, effectively removing it from the list */ function blockSensingHelper(address _sensingHelper) ownerOnly private returns(bool) { if (shMap[_sensingHelper].priceSenseBit == 0) { emit Debug0("Unknown helper."); return false; } /* Remove blocked helper from list of helpers */ delete shMap[_sensingHelper]; for (uint i=0; i<shLst.length; i++) { if (shLst[i] == _sensingHelper) { delete shLst[i]; break; } } return true; } /* Destroy the contract and return funds to owner */ function selfDestruct() public ownerOnly { selfdestruct(owner); } /* Change ownership of the contract */ function changeOwner(address _newOwner) public ownerOnly { if (owner != _newOwner) { owner = _newOwner; } } //// //// Helpers //// /* Algorithm used to detect malicious users */ function markMaliciousNodes() private returns(bool) { // TBD: just mockup: only helpers without report are classified as malicious // check if some helpers need to be blacklisted for (uint i=0; i<shLst.length; i++) { // check if need to block if (shMap[shLst[i]].last_report_seq != curr_seq) { // no sensing data was reported in last round; block user shMap[shLst[i]].toBlock = true; } // TBD: run algo from paper for detection } return true; } /* Check whether we have enough helpers in order to start the SSaaS */ function sufficientRegisteredHelpers() private view returns (bool) { /* Mockup: do more intelligent stuff here; see paper */ if (shLst.length == 1) { return true; // one helper is enough } return false; } /* Do checks */ function check_args(uint _sens_f, uint _round_s, uint _cp_f, uint _max_p_f, uint _min_p_d) private pure returns(bool) { if (_max_p_f == 0 || _min_p_d == 1000 || _sens_f == 0 || _round_s == 0 || _cp_f == 0) return false; /* Do some more checks */ return true; } /* Check whether the helper meets requirements and offers attractive price */ function rejectHelper(uint _priceSenseBit, uint _p_f, uint _p_d) private pure returns(bool) { // Check that _priceSenseBit and p_f/p_d are positive if (_priceSenseBit <= 0 || _p_f <= 0 || _p_d <= 0) return true; if (_p_f > 100 || _p_d < 900) return false; // bad sensors /* Mockup : do something real here; look into our paper */ return false; } }
Transfer ether to the contract so that helpers can withdraw funds to receive payment for the sensing they performed. /
function increaseFunds() public payable {}
15,830,510
pragma solidity ^0.4.24; import "./DummySTO.sol"; import "../modules/ModuleFactory.sol"; import "../libraries/Util.sol"; /** * @title Factory for deploying DummySTO module */ contract DummySTOFactory is ModuleFactory { /** * @notice Constructor * @param _polyAddress Address of the polytoken */ constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public ModuleFactory(_polyAddress, _setupCost, _usageCost, _subscriptionCost) { version = "1.0.0"; name = "DummySTO"; title = "Dummy STO"; description = "Dummy STO"; compatibleSTVersionRange["lowerBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0)); compatibleSTVersionRange["upperBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0)); } /** * @notice Used to launch the Module with the help of factory * @return address Contract address of the Module */ function deploy(bytes _data) external returns(address) { if (setupCost > 0) require(polyToken.transferFrom(msg.sender, owner, setupCost), "Sufficent Allowance is not provided"); //Check valid bytes - can only call module init function DummySTO dummySTO = new DummySTO(msg.sender, address(polyToken)); //Checks that _data is valid (not calling anything it shouldn't) require(Util.getSig(_data) == dummySTO.getInitFunction(), "Invalid data"); /*solium-disable-next-line security/no-low-level-calls*/ require(address(dummySTO).call(_data), "Unsuccessfull call"); /*solium-disable-next-line security/no-block-members*/ emit GenerateModuleFromFactory(address(dummySTO), getName(), address(this), msg.sender, setupCost, now); return address(dummySTO); } /** * @notice Type of the Module factory */ function getTypes() external view returns(uint8[]) { uint8[] memory res = new uint8[](1); res[0] = 3; return res; } /** * @notice Returns the instructions associated with the module */ function getInstructions() external view returns(string) { return "Dummy STO - you can mint tokens at will"; } /** * @notice Get the tags related to the module factory */ function getTags() external view returns(bytes32[]) { bytes32[] memory availableTags = new bytes32[](4); availableTags[0] = "Dummy"; availableTags[1] = "Non-refundable"; availableTags[2] = "ETH"; return availableTags; } }
Returns the instructions associated with the module/
function getInstructions() external view returns(string) { return "Dummy STO - you can mint tokens at will"; }
13,013,228
pragma solidity ^0.4.18; // // EtherPiggyBank // (etherpiggybank.com) // // <`--'\>______ // /. . `' \ // (`') , @ // `-._, / // )-)_/--( > // '''' '''' // // Invest Ethereum into a long term stable solution where // your investment can grow organically as the system expands. // You will gain +1.5% of your invested Ethereum every day that // you leave it in the Ether Piggy Bank! // You can withdraw your investments at any time but it will // incur a 20% withdrawal fee (~13 days of investing). // You can also invest your profits back into your account and // your gains will compound the more you do this! // // Big players can compete for the investment positions available, // every time someone makes a deposit into the Ether Piggy Bank, // they will receive a percentage of that sale in their // affiliate commision. // You can buy this position off anyone and double it's current // buying price but every 3-7 days (depending on the position), // the buying price will halve until it reaches 0.125 ether. // Upon buying, the previous investor gets 75% of the buying price, // the dev gets 5% and the rest goes into the contract to encourage // an all round balanced ecosystem! // // You will also receive a 5% bonus, which will appear in your // affiliate commission, by referring another player to the game // via your referral URL! It's a HYIP on a smart contract, fully // transparent and you'll never need to worry about an exit scam or // someone taking all the money and leaving! contract EtherPiggyBank { // investment tracking for each address mapping (address => uint256) public investedETH; mapping (address => uint256) public lastInvest; // for referrals and investor positions mapping (address => uint256) public affiliateCommision; uint256 REF_BONUS = 4; // 4% of the ether invested // goes into the ref address' affiliate commision uint256 DEV_TAX = 1; // 1% of all ether invested // goes into the dev address' affiliate commision uint256 BASE_PRICE = 0.125 ether; // 1/8 ether uint256 INHERITANCE_TAX = 75; // 75% will be returned to the // investor if their position is purchased, the rest will // go to the contract and the dev uint256 DEV_TRANSFER_TAX = 5; // this means that when purchased the sale will be distrubuted: // 75% to the old position owner // 5% to the dev // and 20% to the contract for all the other investors // ^ this will encourage a healthy ecosystem struct InvestorPosition { address investor; uint256 startingLevel; uint256 startingTime; uint256 halfLife; uint256 percentageCut; } InvestorPosition[] investorPositions; address dev; // start up the contract! function EtherPiggyBank() public { // set the dev address dev = msg.sender; // make the gold level investor investorPositions.push(InvestorPosition({ investor: dev, startingLevel: 5, // 1/8 ether * 2^5 = 4 ether startingTime: now, halfLife: 7 days, // 7 days until the level decreases percentageCut: 5 // with 5% cut of all investments })); // make the silver level investor investorPositions.push(InvestorPosition({ investor: 0x6C0CF053076681CeCBE31E5E19Df8Fb97DeB5756, startingLevel: 4, // 1/8 ether * 2^4 = 2 ether startingTime: now, halfLife: 5 days, // 5 days until the level decreases percentageCut: 3 // with 3% cut of all investments })); // make the bronze level investor investorPositions.push(InvestorPosition({ investor: 0x66fE910c6a556173EA664A94F334d005dDc9cE9E, startingLevel: 3, // 1/8 ether * 2^3 = 1 ether startingTime: now, halfLife: 3 days, // 3 days until the level decreases percentageCut: 1 // with 1% cut of all investments })); } function investETH(address referral) public payable { require(msg.value >= 0.01 ether); if (getProfit(msg.sender) > 0) { uint256 profit = getProfit(msg.sender); lastInvest[msg.sender] = now; msg.sender.transfer(profit); } uint256 amount = msg.value; // handle all of our investor positions first bool flaggedRef = (referral == msg.sender || referral == dev); // ref cannot be the sender or the dev for(uint256 i = 0; i < investorPositions.length; i++) { InvestorPosition memory position = investorPositions[i]; // check that our ref isn't an investor too if (position.investor == referral) { flaggedRef = true; } // we cannot claim on our own investments if (position.investor != msg.sender) { uint256 commision = SafeMath.div(SafeMath.mul(amount, position.percentageCut), 100); affiliateCommision[position.investor] = SafeMath.add(affiliateCommision[position.investor], commision); } } // now for the referral (if we have one) if (!flaggedRef && referral != 0x0) { uint256 refBonus = SafeMath.div(SafeMath.mul(amount, REF_BONUS), 100); // 4% affiliateCommision[referral] = SafeMath.add(affiliateCommision[referral], refBonus); } // hand out the dev tax uint256 devTax = SafeMath.div(SafeMath.mul(amount, DEV_TAX), 100); // 1% affiliateCommision[dev] = SafeMath.add(affiliateCommision[dev], devTax); // now put it in your own piggy bank! investedETH[msg.sender] = SafeMath.add(investedETH[msg.sender], amount); lastInvest[msg.sender] = now; } function divestETH() public { uint256 profit = getProfit(msg.sender); // 20% fee on taking capital out uint256 capital = investedETH[msg.sender]; uint256 fee = SafeMath.div(capital, 5); capital = SafeMath.sub(capital, fee); uint256 total = SafeMath.add(capital, profit); require(total > 0); investedETH[msg.sender] = 0; lastInvest[msg.sender] = now; msg.sender.transfer(total); } function withdraw() public{ uint256 profit = getProfit(msg.sender); require(profit > 0); lastInvest[msg.sender] = now; msg.sender.transfer(profit); } function withdrawAffiliateCommision() public { require(affiliateCommision[msg.sender] > 0); uint256 commision = affiliateCommision[msg.sender]; affiliateCommision[msg.sender] = 0; msg.sender.transfer(commision); } function reinvestProfit() public { uint256 profit = getProfit(msg.sender); require(profit > 0); lastInvest[msg.sender] = now; investedETH[msg.sender] = SafeMath.add(investedETH[msg.sender], profit); } function inheritInvestorPosition(uint256 index) public payable { require(investorPositions.length > index); require(msg.sender == tx.origin); InvestorPosition storage position = investorPositions[index]; uint256 currentLevel = getCurrentLevel(position.startingLevel, position.startingTime, position.halfLife); uint256 currentPrice = getCurrentPrice(currentLevel); require(msg.value >= currentPrice); uint256 purchaseExcess = SafeMath.sub(msg.value, currentPrice); position.startingLevel = currentLevel + 1; position.startingTime = now; // now do the transfers uint256 inheritanceTax = SafeMath.div(SafeMath.mul(currentPrice, INHERITANCE_TAX), 100); // 75% position.investor.transfer(inheritanceTax); position.investor = msg.sender; // set the new investor address // now the dev transfer tax uint256 devTransferTax = SafeMath.div(SafeMath.mul(currentPrice, DEV_TRANSFER_TAX), 100); // 5% dev.transfer(devTransferTax); // and finally the excess msg.sender.transfer(purchaseExcess); // after this point there will be 20% of currentPrice left in the contract // this will be automatically go towards paying for profits and withdrawals } function getInvestorPosition(uint256 index) public view returns(address investor, uint256 currentPrice, uint256 halfLife, uint256 percentageCut) { InvestorPosition memory position = investorPositions[index]; return (position.investor, getCurrentPrice(getCurrentLevel(position.startingLevel, position.startingTime, position.halfLife)), position.halfLife, position.percentageCut); } function getCurrentPrice(uint256 currentLevel) internal view returns(uint256) { return BASE_PRICE * 2**currentLevel; // ** is exponent, price doubles every level } function getCurrentLevel(uint256 startingLevel, uint256 startingTime, uint256 halfLife) internal view returns(uint256) { uint256 timePassed = SafeMath.sub(now, startingTime); uint256 levelsPassed = SafeMath.div(timePassed, halfLife); if (startingLevel < levelsPassed) { return 0; } return SafeMath.sub(startingLevel,levelsPassed); } function getProfitFromSender() public view returns(uint256){ return getProfit(msg.sender); } function getProfit(address customer) public view returns(uint256){ uint256 secondsPassed = SafeMath.sub(now, lastInvest[customer]); return SafeMath.div(SafeMath.mul(secondsPassed, investedETH[customer]), 5760000); // = days * amount * 0.015 (+1.5% per day) } function getAffiliateCommision() public view returns(uint256){ return affiliateCommision[msg.sender]; } function getInvested() public view returns(uint256){ return investedETH[msg.sender]; } function getBalance() public view returns(uint256){ return this.balance; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
20% fee on taking capital out
function divestETH() public { uint256 profit = getProfit(msg.sender); uint256 capital = investedETH[msg.sender]; uint256 fee = SafeMath.div(capital, 5); capital = SafeMath.sub(capital, fee); uint256 total = SafeMath.add(capital, profit); require(total > 0); investedETH[msg.sender] = 0; lastInvest[msg.sender] = now; msg.sender.transfer(total); }
988,614
//Address: 0x3b253defe296877ad467eaca7bfb60937bd7c457 //Contract name: GSD //Balance: 0 Ether //Verification Date: 1/23/2018 //Transacion Count: 13 // CODE STARTS HERE contract SafeMath{ function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function assert(bool assertion) internal { if (!assertion) { throw; } } } contract ERC20{ function totalSupply() constant returns (uint256 totalSupply) {} function balanceOf(address _owner) constant returns (uint256 balance) {} function transfer(address _recipient, uint256 _value) returns (bool success) {} function transferFrom(address _from, address _recipient, uint256 _value) returns (bool success) {} function approve(address _spender, uint256 _value) returns (bool success) {} function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _recipient, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Burn(address indexed _owner, uint256 _value); } contract GSD is ERC20, SafeMath{ mapping(address => uint256) balances; address public owner = msg.sender; uint256 public totalSupply; function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool success){ balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) returns (bool success){ var _allowance = allowed[_from][msg.sender]; balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function burn(uint256 _value) public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = safeSub(balances[burner],_value); totalSupply=safeSub(totalSupply,_value); Burn(burner, _value); } function recycle (uint256 _value) returns (bool success){ balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[address(this)] = safeAdd(balances[address(this)], _value); Transfer(msg.sender, address(this), _value); return true; } function harvest () returns (bool success) { require(msg.sender == owner); uint256[] times; times[0]=1516746600; //10:30 1516747200 times[1]=1516748400; //11:00 bool itsTime=false; //uint256 starttime = 1518566400; //2018 for (uint i=0; i<times.length;i++){ if ( now >= times[i] && now <=(times[i]+600) ) {itsTime=true; break;} } require(itsTime); uint256 Bal=balances[address(this)]; balances[owner] = safeAdd(Bal, balances[owner]); balances[address(this)]=0; Transfer(address(this),owner,Bal); return true; } string public name = "GSD"; string public symbol = "GSD"; uint public decimals = 18; uint public INITIAL_SUPPLY = 20000000000; function GSD() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; // Give all of the initial tokens to the contract deployer. } }
uint256 starttime = 1518566400; 2018
function harvest () returns (bool success) { require(msg.sender == owner); uint256[] times; bool itsTime=false; for (uint i=0; i<times.length;i++){ if ( now >= times[i] && now <=(times[i]+600) ) } require(itsTime); uint256 Bal=balances[address(this)]; balances[owner] = safeAdd(Bal, balances[owner]); balances[address(this)]=0; Transfer(address(this),owner,Bal); return true; } string public name = "GSD"; string public symbol = "GSD"; uint public decimals = 18; uint public INITIAL_SUPPLY = 20000000000;
7,228,051
// SPDX-License-Identifier: BoomerTeam pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./PhoneToken.sol"; import "./uniswapInterfaces/IUniswapFactory.sol"; import "./uniswapInterfaces/IUniswapPair.sol"; // interface IUniswapPair { // function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); // } // interface IUniswapFactory { // function getPair(address tokenA, address tokenB) external view returns (address pair); // } contract Sale is Ownable { using SafeMath for uint256; using SafeERC20 for PhoneToken; address public WETH; address public uniswapV2FactoryAddress = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; mapping(address => bool) public tokensList; // The PHONE token! PhoneToken public phone; // Rate of token with ETH uint256 public rate = 500; // Lock sale bool public lock = false; modifier isAccepted(address _token) { require(_token != WETH && _token != address(phone), "Token is not accepted!"); _; } // Check lock modifier notLock() { require(!lock, "not in lock state"); _; } // Constructor constructor( PhoneToken _phone, address _weth) public { phone = _phone; WETH = _weth; } // Functions function lockIn() public onlyOwner { lock = true; } function unlock() public onlyOwner { lock = false; } /** * @dev change rate of token PHONE * @param _newRate is new rate of token PHONE with ETH */ function changeRate(uint256 _newRate) public onlyOwner { require(_newRate > 0, "_newRate must be greater than 0"); rate = _newRate; } event BuyToken(address indexed buyer, uint256 phoneAmount, uint256 rate); /** * @dev add token to tokensList * @param _token is address of the token */ function addToken(address _token) public onlyOwner isAccepted(_token) { require(!tokensList[_token], "This token was added!"); address pairAddress = IUniswapFactory(uniswapV2FactoryAddress).getPair(_token, WETH); require(pairAddress != address(0), "pair does not exist!"); tokensList[_token] = true; } /** * @dev remove token from tokensList * @param _token is address of the token */ function removeToken(address _token) public onlyOwner isAccepted(_token) { require(tokensList[_token], "This token was removed!"); tokensList[_token] = false; } /** * @dev buy PHONE by ERRC20 * @param _token is address of the token * @param _amount is amount of ERC20 token */ function buyByERC20(address _token, uint256 _amount) public notLock() isAccepted(_token) { require(tokensList[_token], "Token is not accepted!"); uint256 saleBal = phone.balanceOf(address(this)); uint256 phoneAmount = calculatePhoneTokenAmount(_token, _amount); require( phoneAmount <= saleBal, "total phone token purchased must be less than saleBal" ); IERC20(_token).transferFrom(msg.sender, address(this), _amount); phone.safeTransfer(msg.sender, phoneAmount); emit BuyToken(msg.sender, phoneAmount, rate); } function erc20ToPhoneToken(address _token, uint256 _amount) public view notLock() isAccepted(_token) returns (uint256){ require(tokensList[_token], "Token is not accepted!"); uint256 phoneAmount = calculatePhoneTokenAmount(_token, _amount); return phoneAmount; } function calculatePhoneTokenAmount(address _token, uint256 _amount) public view returns (uint256) { address pairAddress = IUniswapFactory(uniswapV2FactoryAddress).getPair(_token, WETH); (uint112 _reserve0, uint112 _reserve1,) = IUniswapPair(pairAddress).getReserves(); uint256 reserve0 = uint256(_reserve0); uint256 reserve1 = uint256(_reserve1); uint256 phoneAmount; if(_token < WETH) { phoneAmount = (_amount.mul(reserve1).div(reserve0)).mul(rate); } else { phoneAmount = (_amount.mul(reserve0).div(reserve1)).mul(rate); } return phoneAmount; } /** * @dev function buy token PHONE */ function buyByETH() public payable notLock() { uint256 saleBal = phone.balanceOf(address(this)); uint256 phoneAmount = (msg.value).mul(rate); require( phoneAmount <= saleBal, "total phone token purchased must be less than saleBal" ); phone.safeTransfer(msg.sender, phoneAmount); emit BuyToken(msg.sender, phoneAmount, rate); } /** * @dev get balance ETH of contract */ function getBalanceETH() public view returns (uint256) { return address(this).balance; } /** * @dev get balanceOf PHONE token of contract */ function getBalancePHONE() public view returns (uint256) { return phone.balanceOf(address(this)); } /** * @dev function withdraw ETH to account owner * @param _amount is amount withdraw */ function withdrawETH(uint256 _amount) public onlyOwner { require(_amount > 0, "_amount must be greater than 0"); require( address(this).balance >= _amount, "_amount must be less than the ETH balance of the contract" ); msg.sender.transfer(_amount); } /** * @dev function withdraw PHONE token to account owner * @param _amount is amount withdraw */ function withdrawPHONE(uint256 _amount) public onlyOwner { require(_amount > 0, "_amount must be greater than 0"); require( phone.balanceOf(address(this)) >= _amount, "_amount must be less than the PHONE token balanceOf the contract" ); phone.safeTransfer(msg.sender, _amount); } /** * @dev function withdraw ERC20 token to account owner * @param _token is address of the token * @param _amount is amount withdraw */ function withdrawERC20(address _token ,uint256 _amount) public onlyOwner { require(_amount > 0, "_amount must be greater than 0"); require( IERC20(_token).balanceOf(address(this)) >= _amount, "The balance is not enough!" ); IERC20(_token).transfer(msg.sender, _amount); } event Received(address, uint256); receive() external payable { emit Received(msg.sender, msg.value); } }
add token to tokensList _token is address of the token/
function addToken(address _token) public onlyOwner isAccepted(_token) { require(!tokensList[_token], "This token was added!"); address pairAddress = IUniswapFactory(uniswapV2FactoryAddress).getPair(_token, WETH); require(pairAddress != address(0), "pair does not exist!"); tokensList[_token] = true; }
12,885,378
pragma solidity >=0.4.22 <0.6.0; contract Migrations { address public owner; uint256 public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity ^0.4.24; import "./PhotonTestToken.sol"; /** * @title PhotochainMarketplace * @dev Marketplace to make and accept offers using PhotonToken */ contract PhotochainMarketplace is Ownable { /** * Event for offer creation logging * @param id Generated unique offer id * @param seller Addess of seller of the photo * @param licenseType Which license is applied on the offer * @param photoDigest 256-bit hash of the photo * @param price How many tokens to pay to accept the offer */ event OfferAdded( bytes32 indexed id, address indexed seller, uint8 licenseType, bytes32 photoDigest, uint256 price ); /** * Event for offer acceptance logging * @param id Offer id to accept * @param licensee Address of the account that bought license */ event OfferAccepted(bytes32 indexed id, address indexed licensee); /** * Event for offer price change * @param id Offer id to update * @param oldPrice Previous price in tokens * @param newPrice New price in tokens */ event OfferPriceChanged(bytes32 indexed id, uint256 oldPrice, uint256 newPrice); /** * Event for offer cancellation * @param id Offer id to cancel */ event OfferCancelled(bytes32 indexed id); struct Offer { address seller; uint8 licenseType; bool isCancelled; bytes32 photoDigest; uint256 price; } ERC20 public token; // List of the offers mapping(bytes32 => Offer) public offers; // List of offer ids by seller mapping(address => bytes32[]) public offersBySeller; // List of offer ids by licensee mapping(address => bytes32[]) public offersByLicensee; modifier onlyValidAddress(address _addr) { require(_addr != address(0), "Invalid address"); _; } modifier onlyActiveOffer(bytes32 _id) { require(offers[_id].seller != address(0), "Offer does not exists"); require(!offers[_id].isCancelled, "Offer is cancelled"); _; } /** * @param _token Address of the PhotonToken contract */ constructor(ERC20 _token) public onlyValidAddress(address(_token)) { token = _token; } /** @dev Sets accounting token address * @param _token Address of the PhotonToken contract */ function setToken(ERC20 _token) external onlyOwner onlyValidAddress(address(_token)) { token = _token; } /** * @dev Add an offer to the marketplace * @param _seller Address of the photo author * @param _licenseType License type for the offer * @param _photoDigest 256-bit hash of the photo * @param _price Price of the offer */ function addOffer( address _seller, uint8 _licenseType, bytes32 _photoDigest, uint256 _price ) external onlyOwner onlyValidAddress(_seller) { bytes32 _id = keccak256( abi.encodePacked( _seller, _licenseType, _photoDigest ) ); require(offers[_id].seller == address(0), "Offer already exists"); offersBySeller[_seller].push(_id); offers[_id] = Offer({ seller: _seller, licenseType: _licenseType, isCancelled: false, photoDigest: _photoDigest, price: _price }); emit OfferAdded(_id, _seller, _licenseType, _photoDigest, _price); } /** * @dev Accept an offer on the marketplace * @param _id Offer id * @param _licensee Address of the licensee that is buying the photo */ function acceptOffer(bytes32 _id, address _licensee) external onlyOwner onlyValidAddress(_licensee) onlyActiveOffer(_id) { Offer storage offer = offers[_id]; if (offer.price > 0) { require( token.transferFrom(_licensee, address(this), offer.price), "Token transfer to contract failed" ); require( token.transfer(offer.seller, offer.price), "Token transfer to seller failed" ); } offersByLicensee[_licensee].push(_id); emit OfferAccepted(_id, _licensee); } /** * @dev Change price of the offer * @param _id Offer id * @param _price Price of the offer in tokens */ function setOfferPrice(bytes32 _id, uint256 _price) external onlyOwner onlyActiveOffer(_id) { uint256 oldPrice = offers[_id].price; offers[_id].price = _price; emit OfferPriceChanged(_id, oldPrice, _price); } /** * @dev Cancel offer * @param _id Offer id */ function cancelOffer(bytes32 _id) external onlyOwner onlyActiveOffer(_id) { offers[_id].isCancelled = true; emit OfferCancelled(_id); } /** * @dev Get list of offers id from a seller * @param _seller The address of the seller to find its offers * @return Offer ids */ function getOffers(address _seller) external view returns (bytes32[] memory) { return offersBySeller[_seller]; } /** * @dev Get the offer by id * @param _id The offer id * @return Offer details */ function getOfferById(bytes32 _id) external view returns ( address seller, uint8 licenseType, bool isCancelled, bytes32 photoDigest, uint256 price ) { Offer storage offer = offers[_id]; seller = offer.seller; licenseType = offer.licenseType; isCancelled = offer.isCancelled; photoDigest = offer.photoDigest; price = offer.price; } /** * @dev Get the list of the offers id by a licensee * @param _licensee Address of a licensee of offers */ function getLicenses(address _licensee) external view returns (bytes32[] memory) { return offersByLicensee[_licensee]; } } /** *Submitted for verification at Etherscan.io on 2018-09-30 */ pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error * @dev Based on https://github.com/OpenZeppelin/zeppelin-solidity */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev Based on https://github.com/OpenZeppelin/zeppelin-solidity */ contract StandardToken is ERC20 { using SafeMath for uint256; uint256 internal _totalSupply; mapping(address => uint256) internal _balanceOf; mapping (address => mapping (address => uint256)) internal _allowance; modifier onlyValidAddress(address addr) { require(addr != address(0), "Address cannot be zero"); _; } modifier onlySufficientBalance(address from, uint256 value) { require(value <= _balanceOf[from], "Insufficient balance"); _; } modifier onlySufficientAllowance(address owner, address spender, uint256 value) { require(value <= _allowance[owner][spender], "Insufficient allowance"); _; } /** * @dev Transfers token to the specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public onlyValidAddress(to) onlySufficientBalance(msg.sender, value) returns (bool) { _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(value); _balanceOf[to] = _balanceOf[to].add(value); emit Transfer(msg.sender, to, value); return true; } /** * @dev Transfers tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public onlyValidAddress(to) onlySufficientBalance(from, value) onlySufficientAllowance(from, msg.sender, value) returns (bool) { _balanceOf[from] = _balanceOf[from].sub(value); _balanceOf[to] = _balanceOf[to].add(value); _allowance[from][msg.sender] = _allowance[from][msg.sender].sub(value); emit Transfer(from, to, value); return true; } /** * @dev Approves the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public onlyValidAddress(spender) returns (bool) { _allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increases the amount of tokens that an owner allowed to a spender. * * approve should be called when _allowance[spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public onlyValidAddress(spender) returns (bool) { _allowance[msg.sender][spender] = _allowance[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); return true; } /** * @dev Decreases the amount of tokens that an owner allowed to a spender. * * approve should be called when _allowance[spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public onlyValidAddress(spender) onlySufficientAllowance(msg.sender, spender, subtractedValue) returns (bool) { _allowance[msg.sender][spender] = _allowance[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); return true; } /** * @dev Gets total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balanceOf[owner]; } /** * @dev Checks the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowance[owner][spender]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * @dev Based on https://github.com/OpenZeppelin/zeppelin-soliditysettable */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner, "Can only be called by the owner"); _; } modifier onlyValidAddress(address addr) { require(addr != address(0), "Address cannot be zero"); _; } /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner onlyValidAddress(newOwner) { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Mintable token * @dev Standard token with minting * @dev Based on https://github.com/OpenZeppelin/zeppelin-solidity */ contract MintableToken is StandardToken, Ownable { bool public mintingFinished; uint256 public cap; event Mint(address indexed to, uint256 amount); event MintFinished(); modifier onlyMinting() { require(!mintingFinished, "Minting is already finished"); _; } modifier onlyNotExceedingCap(uint256 amount) { require(_totalSupply.add(amount) <= cap, "Total supply must not exceed cap"); _; } constructor(uint256 _cap) public { cap = _cap; } /** * @dev Creates new tokens for the given address * @param to The address that will receive the minted tokens. * @param amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 amount) public onlyOwner onlyMinting onlyValidAddress(to) onlyNotExceedingCap(amount) returns (bool) { mintImpl(to, amount); return true; } /** * @dev Creates new tokens for the given addresses * @param addresses The array of addresses that will receive the minted tokens. * @param amounts The array of amounts of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mintMany(address[] addresses, uint256[] amounts) public onlyOwner onlyMinting onlyNotExceedingCap(sum(amounts)) returns (bool) { require( addresses.length == amounts.length, "Addresses array must be the same size as amounts array" ); for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Address cannot be zero"); mintImpl(addresses[i], amounts[i]); } return true; } /** * @dev Stops minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner onlyMinting returns (bool) { mintingFinished = true; emit MintFinished(); return true; } function mintImpl(address to, uint256 amount) private { _totalSupply = _totalSupply.add(amount); _balanceOf[to] = _balanceOf[to].add(amount); emit Mint(to, amount); emit Transfer(address(0), to, amount); } function sum(uint256[] arr) private pure returns (uint256) { uint256 aggr = 0; for (uint256 i = 0; i < arr.length; i++) { aggr = aggr.add(arr[i]); } return aggr; } } contract PhotonTestToken is MintableToken { string public name = "PhotonTestToken"; string public symbol = "PHT"; uint256 public decimals = 18; uint256 public cap = 120 * 10**6 * 10**decimals; // solhint-disable-next-line no-empty-blocks constructor() public MintableToken(cap) {} } pragma solidity >=0.4.22 <0.6.0; contract Migrations { address public owner; uint256 public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity ^0.4.24; import "./PhotonTestToken.sol"; /** * @title PhotochainMarketplace * @dev Marketplace to make and accept offers using PhotonToken */ contract PhotochainMarketplace is Ownable { /** * Event for offer creation logging * @param id Generated unique offer id * @param seller Addess of seller of the photo * @param licenseType Which license is applied on the offer * @param photoDigest 256-bit hash of the photo * @param price How many tokens to pay to accept the offer */ event OfferAdded( bytes32 indexed id, address indexed seller, uint8 licenseType, bytes32 photoDigest, uint256 price ); /** * Event for offer acceptance logging * @param id Offer id to accept * @param licensee Address of the account that bought license */ event OfferAccepted(bytes32 indexed id, address indexed licensee); /** * Event for offer price change * @param id Offer id to update * @param oldPrice Previous price in tokens * @param newPrice New price in tokens */ event OfferPriceChanged(bytes32 indexed id, uint256 oldPrice, uint256 newPrice); /** * Event for offer cancellation * @param id Offer id to cancel */ event OfferCancelled(bytes32 indexed id); struct Offer { address seller; uint8 licenseType; bool isCancelled; bytes32 photoDigest; uint256 price; } ERC20 public token; // List of the offers mapping(bytes32 => Offer) public offers; // List of offer ids by seller mapping(address => bytes32[]) public offersBySeller; // List of offer ids by licensee mapping(address => bytes32[]) public offersByLicensee; modifier onlyValidAddress(address _addr) { require(_addr != address(0), "Invalid address"); _; } modifier onlyActiveOffer(bytes32 _id) { require(offers[_id].seller != address(0), "Offer does not exists"); require(!offers[_id].isCancelled, "Offer is cancelled"); _; } /** * @param _token Address of the PhotonToken contract */ constructor(ERC20 _token) public onlyValidAddress(address(_token)) { token = _token; } /** @dev Sets accounting token address * @param _token Address of the PhotonToken contract */ function setToken(ERC20 _token) external onlyOwner onlyValidAddress(address(_token)) { token = _token; } /** * @dev Add an offer to the marketplace * @param _seller Address of the photo author * @param _licenseType License type for the offer * @param _photoDigest 256-bit hash of the photo * @param _price Price of the offer */ function addOffer( address _seller, uint8 _licenseType, bytes32 _photoDigest, uint256 _price ) external onlyOwner onlyValidAddress(_seller) { bytes32 _id = keccak256( abi.encodePacked( _seller, _licenseType, _photoDigest ) ); require(offers[_id].seller == address(0), "Offer already exists"); offersBySeller[_seller].push(_id); offers[_id] = Offer({ seller: _seller, licenseType: _licenseType, isCancelled: false, photoDigest: _photoDigest, price: _price }); emit OfferAdded(_id, _seller, _licenseType, _photoDigest, _price); } /** * @dev Accept an offer on the marketplace * @param _id Offer id * @param _licensee Address of the licensee that is buying the photo */ function acceptOffer(bytes32 _id, address _licensee) external onlyOwner onlyValidAddress(_licensee) onlyActiveOffer(_id) { Offer storage offer = offers[_id]; if (offer.price > 0) { require( token.transferFrom(_licensee, address(this), offer.price), "Token transfer to contract failed" ); require( token.transfer(offer.seller, offer.price), "Token transfer to seller failed" ); } offersByLicensee[_licensee].push(_id); emit OfferAccepted(_id, _licensee); } /** * @dev Change price of the offer * @param _id Offer id * @param _price Price of the offer in tokens */ function setOfferPrice(bytes32 _id, uint256 _price) external onlyOwner onlyActiveOffer(_id) { uint256 oldPrice = offers[_id].price; offers[_id].price = _price; emit OfferPriceChanged(_id, oldPrice, _price); } /** * @dev Cancel offer * @param _id Offer id */ function cancelOffer(bytes32 _id) external onlyOwner onlyActiveOffer(_id) { offers[_id].isCancelled = true; emit OfferCancelled(_id); } /** * @dev Get list of offers id from a seller * @param _seller The address of the seller to find its offers * @return Offer ids */ function getOffers(address _seller) external view returns (bytes32[] memory) { return offersBySeller[_seller]; } /** * @dev Get the offer by id * @param _id The offer id * @return Offer details */ function getOfferById(bytes32 _id) external view returns ( address seller, uint8 licenseType, bool isCancelled, bytes32 photoDigest, uint256 price ) { Offer storage offer = offers[_id]; seller = offer.seller; licenseType = offer.licenseType; isCancelled = offer.isCancelled; photoDigest = offer.photoDigest; price = offer.price; } /** * @dev Get the list of the offers id by a licensee * @param _licensee Address of a licensee of offers */ function getLicenses(address _licensee) external view returns (bytes32[] memory) { return offersByLicensee[_licensee]; } } /** *Submitted for verification at Etherscan.io on 2018-09-30 */ pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error * @dev Based on https://github.com/OpenZeppelin/zeppelin-solidity */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev Based on https://github.com/OpenZeppelin/zeppelin-solidity */ contract StandardToken is ERC20 { using SafeMath for uint256; uint256 internal _totalSupply; mapping(address => uint256) internal _balanceOf; mapping (address => mapping (address => uint256)) internal _allowance; modifier onlyValidAddress(address addr) { require(addr != address(0), "Address cannot be zero"); _; } modifier onlySufficientBalance(address from, uint256 value) { require(value <= _balanceOf[from], "Insufficient balance"); _; } modifier onlySufficientAllowance(address owner, address spender, uint256 value) { require(value <= _allowance[owner][spender], "Insufficient allowance"); _; } /** * @dev Transfers token to the specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public onlyValidAddress(to) onlySufficientBalance(msg.sender, value) returns (bool) { _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(value); _balanceOf[to] = _balanceOf[to].add(value); emit Transfer(msg.sender, to, value); return true; } /** * @dev Transfers tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public onlyValidAddress(to) onlySufficientBalance(from, value) onlySufficientAllowance(from, msg.sender, value) returns (bool) { _balanceOf[from] = _balanceOf[from].sub(value); _balanceOf[to] = _balanceOf[to].add(value); _allowance[from][msg.sender] = _allowance[from][msg.sender].sub(value); emit Transfer(from, to, value); return true; } /** * @dev Approves the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public onlyValidAddress(spender) returns (bool) { _allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increases the amount of tokens that an owner allowed to a spender. * * approve should be called when _allowance[spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public onlyValidAddress(spender) returns (bool) { _allowance[msg.sender][spender] = _allowance[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); return true; } /** * @dev Decreases the amount of tokens that an owner allowed to a spender. * * approve should be called when _allowance[spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public onlyValidAddress(spender) onlySufficientAllowance(msg.sender, spender, subtractedValue) returns (bool) { _allowance[msg.sender][spender] = _allowance[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); return true; } /** * @dev Gets total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balanceOf[owner]; } /** * @dev Checks the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowance[owner][spender]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * @dev Based on https://github.com/OpenZeppelin/zeppelin-soliditysettable */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner, "Can only be called by the owner"); _; } modifier onlyValidAddress(address addr) { require(addr != address(0), "Address cannot be zero"); _; } /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner onlyValidAddress(newOwner) { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Mintable token * @dev Standard token with minting * @dev Based on https://github.com/OpenZeppelin/zeppelin-solidity */ contract MintableToken is StandardToken, Ownable { bool public mintingFinished; uint256 public cap; event Mint(address indexed to, uint256 amount); event MintFinished(); modifier onlyMinting() { require(!mintingFinished, "Minting is already finished"); _; } modifier onlyNotExceedingCap(uint256 amount) { require(_totalSupply.add(amount) <= cap, "Total supply must not exceed cap"); _; } constructor(uint256 _cap) public { cap = _cap; } /** * @dev Creates new tokens for the given address * @param to The address that will receive the minted tokens. * @param amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 amount) public onlyOwner onlyMinting onlyValidAddress(to) onlyNotExceedingCap(amount) returns (bool) { mintImpl(to, amount); return true; } /** * @dev Creates new tokens for the given addresses * @param addresses The array of addresses that will receive the minted tokens. * @param amounts The array of amounts of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mintMany(address[] addresses, uint256[] amounts) public onlyOwner onlyMinting onlyNotExceedingCap(sum(amounts)) returns (bool) { require( addresses.length == amounts.length, "Addresses array must be the same size as amounts array" ); for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Address cannot be zero"); mintImpl(addresses[i], amounts[i]); } return true; } /** * @dev Stops minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner onlyMinting returns (bool) { mintingFinished = true; emit MintFinished(); return true; } function mintImpl(address to, uint256 amount) private { _totalSupply = _totalSupply.add(amount); _balanceOf[to] = _balanceOf[to].add(amount); emit Mint(to, amount); emit Transfer(address(0), to, amount); } function sum(uint256[] arr) private pure returns (uint256) { uint256 aggr = 0; for (uint256 i = 0; i < arr.length; i++) { aggr = aggr.add(arr[i]); } return aggr; } } contract PhotonTestToken is MintableToken { string public name = "PhotonTestToken"; string public symbol = "PHT"; uint256 public decimals = 18; uint256 public cap = 120 * 10**6 * 10**decimals; // solhint-disable-next-line no-empty-blocks constructor() public MintableToken(cap) {} } pragma solidity >=0.4.22 <0.6.0; contract Migrations { address public owner; uint256 public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity ^0.4.24; import "./PhotonTestToken.sol"; /** * @title PhotochainMarketplace * @dev Marketplace to make and accept offers using PhotonToken */ contract PhotochainMarketplace is Ownable { /** * Event for offer creation logging * @param id Generated unique offer id * @param seller Addess of seller of the photo * @param licenseType Which license is applied on the offer * @param photoDigest 256-bit hash of the photo * @param price How many tokens to pay to accept the offer */ event OfferAdded( bytes32 indexed id, address indexed seller, uint8 licenseType, bytes32 photoDigest, uint256 price ); /** * Event for offer acceptance logging * @param id Offer id to accept * @param licensee Address of the account that bought license */ event OfferAccepted(bytes32 indexed id, address indexed licensee); /** * Event for offer price change * @param id Offer id to update * @param oldPrice Previous price in tokens * @param newPrice New price in tokens */ event OfferPriceChanged(bytes32 indexed id, uint256 oldPrice, uint256 newPrice); /** * Event for offer cancellation * @param id Offer id to cancel */ event OfferCancelled(bytes32 indexed id); struct Offer { address seller; uint8 licenseType; bool isCancelled; bytes32 photoDigest; uint256 price; } ERC20 public token; // List of the offers mapping(bytes32 => Offer) public offers; // List of offer ids by seller mapping(address => bytes32[]) public offersBySeller; // List of offer ids by licensee mapping(address => bytes32[]) public offersByLicensee; modifier onlyValidAddress(address _addr) { require(_addr != address(0), "Invalid address"); _; } modifier onlyActiveOffer(bytes32 _id) { require(offers[_id].seller != address(0), "Offer does not exists"); require(!offers[_id].isCancelled, "Offer is cancelled"); _; } /** * @param _token Address of the PhotonToken contract */ constructor(ERC20 _token) public onlyValidAddress(address(_token)) { token = _token; } /** @dev Sets accounting token address * @param _token Address of the PhotonToken contract */ function setToken(ERC20 _token) external onlyOwner onlyValidAddress(address(_token)) { token = _token; } /** * @dev Add an offer to the marketplace * @param _seller Address of the photo author * @param _licenseType License type for the offer * @param _photoDigest 256-bit hash of the photo * @param _price Price of the offer */ function addOffer( address _seller, uint8 _licenseType, bytes32 _photoDigest, uint256 _price ) external onlyOwner onlyValidAddress(_seller) { bytes32 _id = keccak256( abi.encodePacked( _seller, _licenseType, _photoDigest ) ); require(offers[_id].seller == address(0), "Offer already exists"); offersBySeller[_seller].push(_id); offers[_id] = Offer({ seller: _seller, licenseType: _licenseType, isCancelled: false, photoDigest: _photoDigest, price: _price }); emit OfferAdded(_id, _seller, _licenseType, _photoDigest, _price); } /** * @dev Accept an offer on the marketplace * @param _id Offer id * @param _licensee Address of the licensee that is buying the photo */ function acceptOffer(bytes32 _id, address _licensee) external onlyOwner onlyValidAddress(_licensee) onlyActiveOffer(_id) { Offer storage offer = offers[_id]; if (offer.price > 0) { require( token.transferFrom(_licensee, address(this), offer.price), "Token transfer to contract failed" ); require( token.transfer(offer.seller, offer.price), "Token transfer to seller failed" ); } offersByLicensee[_licensee].push(_id); emit OfferAccepted(_id, _licensee); } /** * @dev Change price of the offer * @param _id Offer id * @param _price Price of the offer in tokens */ function setOfferPrice(bytes32 _id, uint256 _price) external onlyOwner onlyActiveOffer(_id) { uint256 oldPrice = offers[_id].price; offers[_id].price = _price; emit OfferPriceChanged(_id, oldPrice, _price); } /** * @dev Cancel offer * @param _id Offer id */ function cancelOffer(bytes32 _id) external onlyOwner onlyActiveOffer(_id) { offers[_id].isCancelled = true; emit OfferCancelled(_id); } /** * @dev Get list of offers id from a seller * @param _seller The address of the seller to find its offers * @return Offer ids */ function getOffers(address _seller) external view returns (bytes32[] memory) { return offersBySeller[_seller]; } /** * @dev Get the offer by id * @param _id The offer id * @return Offer details */ function getOfferById(bytes32 _id) external view returns ( address seller, uint8 licenseType, bool isCancelled, bytes32 photoDigest, uint256 price ) { Offer storage offer = offers[_id]; seller = offer.seller; licenseType = offer.licenseType; isCancelled = offer.isCancelled; photoDigest = offer.photoDigest; price = offer.price; } /** * @dev Get the list of the offers id by a licensee * @param _licensee Address of a licensee of offers */ function getLicenses(address _licensee) external view returns (bytes32[] memory) { return offersByLicensee[_licensee]; } } /** *Submitted for verification at Etherscan.io on 2018-09-30 */ pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error * @dev Based on https://github.com/OpenZeppelin/zeppelin-solidity */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev Based on https://github.com/OpenZeppelin/zeppelin-solidity */ contract StandardToken is ERC20 { using SafeMath for uint256; uint256 internal _totalSupply; mapping(address => uint256) internal _balanceOf; mapping (address => mapping (address => uint256)) internal _allowance; modifier onlyValidAddress(address addr) { require(addr != address(0), "Address cannot be zero"); _; } modifier onlySufficientBalance(address from, uint256 value) { require(value <= _balanceOf[from], "Insufficient balance"); _; } modifier onlySufficientAllowance(address owner, address spender, uint256 value) { require(value <= _allowance[owner][spender], "Insufficient allowance"); _; } /** * @dev Transfers token to the specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public onlyValidAddress(to) onlySufficientBalance(msg.sender, value) returns (bool) { _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(value); _balanceOf[to] = _balanceOf[to].add(value); emit Transfer(msg.sender, to, value); return true; } /** * @dev Transfers tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public onlyValidAddress(to) onlySufficientBalance(from, value) onlySufficientAllowance(from, msg.sender, value) returns (bool) { _balanceOf[from] = _balanceOf[from].sub(value); _balanceOf[to] = _balanceOf[to].add(value); _allowance[from][msg.sender] = _allowance[from][msg.sender].sub(value); emit Transfer(from, to, value); return true; } /** * @dev Approves the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public onlyValidAddress(spender) returns (bool) { _allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increases the amount of tokens that an owner allowed to a spender. * * approve should be called when _allowance[spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public onlyValidAddress(spender) returns (bool) { _allowance[msg.sender][spender] = _allowance[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); return true; } /** * @dev Decreases the amount of tokens that an owner allowed to a spender. * * approve should be called when _allowance[spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public onlyValidAddress(spender) onlySufficientAllowance(msg.sender, spender, subtractedValue) returns (bool) { _allowance[msg.sender][spender] = _allowance[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); return true; } /** * @dev Gets total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balanceOf[owner]; } /** * @dev Checks the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowance[owner][spender]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * @dev Based on https://github.com/OpenZeppelin/zeppelin-soliditysettable */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner, "Can only be called by the owner"); _; } modifier onlyValidAddress(address addr) { require(addr != address(0), "Address cannot be zero"); _; } /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner onlyValidAddress(newOwner) { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Mintable token * @dev Standard token with minting * @dev Based on https://github.com/OpenZeppelin/zeppelin-solidity */ contract MintableToken is StandardToken, Ownable { bool public mintingFinished; uint256 public cap; event Mint(address indexed to, uint256 amount); event MintFinished(); modifier onlyMinting() { require(!mintingFinished, "Minting is already finished"); _; } modifier onlyNotExceedingCap(uint256 amount) { require(_totalSupply.add(amount) <= cap, "Total supply must not exceed cap"); _; } constructor(uint256 _cap) public { cap = _cap; } /** * @dev Creates new tokens for the given address * @param to The address that will receive the minted tokens. * @param amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 amount) public onlyOwner onlyMinting onlyValidAddress(to) onlyNotExceedingCap(amount) returns (bool) { mintImpl(to, amount); return true; } /** * @dev Creates new tokens for the given addresses * @param addresses The array of addresses that will receive the minted tokens. * @param amounts The array of amounts of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mintMany(address[] addresses, uint256[] amounts) public onlyOwner onlyMinting onlyNotExceedingCap(sum(amounts)) returns (bool) { require( addresses.length == amounts.length, "Addresses array must be the same size as amounts array" ); for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Address cannot be zero"); mintImpl(addresses[i], amounts[i]); } return true; } /** * @dev Stops minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner onlyMinting returns (bool) { mintingFinished = true; emit MintFinished(); return true; } function mintImpl(address to, uint256 amount) private { _totalSupply = _totalSupply.add(amount); _balanceOf[to] = _balanceOf[to].add(amount); emit Mint(to, amount); emit Transfer(address(0), to, amount); } function sum(uint256[] arr) private pure returns (uint256) { uint256 aggr = 0; for (uint256 i = 0; i < arr.length; i++) { aggr = aggr.add(arr[i]); } return aggr; } } contract PhotonTestToken is MintableToken { string public name = "PhotonTestToken"; string public symbol = "PHT"; uint256 public decimals = 18; uint256 public cap = 120 * 10**6 * 10**decimals; // solhint-disable-next-line no-empty-blocks constructor() public MintableToken(cap) {} }
Creates new tokens for the given addresses addresses The array of addresses that will receive the minted tokens. amounts The array of amounts of tokens to mint. return A boolean that indicates if the operation was successful./
function mintMany(address[] addresses, uint256[] amounts) public onlyOwner onlyMinting onlyNotExceedingCap(sum(amounts)) returns (bool) { require( addresses.length == amounts.length, "Addresses array must be the same size as amounts array" ); for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Address cannot be zero"); mintImpl(addresses[i], amounts[i]); } return true; }
5,417,603
./full_match/4/0x9805B54f70D5CB4769843B653Ed8c8189C9ab2B0/sources/contracts/StakingRewards.sol
functions to calculate rewards and earnings/
function rewardPerToken() public view returns (uint) { if (totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored + (((block.timestamp - lastUpdateTime) * rewardRate * 1e18) / totalSupply); }
12,439,406
./full_match/1/0x34FDDbab979FAcB3cfEf1863D2Ef4C4ECF9Fd7e1/sources/MasterChef.sol
100% = 1000000000 10% = 100000000 1% = 10000000 30 DAY 3% 60 DAY 2.94% 90 DAY 2.8812% 120 DAY 2.823576% 150 DAY 2.767104% 180 DAY 2.711762% Total Reward : 17.123642%
function addDefaultRateInfo() public onlyOwner { uint256 oneDAY = 60 * 60 * 24; rateInfo.push(RateInfo({ time: oneDAY.mul(30), rate: _safeRate(30000000) })); rateInfo.push(RateInfo({ time: oneDAY.mul(60), rate: _safeRate(29400000) })); rateInfo.push(RateInfo({ time: oneDAY.mul(90), rate: _safeRate(28812000) })); rateInfo.push(RateInfo({ time: oneDAY.mul(120), rate: _safeRate(28235760) })); rateInfo.push(RateInfo({ time: oneDAY.mul(150), rate: _safeRate(27671040) })); rateInfo.push(RateInfo({ time: oneDAY.mul(180), rate: _safeRate(27117620) })); }
4,885,274
// SPDX-License-Identifier: MIT // File: contracts/true-currencies-new/ProxyStorage.sol pragma solidity 0.6.10; /** * Defines the storage layout of the token implementation contract. Any * newly declared state variables in future upgrades should be appended * to the bottom. Never remove state variables from this list, however variables * can be renamed. Please add _Deprecated to deprecated variables. */ contract ProxyStorage { address public owner; address public pendingOwner; bool initialized; address balances_Deprecated; address allowances_Deprecated; uint256 _totalSupply; bool private paused_Deprecated = false; address private globalPause_Deprecated; uint256 public burnMin = 0; uint256 public burnMax = 0; address registry_Deprecated; string name_Deprecated; string symbol_Deprecated; uint256[] gasRefundPool_Deprecated; uint256 private redemptionAddressCount_Deprecated; uint256 minimumGasPriceForFutureRefunds_Deprecated; mapping(address => uint256) _balances; mapping(address => mapping(address => uint256)) _allowances; mapping(bytes32 => mapping(address => uint256)) attributes_Deprecated; // reward token storage mapping(address => address) finOps_Deprecated; mapping(address => mapping(address => uint256)) finOpBalances_Deprecated; mapping(address => uint256) finOpSupply_Deprecated; // true reward allocation // proportion: 1000 = 100% struct RewardAllocation { uint256 proportion; address finOp; } mapping(address => RewardAllocation[]) _rewardDistribution_Deprecated; uint256 maxRewardProportion_Deprecated = 1000; mapping(address => bool) isBlacklisted; mapping(address => bool) public canBurn; /* Additionally, we have several keccak-based storage locations. * If you add more keccak-based storage mappings, such as mappings, you must document them here. * If the length of the keccak input is the same as an existing mapping, it is possible there could be a preimage collision. * A preimage collision can be used to attack the contract by treating one storage location as another, * which would always be a critical issue. * Carefully examine future keccak-based storage to ensure there can be no preimage collisions. ******************************************************************************************************* ** length input usage ******************************************************************************************************* ** 19 "trueXXX.proxy.owner" Proxy Owner ** 27 "trueXXX.pending.proxy.owner" Pending Proxy Owner ** 28 "trueXXX.proxy.implementation" Proxy Implementation ** 32 uint256(11) gasRefundPool_Deprecated ** 64 uint256(address),uint256(14) balanceOf ** 64 uint256(address),keccak256(uint256(address),uint256(15)) allowance ** 64 uint256(address),keccak256(bytes32,uint256(16)) attributes **/ } // File: contracts/true-currencies-new/ClaimableOwnable.sol pragma solidity 0.6.10; /** * @title ClamableOwnable * @dev The ClamableOwnable contract is a copy of Claimable Contract by Zeppelin. * and provides basic authorization control functions. Inherits storage layout of * ProxyStorage. */ contract ClaimableOwnable is ProxyStorage { /** * @dev emitted when ownership is transferred * @param previousOwner previous owner of this contract * @param newOwner new owner of this contract */ event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev sets the original `owner` of the contract to the sender * at construction. Must then be reinitialized */ constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), owner); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "only Owner"); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner, "only pending owner"); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/true-currencies-new/ERC20.sol /** * @notice This is a copy of openzeppelin ERC20 contract with removed state variables. * Removing state variables has been necessary due to proxy pattern usage. * Changes to Openzeppelin ERC20 https://github.com/OpenZeppelin/openzeppelin-contracts/blob/de99bccbfd4ecd19d7369d01b070aa72c64423c9/contracts/token/ERC20/ERC20.sol: * - Remove state variables _name, _symbol, _decimals * - Use state variables _balances, _allowances, _totalSupply from ProxyStorage * - Remove constructor * - Solidity version changed from ^0.6.0 to 0.6.10 * - Contract made abstract * * See also: ClaimableOwnable.sol and ProxyStorage.sol */ pragma solidity 0.6.10; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ abstract contract ERC20 is ClaimableOwnable, Context, IERC20 { using SafeMath for uint256; using Address for address; /** * @dev Returns the name of the token. */ function name() public virtual pure returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public virtual pure returns (string memory); /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public virtual pure returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ // solhint-disable-next-line no-empty-blocks function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/true-currencies-new/ReclaimerToken.sol pragma solidity 0.6.10; /** * @title ReclaimerToken * @dev ERC20 token which allows owner to reclaim ERC20 tokens * or ether sent to this contract */ abstract contract ReclaimerToken is ERC20 { /** * @dev send all eth balance in the contract to another address * @param _to address to send eth balance to */ function reclaimEther(address payable _to) external onlyOwner { _to.transfer(address(this).balance); } /** * @dev send all token balance of an arbitrary erc20 token * in the contract to another address * @param token token to reclaim * @param _to address to send eth balance to */ function reclaimToken(IERC20 token, address _to) external onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(_to, balance); } } // File: contracts/true-currencies-new/BurnableTokenWithBounds.sol pragma solidity 0.6.10; /** * @title BurnableTokenWithBounds * @dev Burning functions as redeeming money from the system. * The platform will keep track of who burns coins, * and will send them back the equivalent amount of money (rounded down to the nearest cent). */ abstract contract BurnableTokenWithBounds is ReclaimerToken { /** * @dev Emitted when `value` tokens are burnt from one account (`burner`) * @param burner address which burned tokens * @param value amount of tokens burned */ event Burn(address indexed burner, uint256 value); /** * @dev Emitted when new burn bounds were set * @param newMin new minimum burn amount * @param newMax new maximum burn amount * @notice `newMin` should never be greater than `newMax` */ event SetBurnBounds(uint256 newMin, uint256 newMax); /** * @dev Destroys `amount` tokens from `msg.sender`, reducing the * total supply. * @param amount amount of tokens to burn * * Emits a {Transfer} event with `to` set to the zero address. * Emits a {Burn} event with `burner` set to `msg.sender` * * Requirements * * - `msg.sender` must have at least `amount` tokens. * */ function burn(uint256 amount) external { _burn(msg.sender, amount); } /** * @dev Change the minimum and maximum amount that can be burned at once. * Burning may be disabled by setting both to 0 (this will not be done * under normal operation, but we can't add checks to disallow it without * losing a lot of flexibility since burning could also be as good as disabled * by setting the minimum extremely high, and we don't want to lock * in any particular cap for the minimum) * @param _min minimum amount that can be burned at once * @param _max maximum amount that can be burned at once */ function setBurnBounds(uint256 _min, uint256 _max) external onlyOwner { require(_min <= _max, "BurnableTokenWithBounds: min > max"); burnMin = _min; burnMax = _max; emit SetBurnBounds(_min, _max); } /** * @dev Checks if amount is within allowed burn bounds and * destroys `amount` tokens from `account`, reducing the * total supply. * @param account account to burn tokens for * @param amount amount of tokens to burn * * Emits a {Burn} event */ function _burn(address account, uint256 amount) internal virtual override { require(amount >= burnMin, "BurnableTokenWithBounds: below min burn bound"); require(amount <= burnMax, "BurnableTokenWithBounds: exceeds max burn bound"); super._burn(account, amount); emit Burn(account, amount); } } // File: contracts/true-currencies-new/GasRefund.sol pragma solidity 0.6.10; /** * @title Gas Reclaim Legacy * * Note: this contract does not affect any of the token logic. It merely * exists so the TokenController (owner) can reclaim the sponsored gas * * Previously TrueCurrency has a feature called "gas boost" which allowed * us to sponsor gas by setting non-empty storage slots to 1. * We are depricating this feature, but there is a bunch of gas saved * from years of sponsoring gas. This contract is meant to allow the owner * to take advantage of this leftover gas. Once all the slots are used, * this contract can be removed from TrueCurrency. * * Utilitzes the gas refund mechanism in EVM. Each time an non-empty * storage slot is set to 0, evm will refund 15,000 to the sender. * Also utilized the refund for selfdestruct, see gasRefund39 * */ abstract contract GasRefund { /** * @dev Refund 15,000 gas per slot. * @param amount number of slots to free */ function gasRefund15(uint256 amount) internal { // refund gas assembly { // get number of free slots let offset := sload(0xfffff) // make sure there are enough slots if lt(offset, amount) { amount := offset } if eq(amount, 0) { stop() } let location := add(offset, 0xfffff) let end := sub(location, amount) // loop until amount is reached // i = storage location for { } gt(location, end) { location := sub(location, 1) } { // set storage location to zero // this refunds 15,000 gas sstore(location, 0) } // store new number of free slots sstore(0xfffff, sub(offset, amount)) } } /** * @dev use smart contract self-destruct to refund gas * will refund 39,000 * amount gas */ function gasRefund39(uint256 amount) internal { assembly { // get amount of gas slots let offset := sload(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) // make sure there are enough slots if lt(offset, amount) { amount := offset } if eq(amount, 0) { stop() } // first sheep pointer let location := sub(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, offset) // last sheep pointer let end := add(location, amount) for { } lt(location, end) { location := add(location, 1) } { // load sheep address let sheep := sload(location) // call selfdestruct on sheep pop(call(gas(), sheep, 0, 0, 0, 0, 0)) // clear sheep address sstore(location, 0) } sstore(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, sub(offset, amount)) } } /** * @dev Return the remaining sponsored gas slots */ function remainingGasRefundPool() public view returns (uint256 length) { assembly { length := sload(0xfffff) } } /** * @dev Return the remaining sheep slots */ function remainingSheepRefundPool() public view returns (uint256 length) { assembly { length := sload(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) } } } // File: contracts/true-currencies-new/TrueCurrency.sol pragma solidity 0.6.10; /** * @title TrueCurrency * @dev TrueCurrency is an ERC20 with blacklist & redemption addresses * * TrueCurrency is a compliant stablecoin with blacklist and redemption * addresses. Only the owner can blacklist accounts. Redemption addresses * are assigned automatically to the first 0x100000 addresses. Sending * tokens to the redemption address will trigger a burn operation. Only * the owner can mint or blacklist accounts. * * This contract is owned by the TokenController, which manages token * minting & admin functionality. See TokenController.sol * * See also: BurnableTokenWithBounds.sol * * ~~~~ Features ~~~~ * * Redemption Addresses * - The first 0x100000 addresses are redemption addresses * - Tokens sent to redemption addresses are burned * - Redemptions are tracked off-chain * - Cannot mint tokens to redemption addresses * * Blacklist * - Owner can blacklist accounts in accordance with local regulatory bodies * - Only a court order will merit a blacklist; blacklisting is extremely rare * * Burn Bounds & CanBurn * - Owner can set min & max burn amounts * - Only accounts flagged in canBurn are allowed to burn tokens * - canBurn prevents tokens from being sent to the incorrect address * * Reclaimer Token * - ERC20 Tokens and Ether sent to this contract can be reclaimed by the owner */ abstract contract TrueCurrency is BurnableTokenWithBounds, GasRefund { uint256 constant CENT = 10**16; uint256 constant REDEMPTION_ADDRESS_COUNT = 0x100000; /** * @dev Emitted when account blacklist status changes */ event Blacklisted(address indexed account, bool isBlacklisted); /** * @dev Emitted when `value` tokens are minted for `to` * @param to address to mint tokens for * @param value amount of tokens to be minted */ event Mint(address indexed to, uint256 value); /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * @param account address to mint tokens for * @param amount amount of tokens to be minted * * Emits a {Mint} event * * Requirements * * - `account` cannot be the zero address. * - `account` cannot be blacklisted. * - `account` cannot be a redemption address. */ function mint(address account, uint256 amount) external onlyOwner { require(!isBlacklisted[account], "TrueCurrency: account is blacklisted"); require(!isRedemptionAddress(account), "TrueCurrency: account is a redemption address"); _mint(account, amount); emit Mint(account, amount); } /** * @dev Set blacklisted status for the account. * @param account address to set blacklist flag for * @param _isBlacklisted blacklist flag value * * Requirements: * * - `msg.sender` should be owner. */ function setBlacklisted(address account, bool _isBlacklisted) external onlyOwner { require(uint256(account) >= REDEMPTION_ADDRESS_COUNT, "TrueCurrency: blacklisting of redemption address is not allowed"); isBlacklisted[account] = _isBlacklisted; emit Blacklisted(account, _isBlacklisted); } /** * @dev Set canBurn status for the account. * @param account address to set canBurn flag for * @param _canBurn canBurn flag value * * Requirements: * * - `msg.sender` should be owner. */ function setCanBurn(address account, bool _canBurn) external onlyOwner { canBurn[account] = _canBurn; } /** * @dev Check if neither account is blacklisted before performing transfer * If transfer recipient is a redemption address, burns tokens * @notice Transfer to redemption address will burn tokens with a 1 cent precision * @param sender address of sender * @param recipient address of recipient * @param amount amount of tokens to transfer */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual override { require(!isBlacklisted[sender], "TrueCurrency: sender is blacklisted"); require(!isBlacklisted[recipient], "TrueCurrency: recipient is blacklisted"); if (isRedemptionAddress(recipient)) { super._transfer(sender, recipient, amount.sub(amount.mod(CENT))); _burn(recipient, amount.sub(amount.mod(CENT))); } else { super._transfer(sender, recipient, amount); } } /** * @dev Requere neither accounts to be blacklisted before approval * @param owner address of owner giving approval * @param spender address of spender to approve for * @param amount amount of tokens to approve */ function _approve( address owner, address spender, uint256 amount ) internal override { require(!isBlacklisted[owner], "TrueCurrency: tokens owner is blacklisted"); require(!isBlacklisted[spender] || amount == 0, "TrueCurrency: tokens spender is blacklisted"); super._approve(owner, spender, amount); } /** * @dev Check if tokens can be burned at address before burning * @param account account to burn tokens from * @param amount amount of tokens to burn */ function _burn(address account, uint256 amount) internal override { require(canBurn[account], "TrueCurrency: cannot burn from this address"); super._burn(account, amount); } /** * @dev First 0x100000-1 addresses (0x0000000000000000000000000000000000000001 to 0x00000000000000000000000000000000000fffff) * are the redemption addresses. * @param account address to check is a redemption address * * All transfers to redemption address will trigger token burn. * * @notice For transfer to succeed, canBurn must be true for redemption address * * @return is `account` a redemption address */ function isRedemptionAddress(address account) internal pure returns (bool) { return uint256(account) < REDEMPTION_ADDRESS_COUNT && uint256(account) != 0; } /** * @dev reclaim gas from legacy gas refund #1 * will refund 15,000 * amount gas to sender (minus exection cost) * If gas pool is empty, refund 39,000 * amount gas by calling selfdestruct */ function refundGas(uint256 amount) external onlyOwner { if (remainingGasRefundPool() > 0) { gasRefund15(amount); } else { gasRefund39(amount.div(3)); } } } // File: contracts/true-currencies-new/TrueGBP.sol pragma solidity 0.6.10; /** * @title TrueGBP * @dev This is the top-level ERC20 contract, but most of the interesting functionality is * inherited - see the documentation on the corresponding contracts. */ contract TrueGBP is TrueCurrency { uint8 constant DECIMALS = 18; uint8 constant ROUNDING = 2; function decimals() public override pure returns (uint8) { return DECIMALS; } function rounding() public pure returns (uint8) { return ROUNDING; } function name() public override pure returns (string memory) { return "TrueGBP"; } function symbol() public override pure returns (string memory) { return "TGBP"; } }
Allows the current owner to set the pendingOwner address. newOwner The address to transfer ownership to./
function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; }
59,220
/** *Submitted for verification at Etherscan.io on 2021-05-20 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /******************************************/ /* ChainLink starts here */ /******************************************/ interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } /******************************************/ /* Benchmark starts here */ /******************************************/ abstract contract Benchmark { function rebase(uint256 supplyDelta, bool increaseSupply) external virtual returns (uint256); function transfer(address to, uint256 value) external virtual returns (bool); function balanceOf(address who) external virtual view returns (uint256); function totalSupply() external virtual view returns (uint256); } /******************************************/ /* BenchmarkSync starts here */ /******************************************/ abstract contract BenchmarkSync { function syncPools() external virtual; } /******************************************/ /* BenchmarkOracle starts here */ /******************************************/ contract BenchmarkOracle { AggregatorV3Interface internal priceFeed; int256 public lastOracleVxx; address owner1; address owner2; address owner3; address owner4; address owner5; address public standard; uint256 public standardRewards; Benchmark public bm; BenchmarkSync public sync; Transaction public pendingRebasement; uint256 internal lastRebasementTime; struct Transaction { address initiator; int256 rebaseOne; int256 rebaseTwo; bool executed; } modifier isOwner() { require (msg.sender == owner1 || msg.sender == owner2 || msg.sender == owner3 || msg.sender == owner4 || msg.sender == owner5); _; } constructor(address _benchmark, address _standard, address _sync) { /** * Network: Ethereum * Aggregator: VXX * Address: 0xC18F2a0C166A091fcD5E2051EFEFD63c4f4A27E9 */ priceFeed = AggregatorV3Interface(0xC18F2a0C166A091fcD5E2051EFEFD63c4f4A27E9); lastOracleVxx = getOracleVxx(); owner1 = 0x2c155e07a1Ee62f229c9968B7A903dC69436e3Ec; owner2 = 0xdBd39C1b439ba2588Dab47eED41b8456486F4Ba5; owner3 = 0x90d33D152A422D63e0Dd1c107b7eD3943C06ABA8; owner4 = 0xE12E421D5C4b4D8193bf269BF94DC8dA28798BA9; owner5 = 0xD4B33C108659A274D8C35b60e6BfCb179a2a6D4C; standard = _standard; bm = Benchmark(_benchmark); sync = BenchmarkSync(_sync); pendingRebasement.executed = true; } /** * Returns the latest price */ function getOracleVxx() public view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); return price; } /** * Returns absolute value. */ function abs(int x) private pure returns (int) { return x >= 0 ? x : -x; } /** * @dev Initiates a rebasement proposal that has to be confirmed by another owner of the contract to be executed. Can't be called while another proposal is pending. * @param _rebaseOne Divergence from the target price. * @param _rebaseTwo VXX difference. */ function initiateRebasement(int256 _rebaseOne, int256 _rebaseTwo) public isOwner { require (pendingRebasement.executed == true, "Pending rebasement."); require (lastRebasementTime < (block.timestamp - 54000), "Rebasement has already occured within the past 15 hours."); Transaction storage txn = pendingRebasement; txn.initiator = msg.sender; txn.rebaseOne = _rebaseOne; txn.rebaseTwo = _rebaseTwo; txn.executed = false; } /** * @dev Confirms and executes a pending rebasement proposal. Prohibits further proposals for 15 hours. Distribute Standard rewards and sync liquidity pools. * @param _overrule True if Chainlink Oracle should be ignored. * @param _currentVxx Manually provide current VXX value if Chainlink Oracle is ignored. */ function confirmRebasement(bool _overrule, int256 _currentVxx) public isOwner { require (pendingRebasement.initiator != msg.sender, "Initiator can't confirm rebasement."); require (pendingRebasement.executed == false, "Rebasement already executed."); int256 oracleRebaseTwo; if (_overrule == false) { oracleRebaseTwo = ((getOracleVxx() - lastOracleVxx) * 1e10) / lastOracleVxx; oracleRebaseTwo = oracleRebaseTwo < 0 ? int(0) : oracleRebaseTwo; require (oracleRebaseTwo == pendingRebasement.rebaseTwo, "VXX rebases don't match!"); lastOracleVxx = getOracleVxx(); } else { oracleRebaseTwo = pendingRebasement.rebaseTwo; require(_currentVxx != 0, "Current VXX not provided."); lastOracleVxx = _currentVxx; } pendingRebasement.executed = true; lastRebasementTime = block.timestamp; int256 rebasePercentage = pendingRebasement.rebaseOne + oracleRebaseTwo; bool increaseSupply = rebasePercentage >= 0 ? true : false; uint256 absolutePercentage = uint256(abs(rebasePercentage)); uint256 supplyDelta = bm.totalSupply() * absolutePercentage / 1e10; bm.rebase(supplyDelta, increaseSupply); bm.transfer(standard, standardRewards); sync.syncPools(); } /** * @dev View Supply delta and sign for rebasement verification. * @param _overrule True if Chainlink Oracle should be ignored. */ function verifyRebasement(bool _overrule) public view returns (uint256, bool) { int256 oracleRebaseTwo; if (_overrule == false) { oracleRebaseTwo = ((getOracleVxx() - lastOracleVxx) * 1e10) / lastOracleVxx; oracleRebaseTwo = oracleRebaseTwo < 0 ? int(0) : oracleRebaseTwo; require (oracleRebaseTwo == pendingRebasement.rebaseTwo, "VXX rebases don't match!"); } else { oracleRebaseTwo = pendingRebasement.rebaseTwo; } int256 rebasePercentage = pendingRebasement.rebaseOne + oracleRebaseTwo; bool increaseSupply = rebasePercentage >= 0 ? true : false; uint256 absolutePercentage = uint256(abs(rebasePercentage)); uint256 supplyDelta = bm.totalSupply() * absolutePercentage / 1e10; return(supplyDelta, increaseSupply); } /** * @dev Denies a pending rebasement proposal and allows the creation of a new proposal. */ function denyRebasement() public isOwner { require (pendingRebasement.executed == false, "Rebasement already executed."); pendingRebasement.executed = true; } /** * @dev Change Standard staking rewards. * @param _standardRewards New amount. */ function setStandardRewards(uint256 _standardRewards) public isOwner { standardRewards = _standardRewards; } /** * @dev Remove all MARK deposited on this contract. */ function withdrawMark() public { require (msg.sender == 0x2c155e07a1Ee62f229c9968B7A903dC69436e3Ec || msg.sender == 0xdBd39C1b439ba2588Dab47eED41b8456486F4Ba5, "Only Masterchief can withdraw."); bm.transfer(msg.sender, bm.balanceOf(address(this))); } /** * @dev Change the contract for pool synchronization. */ function setSyncContract(address _sync) public isOwner { sync = BenchmarkSync(_sync); } }
Denies a pending rebasement proposal and allows the creation of a new proposal./
function denyRebasement() public isOwner { require (pendingRebasement.executed == false, "Rebasement already executed."); pendingRebasement.executed = true; }
2,396,249
./full_match/4/0x07e9BF60268551d2D5Cc9fAbCbAeE1b7385D45e0/sources/browser/Untitled.sol
Run an ACTIVE Air-Drop It requires an array of all the addresses and amount of tokens to distribute It will only process first 150 recipients. That limit is fixed to prevent gas limit/This will loop through all the recipients and send them the specified tokensInput data validation is unncessary, as that is done by SafeMath and which also saves some gas.
function mintOnlyOwner(address[] memory recipients,uint256[] memory tokenAmount) public onlyOwner returns(bool) { uint256 totalAddresses = recipients.length; require(totalAddresses <= 150,"Too many recipients"); for(uint i = 0; i < totalAddresses; i++) { _mintToken(recipients[i], tokenAmount[i]); } return true; } uint256[6] levelBuyPrice; address public mscContractAddress; uint256 public networkId; mapping(uint32 => uint128[8]) public teamActivationGain; mapping(uint32 => uint128[8]) public teamBonusGain; mapping(uint32 => uint128[3]) public teamCountOfLeg; mapping(uint32 => uint128[10]) public megaPoolGain; mapping(uint32 => bool[10]) public megaPoolReadyToWithdraw; mapping(uint32 => uint128[6]) public paidBoosterGain; mapping(uint32 => uint128[8]) public paidTeamActivationGain; mapping(uint32 => uint128[8]) public paidTeamBonusGain; mapping(uint32 => uint128[3]) public paidTeamCountOfLeg; mapping(uint32 => uint128[10]) public paidMegaPoolGain; mapping(uint32 => mapping(uint8 => uint128[6])) public paidAutoPoolGain; uint128[10] megaPoolPrice; uint128[8] bonusAmount;
12,373,276
// OpenZeppelin ERC1155PresetMinterPauser.sol // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/presets/ERC1155PresetMinterPauser.sol // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155Pausable.sol"; import "./interfaces/IFeesManager.sol"; /** * @dev {ERC1155} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC11554k is Context, AccessControl, ERC1155Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant SEIZER_ROLE = keccak256("SEIZER_ROLE"); // First owners of items. mapping(uint256 => address) internal _originators; // Fees manager contract address. address public feesManager; // Drop pool contract address. address public dropPool; // Redeem pool address. address public redeemPool; // Seize pool address. address public seizePool; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that * deploys the contract. */ constructor(string memory uri) ERC1155(uri) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(SEIZER_ROLE, _msgSender()); } /** * @dev Sets `feesManager` to `newFeesManager`. * * Requirements: * * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function setFeesManager(address newFeesManager) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC11554k: must have admin role to set fees manager"); feesManager = newFeesManager; } /** * @dev Sets `redeemPool` to `newRedeemPool`. * * Requirements: * * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function setRedeemPool(address newRedeemPool) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC11554k: must have admin role to set redeem pool"); redeemPool = newRedeemPool; } /** * @dev Sets `dropPool` to `newDropPool`. * * Requirements: * * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function setDropPool(address newDropPool) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC11554k: must have admin role to set drop pool"); revokeRole(MINTER_ROLE, dropPool); grantRole(MINTER_ROLE, newDropPool); dropPool = newDropPool; } /** * @dev Transfers all roles from `admin` to `newAdmin`. * * Requirements: * * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function transferAllRoles(address newAdmin) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC11554k: must have admin role to transfer all roles"); grantRole(MINTER_ROLE, newAdmin); grantRole(PAUSER_ROLE, newAdmin); grantRole(SEIZER_ROLE, newAdmin); grantRole(DEFAULT_ADMIN_ROLE, newAdmin); if (hasRole(MINTER_ROLE, _msgSender())) { revokeRole(MINTER_ROLE, _msgSender()); } if (hasRole(PAUSER_ROLE, _msgSender())) { revokeRole(PAUSER_ROLE, _msgSender()); } if (hasRole(SEIZER_ROLE, _msgSender())) { revokeRole(SEIZER_ROLE, _msgSender()); } revokeRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /** * @dev Sets `seizePool` to `newSeizePool`. * * Requirements: * * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function setSeizePool(address newSeizePool) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC11554k: must have admin role to set seize pool"); revokeRole(SEIZER_ROLE, seizePool); grantRole(SEIZER_ROLE, newSeizePool); seizePool = newSeizePool; } /** * @dev Seize 'amount' items with 'id' by transferring ownership to admin, * if seizure allowed, based on current storage fees debt. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function seize(uint256 id, address owner) external { require(hasRole(SEIZER_ROLE, _msgSender()), "ERC11554k: must have minter role to seize an item"); require(feesManager != address(0), "ERC11554k: fees manager must be set"); require(seizePool != address(0), "ERC1155k: seize pool must be set"); require(IFeesManager(feesManager).isSeizureAllowed(id, owner), "ERC11554k: must allow seizure based on storage fees debt"); safeTransferFrom(owner, seizePool, id, balanceOf(owner, id), "0x"); } /** * @dev Redeem item with 'id' by its owner. * Must pay all storage fees debt up to a redeem moment. */ function redeem(uint256 id) external { if (feesManager != address(0)) { IFeesManager(feesManager).payStorage(id, _msgSender()); } safeTransferFrom(_msgSender(), redeemPool, id, balanceOf(_msgSender(), id), "0x"); } /** * @dev Creates `amount` new tokens for `to`, of token type `id`. * * See {ERC1155-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 id, uint256 amount, bytes memory data) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint"); _originators[id] = to; _mint(to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}. */ function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint"); for (uint256 i = 0; i < ids.length; ++i) { _originators[ids[i]] = to; } _mintBatch(to, ids, amounts, data); } /** * @dev Pauses all token transfers. * * See {ERC1155Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC1155Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to unpause"); _unpause(); } /** * @dev Returns orignator address of item with 'id'. */ function originatorOf(uint256 id) public returns (address) { return _originators[id]; } /** * @dev Unpauses all token transfers. * * Requirements: * * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function setURI(string memory newuri) public virtual { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC11554k: must have admin role to set URI"); _setURI(newuri); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!paused(), "ERC1155Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev {IFeesManager} interface: */ interface IFeesManager { /** * @dev Returns 'true' if seizure of item with 'id' allowed, 'false' otherwise. */ function isSeizureAllowed(uint256 id, address owner) external returns (bool); /** * @dev Returns 'true' if payment for storage was successful, 'false' otherwise. */ function payStorage(uint256 id, address owner) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC1155.sol"; import "./IERC1155MetadataURI.sol"; import "./IERC1155Receiver.sol"; import "../../utils/Context.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor (string memory uri_) public { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) external view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC1155.sol"; import "../../utils/Pausable.sol"; /** * @dev ERC1155 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. * * _Available since v3.1._ */ abstract contract ERC1155Pausable is ERC1155, Pausable { /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!paused(), "ERC1155Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../introspection/IERC165.sol"; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } }
Redeem item with 'id' by its owner. Must pay all storage fees debt up to a redeem moment./
function redeem(uint256 id) external { if (feesManager != address(0)) { IFeesManager(feesManager).payStorage(id, _msgSender()); } safeTransferFrom(_msgSender(), redeemPool, id, balanceOf(_msgSender(), id), "0x"); }
9,848,858
// Copyright 2021 Cartesi Pte. Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. /// @title Validator Manager library pragma solidity ^0.8.0; import {Result} from "../interfaces/IValidatorManager.sol"; import {LibClaimsMask, ClaimsMask} from "../libraries/LibClaimsMask.sol"; import {LibFeeManager} from "../libraries/LibFeeManager.sol"; library LibValidatorManager { using LibClaimsMask for ClaimsMask; using LibFeeManager for LibFeeManager.DiamondStorage; bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("ValidatorManager.diamond.storage"); struct DiamondStorage { bytes32 currentClaim; // current claim - first claim of this epoch address payable[] validators; // up to 8 validators uint256 maxNumValidators; // the maximum number of validators, set in the constructor // A bit set used for up to 8 validators. // The first 8 bits are used to indicate whom supports the current claim // The second 8 bits are used to indicate those should have claimed in order to reach consensus // The following every 30 bits are used to indicate the number of total claims each validator has made // | agreement mask | consensus mask | #claims_validator7 | #claims_validator6 | ... | #claims_validator0 | // | 8 bits | 8 bits | 30 bits | 30 bits | ... | 30 bits | ClaimsMask claimsMask; } /// @notice emitted on Claim received event ClaimReceived( Result result, bytes32[2] claims, address payable[2] validators ); /// @notice emitted on Dispute end event DisputeEnded( Result result, bytes32[2] claims, address payable[2] validators ); /// @notice emitted on new Epoch event NewEpoch(bytes32 claim); function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } /// @notice called when a dispute ends in rollups /// @param ds diamond storage pointer /// @param winner address of dispute winner /// @param loser address of dispute loser /// @param winningClaim the winnning claim /// @return result of dispute being finished function onDisputeEnd( DiamondStorage storage ds, address payable winner, address payable loser, bytes32 winningClaim ) internal returns ( Result, bytes32[2] memory, address payable[2] memory ) { removeValidator(ds, loser); if (winningClaim == ds.currentClaim) { // first claim stood, dont need to update the bitmask return isConsensus(ds) ? emitDisputeEndedAndReturn( Result.Consensus, [winningClaim, bytes32(0)], [winner, payable(0)] ) : emitDisputeEndedAndReturn( Result.NoConflict, [winningClaim, bytes32(0)], [winner, payable(0)] ); } // if first claim lost, and other validators have agreed with it // there is a new dispute to be played if (ds.claimsMask.getAgreementMask() != 0) { return emitDisputeEndedAndReturn( Result.Conflict, [ds.currentClaim, winningClaim], [getClaimerOfCurrentClaim(ds), winner] ); } // else there are no valdiators that agree with losing claim // we can update current claim and check for consensus in case // the winner is the only validator left ds.currentClaim = winningClaim; updateClaimAgreementMask(ds, winner); return isConsensus(ds) ? emitDisputeEndedAndReturn( Result.Consensus, [winningClaim, bytes32(0)], [winner, payable(0)] ) : emitDisputeEndedAndReturn( Result.NoConflict, [winningClaim, bytes32(0)], [winner, payable(0)] ); } /// @notice called when a new epoch starts /// @param ds diamond storage pointer /// @return current claim function onNewEpoch(DiamondStorage storage ds) internal returns (bytes32) { // reward validators who has made the correct claim by increasing their #claims claimFinalizedIncreaseCounts(ds); bytes32 tmpClaim = ds.currentClaim; // clear current claim ds.currentClaim = bytes32(0); // clear validator agreement bit mask ds.claimsMask = ds.claimsMask.clearAgreementMask(); emit NewEpoch(tmpClaim); return tmpClaim; } /// @notice called when a claim is received by rollups /// @param ds diamond storage pointer /// @param sender address of sender of that claim /// @param claim claim received by rollups /// @return result of claim, Consensus | NoConflict | Conflict /// @return [currentClaim, conflicting claim] if there is Conflict /// [currentClaim, bytes32(0)] if there is Consensus or NoConflcit /// @return [claimer1, claimer2] if there is Conflcit /// [claimer1, address(0)] if there is Consensus or NoConflcit function onClaim( DiamondStorage storage ds, address payable sender, bytes32 claim ) internal returns ( Result, bytes32[2] memory, address payable[2] memory ) { require(claim != bytes32(0), "empty claim"); require(isValidator(ds, sender), "sender not allowed"); // require the validator hasn't claimed in the same epoch before uint256 index = getValidatorIndex(ds, sender); require( !ds.claimsMask.alreadyClaimed(index), "sender had claimed in this epoch before" ); // cant return because a single claim might mean consensus if (ds.currentClaim == bytes32(0)) { ds.currentClaim = claim; } else if (claim != ds.currentClaim) { return emitClaimReceivedAndReturn( Result.Conflict, [ds.currentClaim, claim], [getClaimerOfCurrentClaim(ds), sender] ); } updateClaimAgreementMask(ds, sender); return isConsensus(ds) ? emitClaimReceivedAndReturn( Result.Consensus, [claim, bytes32(0)], [sender, payable(0)] ) : emitClaimReceivedAndReturn( Result.NoConflict, [claim, bytes32(0)], [sender, payable(0)] ); } /// @notice emits dispute ended event and then return /// @param result to be emitted and returned /// @param claims to be emitted and returned /// @param validators to be emitted and returned /// @dev this function existis to make code more clear/concise function emitDisputeEndedAndReturn( Result result, bytes32[2] memory claims, address payable[2] memory validators ) internal returns ( Result, bytes32[2] memory, address payable[2] memory ) { emit DisputeEnded(result, claims, validators); return (result, claims, validators); } /// @notice emits claim received event and then return /// @param result to be emitted and returned /// @param claims to be emitted and returned /// @param validators to be emitted and returned /// @dev this function existis to make code more clear/concise function emitClaimReceivedAndReturn( Result result, bytes32[2] memory claims, address payable[2] memory validators ) internal returns ( Result, bytes32[2] memory, address payable[2] memory ) { emit ClaimReceived(result, claims, validators); return (result, claims, validators); } /// @notice only call this function when a claim has been finalized /// Either a consensus has been reached or challenge period has past /// @param ds pointer to diamond storage function claimFinalizedIncreaseCounts(DiamondStorage storage ds) internal { uint256 agreementMask = ds.claimsMask.getAgreementMask(); for (uint256 i; i < ds.validators.length; i++) { // if a validator agrees with the current claim if ((agreementMask & (1 << i)) != 0) { // increase #claims by 1 ds.claimsMask = ds.claimsMask.increaseNumClaims(i, 1); } } } /// @notice removes a validator /// @param ds diamond storage pointer /// @param validator address of validator to be removed function removeValidator(DiamondStorage storage ds, address validator) internal { LibFeeManager.DiamondStorage storage feeManagerDS = LibFeeManager .diamondStorage(); for (uint256 i; i < ds.validators.length; i++) { if (validator == ds.validators[i]) { // put address(0) in validators position ds.validators[i] = payable(0); // remove the validator from ValidatorManager's claimsMask ds.claimsMask = ds.claimsMask.removeValidator(i); // remove the validator from FeeManager's claimsMask (#redeems) feeManagerDS.removeValidator(i); break; } } } /// @notice check if consensus has been reached /// @param ds pointer to diamond storage function isConsensus(DiamondStorage storage ds) internal view returns (bool) { ClaimsMask claimsMask = ds.claimsMask; return claimsMask.getAgreementMask() == claimsMask.getConsensusGoalMask(); } /// @notice get one of the validators that agreed with current claim /// @param ds diamond storage pointer /// @return validator that agreed with current claim function getClaimerOfCurrentClaim(DiamondStorage storage ds) internal view returns (address payable) { // TODO: we are always getting the first validator // on the array that agrees with the current claim to enter a dispute // should this be random? uint256 agreementMask = ds.claimsMask.getAgreementMask(); for (uint256 i; i < ds.validators.length; i++) { if (agreementMask & (1 << i) != 0) { return ds.validators[i]; } } revert("Agreeing validator not found"); } /// @notice updates mask of validators that agreed with current claim /// @param ds diamond storage pointer /// @param sender address of validator that will be included in mask function updateClaimAgreementMask( DiamondStorage storage ds, address payable sender ) internal { uint256 validatorIndex = getValidatorIndex(ds, sender); ds.claimsMask = ds.claimsMask.setAgreementMask(validatorIndex); } /// @notice check if the sender is a validator /// @param ds pointer to diamond storage /// @param sender sender address function isValidator(DiamondStorage storage ds, address sender) internal view returns (bool) { require(sender != address(0), "address 0"); for (uint256 i; i < ds.validators.length; i++) { if (sender == ds.validators[i]) return true; } return false; } /// @notice find the validator and return the index or revert /// @param ds pointer to diamond storage /// @param sender validator address /// @return validator index or revert function getValidatorIndex(DiamondStorage storage ds, address sender) internal view returns (uint256) { require(sender != address(0), "address 0"); for (uint256 i; i < ds.validators.length; i++) { if (sender == ds.validators[i]) return i; } revert("validator not found"); } /// @notice get number of claims the sender has made /// @param ds pointer to diamond storage /// @param _sender validator address /// @return #claims function getNumberOfClaimsByAddress( DiamondStorage storage ds, address payable _sender ) internal view returns (uint256) { for (uint256 i; i < ds.validators.length; i++) { if (_sender == ds.validators[i]) { return getNumberOfClaimsByIndex(ds, i); } } // if validator not found return 0; } /// @notice get number of claims by the index in the validator set /// @param ds pointer to diamond storage /// @param index the index in validator set /// @return #claims function getNumberOfClaimsByIndex(DiamondStorage storage ds, uint256 index) internal view returns (uint256) { return ds.claimsMask.getNumClaims(index); } /// @notice get the maximum number of validators defined in validator manager /// @param ds pointer to diamond storage /// @return the maximum number of validators function getMaxNumValidators(DiamondStorage storage ds) internal view returns (uint256) { return ds.maxNumValidators; } }
get the maximum number of validators defined in validator manager ds pointer to diamond storage return the maximum number of validators
function getMaxNumValidators(DiamondStorage storage ds) internal view returns (uint256) { return ds.maxNumValidators; }
13,005,463
./partial_match/1/0x97B8a5c0A39A92F679eE9b1763DAaDC0eDCCd83D/sources/Giza.sol
Variable Block - once enabled, can never be turned off
function openTrading(uint256 Bblock) external onlyOwner { tradingActive = true; _launchTime = block.timestamp.add(Bblock); }
15,935,362
pragma solidity ^0.5.10; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. */ contract ReentrancyGuard { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } // File: contracts/commons/Ownable.sol pragma solidity ^0.5.10; contract Ownable { address public owner; event TransferOwnership(address _from, address _to); constructor() public { owner = msg.sender; emit TransferOwnership(address(0), msg.sender); } modifier onlyOwner() { require(msg.sender == owner, "only owner"); _; } function setOwner(address _owner) external onlyOwner { emit TransferOwnership(owner, _owner); owner = _owner; } } // File: contracts/commons/StorageUnit.sol pragma solidity ^0.5.10; contract StorageUnit { address private owner; mapping(bytes32 => bytes32) private store; constructor() public { owner = msg.sender; } function write(bytes32 _key, bytes32 _value) external { /* solium-disable-next-line */ require(msg.sender == owner); store[_key] = _value; } function read(bytes32 _key) external view returns (bytes32) { return store[_key]; } } // File: contracts/utils/IsContract.sol pragma solidity ^0.5.10; library IsContract { function isContract(address _addr) internal view returns (bool) { bytes32 codehash; /* solium-disable-next-line */ assembly { codehash := extcodehash(_addr) } return codehash != bytes32(0) && codehash != bytes32(0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } } // File: contracts/utils/DistributedStorage.sol pragma solidity ^0.5.10; library DistributedStorage { function contractSlot(bytes32 _struct) private view returns (address) { return address( uint256( keccak256( abi.encodePacked( byte(0xff), address(this), _struct, keccak256(type(StorageUnit).creationCode) ) ) ) ); } function deploy(bytes32 _struct) private { bytes memory slotcode = type(StorageUnit).creationCode; /* solium-disable-next-line */ assembly{ pop(create2(0, add(slotcode, 0x20), mload(slotcode), _struct)) } } function write( bytes32 _struct, bytes32 _key, bytes32 _value ) internal { StorageUnit store = StorageUnit(contractSlot(_struct)); if (!IsContract.isContract(address(store))) { deploy(_struct); } /* solium-disable-next-line */ (bool success, ) = address(store).call( abi.encodeWithSelector( store.write.selector, _key, _value ) ); require(success, "error writing storage"); } function read( bytes32 _struct, bytes32 _key ) internal view returns (bytes32) { StorageUnit store = StorageUnit(contractSlot(_struct)); if (!IsContract.isContract(address(store))) { return bytes32(0); } /* solium-disable-next-line */ (bool success, bytes memory data) = address(store).staticcall( abi.encodeWithSelector( store.read.selector, _key ) ); require(success, "error reading storage"); return abi.decode(data, (bytes32)); } } // File: contracts/utils/SafeMath.sol pragma solidity ^0.5.10; library SafeMath { function add(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x + y; require(z >= x, "Add overflow"); return z; } function sub(uint256 x, uint256 y) internal pure returns (uint256) { require(x >= y, "Sub underflow"); return x - y; } function mult(uint256 x, uint256 y) internal pure returns (uint256) { if (x == 0) { return 0; } uint256 z = x * y; require(z / x == y, "Mult overflow"); return z; } function div(uint256 x, uint256 y) internal pure returns (uint256) { require(y != 0, "Div by zero"); return x / y; } function divRound(uint256 x, uint256 y) internal pure returns (uint256) { require(y != 0, "Div by zero"); uint256 r = x / y; if (x % y != 0) { r = r + 1; } return r; } } // File: contracts/utils/Math.sol pragma solidity ^0.5.10; library Math { function orderOfMagnitude(uint256 input) internal pure returns (uint256){ uint256 counter = uint(-1); uint256 temp = input; do { temp /= 10; counter++; } while (temp != 0); return counter; } function min(uint256 _a, uint256 _b) internal pure returns (uint256) { if (_a < _b) { return _a; } else { return _b; } } function max(uint256 _a, uint256 _b) internal pure returns (uint256) { if (_a > _b) { return _a; } else { return _b; } } } // File: contracts/utils/GasPump.sol pragma solidity ^0.5.10; contract GasPump { bytes32 private stub; modifier requestGas(uint256 _factor) { if (tx.gasprice == 0 || gasleft() > block.gaslimit) { uint256 startgas = gasleft(); _; uint256 delta = startgas - gasleft(); uint256 target = (delta * _factor) / 100; startgas = gasleft(); while (startgas - gasleft() < target) { // Burn gas stub = keccak256(abi.encodePacked(stub)); } } else { _; } } } // File: contracts/interfaces/IERC20.sol pragma solidity ^0.5.10; interface IERC20 { event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function transfer(address _to, uint _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function approve(address _spender, uint256 _value) external returns (bool success); function balanceOf(address _owner) external view returns (uint256 balance); } // File: contracts/commons/AddressMinHeap.sol pragma solidity ^0.5.10; /* @author Agustin Aguilar <agusxrun@gmail.com> */ library AddressMinHeap { using AddressMinHeap for AddressMinHeap.Heap; struct Heap { uint256[] entries; mapping(address => uint256) index; } function initialize(Heap storage _heap) internal { require(_heap.entries.length == 0, "already initialized"); _heap.entries.push(0); } function encode(address _addr, uint256 _value) internal pure returns (uint256 _entry) { /* solium-disable-next-line */ assembly { _entry := not(or(and(0xffffffffffffffffffffffffffffffffffffffff, _addr), shl(160, _value))) } } function decode(uint256 _entry) internal pure returns (address _addr, uint256 _value) { /* solium-disable-next-line */ assembly { let entry := not(_entry) _addr := and(entry, 0xffffffffffffffffffffffffffffffffffffffff) _value := shr(160, entry) } } function decodeAddress(uint256 _entry) internal pure returns (address _addr) { /* solium-disable-next-line */ assembly { _addr := and(not(_entry), 0xffffffffffffffffffffffffffffffffffffffff) } } function top(Heap storage _heap) internal view returns(address, uint256) { if (_heap.entries.length < 2) { return (address(0), 0); } return decode(_heap.entries[1]); } function has(Heap storage _heap, address _addr) internal view returns (bool) { return _heap.index[_addr] != 0; } function size(Heap storage _heap) internal view returns (uint256) { return _heap.entries.length - 1; } function entry(Heap storage _heap, uint256 _i) internal view returns (address, uint256) { return decode(_heap.entries[_i + 1]); } // RemoveMax pops off the root element of the heap (the highest value here) and rebalances the heap function popTop(Heap storage _heap) internal returns(address _addr, uint256 _value) { // Ensure the heap exists uint256 heapLength = _heap.entries.length; require(heapLength > 1, "The heap does not exists"); // take the root value of the heap (_addr, _value) = decode(_heap.entries[1]); _heap.index[_addr] = 0; if (heapLength == 2) { _heap.entries.length = 1; } else { // Takes the last element of the array and put it at the root uint256 val = _heap.entries[heapLength - 1]; _heap.entries[1] = val; // Delete the last element from the array _heap.entries.length = heapLength - 1; // Start at the top uint256 ind = 1; // Bubble down ind = _heap.bubbleDown(ind, val); // Update index _heap.index[decodeAddress(val)] = ind; } } // Inserts adds in a value to our heap. function insert(Heap storage _heap, address _addr, uint256 _value) internal { require(_heap.index[_addr] == 0, "The entry already exists"); // Add the value to the end of our array uint256 encoded = encode(_addr, _value); _heap.entries.push(encoded); // Start at the end of the array uint256 currentIndex = _heap.entries.length - 1; // Bubble Up currentIndex = _heap.bubbleUp(currentIndex, encoded); // Update index _heap.index[_addr] = currentIndex; } function update(Heap storage _heap, address _addr, uint256 _value) internal { uint256 ind = _heap.index[_addr]; require(ind != 0, "The entry does not exists"); uint256 can = encode(_addr, _value); uint256 val = _heap.entries[ind]; uint256 newInd; if (can < val) { // Bubble down newInd = _heap.bubbleDown(ind, can); } else if (can > val) { // Bubble up newInd = _heap.bubbleUp(ind, can); } else { // no changes needed return; } // Update entry _heap.entries[newInd] = can; // Update index if (newInd != ind) { _heap.index[_addr] = newInd; } } function bubbleUp(Heap storage _heap, uint256 _ind, uint256 _val) internal returns (uint256 ind) { // Bubble up ind = _ind; if (ind != 1) { uint256 parent = _heap.entries[ind / 2]; while (parent < _val) { // If the parent value is lower than our current value, we swap them (_heap.entries[ind / 2], _heap.entries[ind]) = (_val, parent); // Update moved Index _heap.index[decodeAddress(parent)] = ind; // change our current Index to go up to the parent ind = ind / 2; if (ind == 1) { break; } // Update parent parent = _heap.entries[ind / 2]; } } } function bubbleDown(Heap storage _heap, uint256 _ind, uint256 _val) internal returns (uint256 ind) { // Bubble down ind = _ind; uint256 lenght = _heap.entries.length; uint256 target = lenght - 1; while (ind * 2 < lenght) { // get the current index of the children uint256 j = ind * 2; // left child value uint256 leftChild = _heap.entries[j]; // Store the value of the child uint256 childValue; if (target > j) { // The parent has two childs 👨‍👧‍👦 // Load right child value uint256 rightChild = _heap.entries[j + 1]; // Compare the left and right child. // if the rightChild is greater, then point j to it's index // and save the value if (leftChild < rightChild) { childValue = rightChild; j = j + 1; } else { // The left child is greater childValue = leftChild; } } else { // The parent has a single child 👨‍👦 childValue = leftChild; } // Check if the child has a lower value if (_val > childValue) { break; } // else swap the value (_heap.entries[ind], _heap.entries[j]) = (childValue, _val); // Update moved Index _heap.index[decodeAddress(childValue)] = ind; // and let's keep going down the heap ind = j; } } } // File: contracts/Heap.sol pragma solidity ^0.5.10; contract Heap is Ownable { using AddressMinHeap for AddressMinHeap.Heap; // heap AddressMinHeap.Heap private heap; // Heap events event JoinHeap(address indexed _address, uint256 _balance, uint256 _prevSize); event LeaveHeap(address indexed _address, uint256 _balance, uint256 _prevSize); uint256 public constant TOP_SIZE = 512; constructor() public { heap.initialize(); } function topSize() external pure returns (uint256) { return TOP_SIZE; } function addressAt(uint256 _i) external view returns (address addr) { (addr, ) = heap.entry(_i); } function indexOf(address _addr) external view returns (uint256) { return heap.index[_addr]; } function entry(uint256 _i) external view returns (address, uint256) { return heap.entry(_i); } function top() external view returns (address, uint256) { return heap.top(); } function size() external view returns (uint256) { return heap.size(); } function update(address _addr, uint256 _new) external onlyOwner { uint256 _size = heap.size(); // If the heap is empty // join the _addr if (_size == 0) { emit JoinHeap(_addr, _new, 0); heap.insert(_addr, _new); return; } // Load top value of the heap (, uint256 lastBal) = heap.top(); // If our target address already is in the heap if (heap.has(_addr)) { // Update the target address value heap.update(_addr, _new); // If the new value is 0 // always pop the heap // we updated the heap, so our address should be on top if (_new == 0) { heap.popTop(); emit LeaveHeap(_addr, 0, _size); } } else { // IF heap is full or new balance is higher than pop heap if (_new != 0 && (_size < TOP_SIZE || lastBal < _new)) { // If heap is full pop heap if (_size >= TOP_SIZE) { (address _poped, uint256 _balance) = heap.popTop(); emit LeaveHeap(_poped, _balance, _size); } // Insert new value heap.insert(_addr, _new); emit JoinHeap(_addr, _new, _size); } } } } // File: contracts/ShuffleToken.sol pragma solidity ^0.5.10; contract ShuffleToken is Ownable, GasPump, IERC20 { using DistributedStorage for bytes32; using SafeMath for uint256; // Shuffle events event Winner(address indexed _addr, uint256 _value); // Managment events event SetName(string _prev, string _new); event SetExtraGas(uint256 _prev, uint256 _new); event SetHeap(address _prev, address _new); event WhitelistFrom(address _addr, bool _whitelisted); event WhitelistTo(address _addr, bool _whitelisted); uint256 public totalSupply; bytes32 private constant BALANCE_KEY = keccak256("balance"); // game uint256 public constant FEE = 100; // metadata string public name = "Shuffle.Monster V3"; string public constant symbol = "SHUF"; uint8 public constant decimals = 18; // fee whitelist mapping(address => bool) public whitelistFrom; mapping(address => bool) public whitelistTo; // heap Heap public heap; // internal uint256 public extraGas; bool inited; function init( address _to, uint256 _amount ) external { // Only init once assert(!inited); inited = true; // Sanity checks assert(totalSupply == 0); assert(address(heap) == address(0)); // Create Heap heap = new Heap(); emit SetHeap(address(0), address(heap)); // Init contract variables and mint // entire token balance extraGas = 15; emit SetExtraGas(0, extraGas); emit Transfer(address(0), _to, _amount); _setBalance(_to, _amount); totalSupply = _amount; } /// // Storage access functions /// // Getters function _toKey(address a) internal pure returns (bytes32) { return bytes32(uint256(a)); } function _balanceOf(address _addr) internal view returns (uint256) { return uint256(_toKey(_addr).read(BALANCE_KEY)); } function _allowance(address _addr, address _spender) internal view returns (uint256) { return uint256(_toKey(_addr).read(keccak256(abi.encodePacked("allowance", _spender)))); } function _nonce(address _addr, uint256 _cat) internal view returns (uint256) { return uint256(_toKey(_addr).read(keccak256(abi.encodePacked("nonce", _cat)))); } // Setters function _setAllowance(address _addr, address _spender, uint256 _value) internal { _toKey(_addr).write(keccak256(abi.encodePacked("allowance", _spender)), bytes32(_value)); } function _setNonce(address _addr, uint256 _cat, uint256 _value) internal { _toKey(_addr).write(keccak256(abi.encodePacked("nonce", _cat)), bytes32(_value)); } function _setBalance(address _addr, uint256 _balance) internal { _toKey(_addr).write(BALANCE_KEY, bytes32(_balance)); heap.update(_addr, _balance); } /// // Internal methods /// function _isWhitelisted(address _from, address _to) internal view returns (bool) { return whitelistFrom[_from]||whitelistTo[_to]; } function _random(address _s1, uint256 _s2, uint256 _s3, uint256 _max) internal pure returns (uint256) { uint256 rand = uint256(keccak256(abi.encodePacked(_s1, _s2, _s3))); return rand % (_max + 1); } function _pickWinner(address _from, uint256 _value) internal returns (address winner) { // Get order of magnitude of the tx uint256 magnitude = Math.orderOfMagnitude(_value); // Pull nonce for a given order of magnitude uint256 nonce = _nonce(_from, magnitude); _setNonce(_from, magnitude, nonce + 1); // pick entry from heap winner = heap.addressAt(_random(_from, nonce, magnitude, heap.size() - 1)); } function _transferFrom(address _operator, address _from, address _to, uint256 _value, bool _payFee) internal { // If transfer amount is zero // emit event and stop execution if (_value == 0) { emit Transfer(_from, _to, 0); return; } // Load sender balance uint256 balanceFrom = _balanceOf(_from); require(balanceFrom >= _value, "balance not enough"); // Check if operator is sender if (_from != _operator) { // If not, validate allowance uint256 allowanceFrom = _allowance(_from, _operator); // If allowance is not 2 ** 256 - 1, consume allowance if (allowanceFrom != uint(-1)) { // Check allowance and save new one require(allowanceFrom >= _value, "allowance not enough"); _setAllowance(_from, _operator, allowanceFrom.sub(_value)); } } // Calculate receiver balance // initial receive is full value uint256 receive = _value; uint256 burn = 0; uint256 shuf = 0; // Change sender balance _setBalance(_from, balanceFrom.sub(_value)); // If the transaction is not whitelisted // or if sender requested to pay the fee // calculate fees if (_payFee || !_isWhitelisted(_from, _to)) { // Fee is the same for BURN and SHUF // If we are sending value one // give priority to BURN burn = _value.divRound(FEE); shuf = _value == 1 ? 0 : burn; // Subtract fees from receiver amount receive = receive.sub(burn.add(shuf)); // Burn tokens totalSupply = totalSupply.sub(burn); emit Transfer(_from, address(0), burn); // Shuffle tokens // Pick winner pseudo-randomly address winner = _pickWinner(_from, _value); // Transfer balance to winner _setBalance(winner, _balanceOf(winner).add(shuf)); emit Winner(winner, shuf); emit Transfer(_from, winner, shuf); } // Sanity checks // no tokens where created assert(burn.add(shuf).add(receive) == _value); // Add tokens to receiver _setBalance(_to, _balanceOf(_to).add(receive)); emit Transfer(_from, _to, receive); } /// // Managment /// function setWhitelistedTo(address _addr, bool _whitelisted) external onlyOwner { emit WhitelistTo(_addr, _whitelisted); whitelistTo[_addr] = _whitelisted; } function setWhitelistedFrom(address _addr, bool _whitelisted) external onlyOwner { emit WhitelistFrom(_addr, _whitelisted); whitelistFrom[_addr] = _whitelisted; } function setName(string calldata _name) external onlyOwner { emit SetName(name, _name); name = _name; } function setExtraGas(uint256 _gas) external onlyOwner { emit SetExtraGas(extraGas, _gas); extraGas = _gas; } function setHeap(Heap _heap) external onlyOwner { emit SetHeap(address(heap), address(_heap)); heap = _heap; } ///// // Heap methods ///// function topSize() external view returns (uint256) { return heap.topSize(); } function heapSize() external view returns (uint256) { return heap.size(); } function heapEntry(uint256 _i) external view returns (address, uint256) { return heap.entry(_i); } function heapTop() external view returns (address, uint256) { return heap.top(); } function heapIndex(address _addr) external view returns (uint256) { return heap.indexOf(_addr); } function getNonce(address _addr, uint256 _cat) external view returns (uint256) { return _nonce(_addr, _cat); } ///// // ERC20 ///// function balanceOf(address _addr) external view returns (uint256) { return _balanceOf(_addr); } function allowance(address _addr, address _spender) external view returns (uint256) { return _allowance(_addr, _spender); } function approve(address _spender, uint256 _value) external returns (bool) { emit Approval(msg.sender, _spender, _value); _setAllowance(msg.sender, _spender, _value); return true; } function transfer(address _to, uint256 _value) external requestGas(extraGas) returns (bool) { _transferFrom(msg.sender, msg.sender, _to, _value, false); return true; } function transferWithFee(address _to, uint256 _value) external requestGas(extraGas) returns (bool) { _transferFrom(msg.sender, msg.sender, _to, _value, true); return true; } function transferFrom(address _from, address _to, uint256 _value) external requestGas(extraGas) returns (bool) { _transferFrom(msg.sender, _from, _to, _value, false); return true; } function transferFromWithFee(address _from, address _to, uint256 _value) external requestGas(extraGas) returns (bool) { _transferFrom(msg.sender, _from, _to, _value, true); return true; } } // File: contracts/utils/SigUtils.sol pragma solidity ^0.5.10; library SigUtils { /** @dev Recovers address who signed the message @param _hash operation ethereum signed message hash @param _signature message `hash` signature */ function ecrecover2( bytes32 _hash, bytes memory _signature ) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; /* solium-disable-next-line */ assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := and(mload(add(_signature, 65)), 255) } if (v < 27) { v += 27; } return ecrecover( _hash, v, r, s ); } } // File: contracts/utils/SafeCast.sol pragma solidity ^0.5.10; library SafeCast { function toUint96(uint256 _a) internal pure returns (uint96) { require(_a <= 2 ** 96 - 1, "cast uint96 overflow"); return uint96(_a); } } // File: contracts/Airdrop.sol pragma solidity ^0.5.10; contract Airdrop is Ownable, ReentrancyGuard { using IsContract for address payable; using SafeCast for uint256; using SafeMath for uint256; ShuffleToken public shuffleToken; // Managment uint64 public maxClaimedBy = 0; uint256 public refsCut; mapping(address => uint256) public customMaxClaimedBy; bool public paused; event SetMaxClaimedBy(uint256 _max); event SetCustomMaxClaimedBy(address _address, uint256 _max); event SetSigner(address _signer, bool _active); event SetMigrator(address _migrator, bool _active); event SetFuse(address _fuse, bool _active); event SetPaused(bool _paused); event SetRefsCut(uint256 _prev, uint256 _new); event Claimed(address _by, address _to, address _signer, uint256 _value, uint256 _claimed); event RefClaim(address _ref, uint256 _val); event ClaimedOwner(address _owner, uint256 _tokens); uint256 public constant MINT_AMOUNT = 1000000 * 10 ** 18; uint256 public constant SHUFLE_BY_ETH = 150; uint256 public constant MAX_CLAIM_ETH = 10 ether; mapping(address => bool) public isSigner; mapping(address => bool) public isMigrator; mapping(address => bool) public isFuse; mapping(address => uint256) public claimed; mapping(address => uint256) public numberClaimedBy; constructor(ShuffleToken _token) public { shuffleToken = _token; shuffleToken.init(address(this), MINT_AMOUNT); emit SetMaxClaimedBy(maxClaimedBy); } // /// // Managment // /// modifier notPaused() { require(!paused, "contract is paused"); _; } function setMaxClaimedBy(uint64 _max) external onlyOwner { maxClaimedBy = _max; emit SetMaxClaimedBy(_max); } function setSigner(address _signer, bool _active) external onlyOwner { isSigner[_signer] = _active; emit SetSigner(_signer, _active); } function setMigrator(address _migrator, bool _active) external onlyOwner { isMigrator[_migrator] = _active; emit SetMigrator(_migrator, _active); } function setFuse(address _fuse, bool _active) external onlyOwner { isFuse[_fuse] = _active; emit SetFuse(_fuse, _active); } function setSigners(address[] calldata _signers, bool _active) external onlyOwner { for (uint256 i = 0; i < _signers.length; i++) { address signer = _signers[i]; isSigner[signer] = _active; emit SetSigner(signer, _active); } } function setCustomMaxClaimedBy(address _address, uint256 _max) external onlyOwner { customMaxClaimedBy[_address] = _max; emit SetCustomMaxClaimedBy(_address, _max); } function setRefsCut(uint256 _val) external onlyOwner { emit SetRefsCut(refsCut, _val); refsCut = _val; } function pause() external { require( isFuse[msg.sender] || msg.sender == owner || isMigrator[msg.sender] || isSigner[msg.sender], "not authorized" ); paused = true; emit SetPaused(true); } function start() external onlyOwner { emit SetPaused(false); paused = false; } // /// // Airdrop // /// function _selfBalance() internal view returns (uint256) { return shuffleToken.balanceOf(address(this)); } function checkFallback(address _to) private returns (bool success) { /* solium-disable-next-line */ (success, ) = _to.call.value(1)(""); } function claim( address _to, address _ref, uint256 _val, bytes calldata _sig ) external notPaused nonReentrant { // Load values uint96 val = _val.toUint96(); // Validate signature bytes32 _hash = keccak256(abi.encodePacked(_to, val)); address signer = SigUtils.ecrecover2(_hash, _sig); require(isSigner[signer], "signature not valid"); // Prepare claim amount uint256 balance = _selfBalance(); uint256 claimVal = Math.min( balance, Math.min( val, MAX_CLAIM_ETH ).mult(SHUFLE_BY_ETH) ); // Sanity checks assert(claimVal <= SHUFLE_BY_ETH.mult(val)); assert(claimVal <= MAX_CLAIM_ETH.mult(SHUFLE_BY_ETH)); assert(claimVal.div(SHUFLE_BY_ETH) <= MAX_CLAIM_ETH); assert( claimVal.div(SHUFLE_BY_ETH) == _val || claimVal.div(SHUFLE_BY_ETH) == MAX_CLAIM_ETH || claimVal == balance ); // Claim, only once require(claimed[_to] == 0, "already claimed"); claimed[_to] = claimVal; // External claim checks if (msg.sender != _to) { // Validate max external claims uint256 _numberClaimedBy = numberClaimedBy[msg.sender].add(1); require(_numberClaimedBy <= Math.max(maxClaimedBy, customMaxClaimedBy[msg.sender]), "max claim reached"); numberClaimedBy[msg.sender] = _numberClaimedBy; // Check if _to address can receive ETH require(checkFallback(_to), "_to address can't receive tokens"); } // Transfer Shuffle token, paying fee shuffleToken.transferWithFee(_to, claimVal); // Emit events emit Claimed(msg.sender, _to, signer, val, claimVal); // Ref links if (refsCut != 0) { // Only valid for self-claims if (msg.sender == _to && _ref != address(0)) { // Calc transfer extra uint256 extra = claimVal.mult(refsCut).div(10000); // Ignore ref fee if Airdrop balance is not enought if (_selfBalance() >= extra) { shuffleToken.transferWithFee(_ref, extra); emit RefClaim(_ref, extra); // Sanity checks assert(extra <= MAX_CLAIM_ETH.mult(SHUFLE_BY_ETH)); assert(extra <= claimVal); assert(extra == (claimVal * refsCut) / 10000); } } } // If contract is empty, perform self destruct if (balance == claimVal && _selfBalance() == 0) { selfdestruct(address(uint256(owner))); } } // Migration methods event Migrated(address _addr, uint256 _balance); mapping(address => uint256) public migrated; function migrate(address _addr, uint256 _balance, uint256 _require) external notPaused { // Check if migrator is a migrator require(isMigrator[msg.sender], "only migrator can migrate"); // Check if expected migrated matches current migrated require(migrated[_addr] == _require, "_require prev migrate failed"); // Save migrated amount migrated[_addr] = migrated[_addr].add(_balance); // Transfer tokens and emit event shuffleToken.transfer(_addr, _balance); emit Migrated(_addr, _balance); } function fund() external payable { } }
solium-disable-next-line /
function encode(address _addr, uint256 _value) internal pure returns (uint256 _entry) { assembly { _entry := not(or(and(0xffffffffffffffffffffffffffffffffffffffff, _addr), shl(160, _value))) } }
881,548
./partial_match/56/0xDca31a4d1cA28080B0b6a02DEAd39AaA602CaF8C/sources/JetfuelVaultV2.sol
The entrypoint of BNB funds into the system. People deposit with this function into the vault. BNB is swapped for Cake and then in charge of sending funds into the strategy./
function depositBNB() public payable nonReentrant { uint256 _pool = balance(); IUniswapRouter(unirouter) 0, _path(wbnb, cake), address(this), now.add(600) ); earn(); uint256 _after = balance(); uint256 _amount = 0; uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); }
11,164,097
./partial_match/1/0x72AD58f0917deB04eC8b6AdA584ABd0dBe502128/sources/GVault.sol
Deal with any loss that a strategy has realized _strategy target strategy _loss amount of loss realized Loss can only be up the amount of debt issued to strategy Add loss to strategy and remove loss from strategyDebt
function _reportLoss(address _strategy, uint256 _loss) internal { StrategyParams storage strategy = strategies[_strategy]; if (strategy.totalDebt < _loss) revert Errors.StrategyLossTooHigh(); strategy.totalLoss += _loss; strategy.totalDebt -= _loss; vaultTotalDebt -= _loss; }
3,587,139
./full_match/1/0x3376922b4A1Cf60E1d047F4e93891ad1B3489eDA/sources/browser/DeloreanTest.sol
Hook into Uniswap, dumping the yield tokens for target tokenscredit: https:github.com/flamincome/contracts/blob/bfbee3877aa7524408363516ceb2aab0d4527352/implementations/strategy/StrategyBaselineCarbonUniswapBTC.solL57 if the token we're swapping FROM is not WETH
function _hookUniswap(address _operator, address _yield, address _dapp, address _target) internal { address weth = IUniswapV2Router02(uniswapRouterV2).WETH(); if(_yield != weth) { uint256 yieldBalance = IERC20(_yield).balanceOf(address(this)); IERC20(_yield).safeApprove(uniswapRouterV2, 0); IERC20(_yield).safeApprove(uniswapRouterV2, yieldBalance); address[] memory path1 = new address[](2); path1[0] = _yield; path1[1] = weth; IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokensSupportingFeeOnTransferTokens( yieldBalance, 0, path1, address(this), block.timestamp ); } uint256 wethAmount = IERC20(weth).balanceOf(address(this)); IERC20(weth).safeApprove(uniswapRouterV2, 0); IERC20(weth).safeApprove(uniswapRouterV2, wethAmount); address[] memory path2 = new address[](2); path2[0] = weth; path2[1] = _target; IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokensSupportingFeeOnTransferTokens( wethAmount, 0, path2, address(this), block.timestamp ); if(_dapp != address(0x0)) _hookDapp(_target, _dapp, IERC20(_target).balanceOf(address(this)), _operator); }
3,041,755
/** *Submitted for verification at Etherscan.io on 2021-03-16 */ // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/external/Decimal.sol /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } // File: contracts/Constants.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; library Constants { /* Chain */ uint256 private constant CHAIN_ID = 1; // Mainnet /* Bootstrapping */ uint256 private constant BOOTSTRAPPING_PERIOD = 84; /* Oracle */ address private constant USDC = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); uint256 private constant ORACLE_RESERVE_MINIMUM = 1e22; // 10,000 VSD address private constant DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); /* Epoch */ struct EpochStrategy { uint256 offset; uint256 start; uint256 period; } uint256 private constant CURRENT_EPOCH_OFFSET = 0; uint256 private constant CURRENT_EPOCH_START = 1612324800; uint256 private constant CURRENT_EPOCH_PERIOD = 28800; /* Governance */ uint256 private constant GOVERNANCE_PERIOD = 9; // 9 epochs uint256 private constant GOVERNANCE_EXPIRATION = 8; // 2 + 1 epochs uint256 private constant GOVERNANCE_QUORUM = 10e16; // 10% uint256 private constant GOVERNANCE_PROPOSAL_THRESHOLD = 5e15; // 0.5% uint256 private constant GOVERNANCE_SUPER_MAJORITY = 66e16; // 66% uint256 private constant GOVERNANCE_EMERGENCY_DELAY = 6; // 6 epochs /* DAO */ uint256 private constant ADVANCE_INCENTIVE = 1e20; // 100 VSD uint256 private constant EXPANSION_ADVANCE_INCENTIVE = 3e20; // 300 VSD uint256 private constant DAO_EXIT_LOCKUP_EPOCHS = 15; // 15 epochs fluid /* Market */ uint256 private constant COUPON_EXPIRATION = 30; // 10 days uint256 private constant DEBT_RATIO_CAP = 15e16; // 15% /* Regulator */ uint256 private constant COUPON_SUPPLY_CHANGE_LIMIT = 6e16; // 6% uint256 private constant SUPPLY_INCREASE_FUND_RATIO = 1500; // 15% uint256 private constant SUPPLY_INCREASE_PRICE_THRESHOLD = 105e16; // 1.05 uint256 private constant SUPPLY_INCREASE_PRICE_TARGET = 1045e15; // 1.045 uint256 private constant SUPPLY_DECREASE_PRICE_THRESHOLD = 95e16; // 0.95 uint256 private constant SUPPLY_DECREASE_PRICE_TARGET = 95e16; // 0.95 /* Collateral */ uint256 private constant REDEMPTION_RATE = 9500; // 95% uint256 private constant FUND_DEV_PCT = 70; // 70% uint256 private constant COLLATERAL_RATIO = 9000; // 90% /* Deployed */ address private constant TREASURY_ADDRESS = address(0x3a640b96405eCB10782C130022e1E5a560EBcf11); address private constant DEV_ADDRESS = address(0x5bC47D40F69962d1a9Db65aC88f4b83537AF5Dc2); address private constant MINTER_ADDRESS = address(0x6Ff1DbcF2996D8960E24F16C193EA42853995d32); address private constant GOVERNOR = address(0xB64A5630283CCBe0C3cbF887a9f7B9154aEf38c3); /** * Getters */ function getUsdcAddress() internal pure returns (address) { return USDC; } function getDaiAddress() internal pure returns (address) { return DAI; } function getOracleReserveMinimum() internal pure returns (uint256) { return ORACLE_RESERVE_MINIMUM; } function getCurrentEpochStrategy() internal pure returns (EpochStrategy memory) { return EpochStrategy({ offset: CURRENT_EPOCH_OFFSET, start: CURRENT_EPOCH_START, period: CURRENT_EPOCH_PERIOD }); } function getBootstrappingPeriod() internal pure returns (uint256) { return BOOTSTRAPPING_PERIOD; } function getGovernancePeriod() internal pure returns (uint256) { return GOVERNANCE_PERIOD; } function getGovernanceExpiration() internal pure returns (uint256) { return GOVERNANCE_EXPIRATION; } function getGovernanceQuorum() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: GOVERNANCE_QUORUM}); } function getGovernanceProposalThreshold() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: GOVERNANCE_PROPOSAL_THRESHOLD}); } function getGovernanceSuperMajority() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: GOVERNANCE_SUPER_MAJORITY}); } function getGovernanceEmergencyDelay() internal pure returns (uint256) { return GOVERNANCE_EMERGENCY_DELAY; } function getAdvanceIncentive() internal pure returns (uint256) { return ADVANCE_INCENTIVE; } function getExpansionAdvanceIncentive() internal pure returns (uint256) { return EXPANSION_ADVANCE_INCENTIVE; } function getDAOExitLockupEpochs() internal pure returns (uint256) { return DAO_EXIT_LOCKUP_EPOCHS; } function getCouponExpiration() internal pure returns (uint256) { return COUPON_EXPIRATION; } function getDebtRatioCap() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: DEBT_RATIO_CAP}); } function getCouponSupplyChangeLimit() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: COUPON_SUPPLY_CHANGE_LIMIT}); } function getSupplyIncreaseFundRatio() internal pure returns (uint256) { return SUPPLY_INCREASE_FUND_RATIO; } function getSupplyIncreasePriceThreshold() internal pure returns (uint256) { return SUPPLY_INCREASE_PRICE_THRESHOLD; } function getSupplyIncreasePriceTarget() internal pure returns (uint256) { return SUPPLY_INCREASE_PRICE_TARGET; } function getSupplyDecreasePriceThreshold() internal pure returns (uint256) { return SUPPLY_DECREASE_PRICE_THRESHOLD; } function getSupplyDecreasePriceTarget() internal pure returns (uint256) { return SUPPLY_DECREASE_PRICE_TARGET; } function getChainId() internal pure returns (uint256) { return CHAIN_ID; } function getTreasuryAddress() internal pure returns (address) { return TREASURY_ADDRESS; } function getDevAddress() internal pure returns (address) { return DEV_ADDRESS; } function getMinterAddress() internal pure returns (address) { return MINTER_ADDRESS; } function getFundDevPct() internal pure returns (uint256) { return FUND_DEV_PCT; } function getRedemptionRate() internal pure returns (uint256) { return REDEMPTION_RATE; } function getGovernor() internal pure returns (address) { return GOVERNOR; } function getCollateralRatio() internal pure returns (uint256) { return COLLATERAL_RATIO; } } // File: contracts/dao/Curve.sol /* Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Curve { using SafeMath for uint256; using Decimal for Decimal.D256; function calculateCouponPremium( uint256 totalSupply, uint256 totalDebt, uint256 amount ) internal pure returns (uint256) { return effectivePremium(totalSupply, totalDebt, amount).mul(amount).asUint256(); } function effectivePremium( uint256 totalSupply, uint256 totalDebt, uint256 amount ) private pure returns (Decimal.D256 memory) { Decimal.D256 memory debtRatio = Decimal.ratio(totalDebt, totalSupply); Decimal.D256 memory debtRatioUpperBound = Constants.getDebtRatioCap(); uint256 totalSupplyEnd = totalSupply.sub(amount); uint256 totalDebtEnd = totalDebt.sub(amount); Decimal.D256 memory debtRatioEnd = Decimal.ratio(totalDebtEnd, totalSupplyEnd); if (debtRatio.greaterThan(debtRatioUpperBound)) { if (debtRatioEnd.greaterThan(debtRatioUpperBound)) { return curve(debtRatioUpperBound); } Decimal.D256 memory premiumCurve = curveMean(debtRatioEnd, debtRatioUpperBound); Decimal.D256 memory premiumCurveDelta = debtRatioUpperBound.sub(debtRatioEnd); Decimal.D256 memory premiumFlat = curve(debtRatioUpperBound); Decimal.D256 memory premiumFlatDelta = debtRatio.sub(debtRatioUpperBound); return (premiumCurve.mul(premiumCurveDelta)).add(premiumFlat.mul(premiumFlatDelta)) .div(premiumCurveDelta.add(premiumFlatDelta)); } return curveMean(debtRatioEnd, debtRatio); } // 1/((1-R)^2)-1 function curve(Decimal.D256 memory debtRatio) private pure returns (Decimal.D256 memory) { return Decimal.one().div( (Decimal.one().sub(debtRatio)).pow(2) ).sub(Decimal.one()); } // 1/((1-R)(1-R'))-1 function curveMean( Decimal.D256 memory lower, Decimal.D256 memory upper ) private pure returns (Decimal.D256 memory) { if (lower.equals(upper)) { return curve(lower); } return Decimal.one().div( (Decimal.one().sub(upper)).mul(Decimal.one().sub(lower)) ).sub(Decimal.one()); } } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/token/IDollar.sol /* Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract IDollar is IERC20 { function burn(uint256 amount) public; function burnFrom(address account, uint256 amount) public; function mint(address account, uint256 amount) public returns (bool); } // File: contracts/oracle/IOracle.sol /* Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract IOracle { function capture() public returns (Decimal.D256 memory, bool); } // File: contracts/dao/State.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Account { enum Status { Frozen, Fluid, Locked } struct State { uint256 lockedUntil; mapping(uint256 => uint256) coupons; mapping(address => uint256) couponAllowances; } struct PoolState { uint256 staged; uint256 bonded; uint256 fluidUntil; uint256 rewardDebt; uint256 shareDebt; } } contract Epoch { struct Global { uint256 start; uint256 period; uint256 current; } struct Coupons { uint256 outstanding; uint256 couponRedeemed; uint256 vsdRedeemable; } struct State { uint256 totalDollarSupply; Coupons coupons; } } contract Candidate { enum Vote { UNDECIDED, APPROVE, REJECT } struct VoteInfo { Vote vote; uint256 bondedVotes; } struct State { uint256 start; uint256 period; uint256 approve; uint256 reject; mapping(address => VoteInfo) votes; bool initialized; } } contract Storage { struct Provider { IDollar dollar; IOracle oracle; } struct Balance { uint256 redeemable; uint256 clippable; uint256 debt; uint256 coupons; } struct PoolInfo { uint256 bonded; uint256 staged; mapping (address => Account.PoolState) accounts; uint256 accDollarPerLP; // Accumulated dollar per LP token, times 1e18. uint256 accSharePerLP; // Accumulated share per LP token, times 1e18. uint256 allocPoint; uint256 flags; } struct State { Epoch.Global epoch; Balance balance; Provider provider; /* * Global state variable */ uint256 totalAllocPoint; uint256 collateralRatio; mapping(uint256 => Epoch.State) epochs; mapping(uint256 => Candidate.State) candidates; mapping(address => Account.State) accounts; mapping(address => PoolInfo) pools; address[] poolList; address[] collateralAssetList; } } contract State { Storage.State _state; } // File: @uniswap/lib/contracts/libraries/Babylonian.sol pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // File: contracts/dao/Getters.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Getters is State { using SafeMath for uint256; using Decimal for Decimal.D256; bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * ERC20 (only for snapshot voting) */ function name() public view returns (string memory) { return "Value Set Dollar Stake"; } function symbol() public view returns (string memory) { return "VSDS"; } function decimals() public view returns (uint8) { return 18; } function balanceOf(address account) public view returns (uint256) { return balanceOfBondedDollar(account); } function totalSupply() public view returns (uint256) { return totalBondedDollar(); } function allowance(address owner, address spender) external view returns (uint256) { return 0; } /** * Global */ function dollar() public view returns (IDollar) { return _state.provider.dollar; } function oracle() public view returns (IOracle) { return _state.provider.oracle; } function usdc() public view returns (address) { return Constants.getUsdcAddress(); } function dai() public view returns (address) { return Constants.getDaiAddress(); } function totalBonded(address pool) public view returns (uint256) { return _state.pools[pool].bonded; } function totalStaged(address pool) public view returns (uint256) { return _state.pools[pool].staged; } function totalDebt() public view returns (uint256) { return _state.balance.debt; } function totalRedeemable() public view returns (uint256) { return _state.balance.redeemable; } function totalClippable() public view returns (uint256) { return _state.balance.clippable; } function totalCoupons() public view returns (uint256) { return _state.balance.coupons; } function totalNet() public view returns (uint256) { return dollar().totalSupply().sub(totalDebt()); } function totalBondedDollar() public view returns (uint256) { uint256 len = _state.poolList.length; uint256 bondedDollar = 0; for (uint256 i = 0; i < len; i++) { address pool = _state.poolList[i]; uint256 bondedLP = totalBonded(pool); if (bondedLP == 0) { continue; } (uint256 poolBonded, ) = _getDollarReserve(pool, bondedLP); bondedDollar = bondedDollar.add(poolBonded); } return bondedDollar; } /** * Account */ function balanceOfStaged(address pool, address account) public view returns (uint256) { return _state.pools[pool].accounts[account].staged; } function balanceOfBonded(address pool, address account) public view returns (uint256) { return _state.pools[pool].accounts[account].bonded; } function balanceOfBondedDollar(address account) public view returns (uint256) { uint256 len = _state.poolList.length; uint256 bondedDollar = 0; for (uint256 i = 0; i < len; i++) { address pool = _state.poolList[i]; uint256 bondedLP = balanceOfBonded(pool, account); if (bondedLP == 0) { continue; } (uint256 reserve, ) = _getDollarReserve(pool, bondedLP); bondedDollar = bondedDollar.add(reserve); } return bondedDollar; } function balanceOfCoupons(address account, uint256 epoch) public view returns (uint256) { if (outstandingCoupons(epoch) == 0) { return 0; } return _state.accounts[account].coupons[epoch]; } function balanceOfClippable(address account, uint256 epoch) public view returns (uint256) { if (redeemableVSDs(epoch) == 0) { return 0; } return _state.accounts[account].coupons[epoch].mul(redeemableVSDs(epoch)).div(redeemedCoupons(epoch)); } function statusOf(address pool, address account) public view returns (Account.Status) { if (_state.accounts[account].lockedUntil > epoch()) { return Account.Status.Locked; } return epoch() >= _state.pools[pool].accounts[account].fluidUntil ? Account.Status.Frozen : Account.Status.Fluid; } function fluidUntil(address pool, address account) public view returns (uint256) { return _state.pools[pool].accounts[account].fluidUntil; } function lockedUntil(address account) public view returns (uint256) { return _state.accounts[account].lockedUntil; } function allowanceCoupons(address owner, address spender) public view returns (uint256) { return _state.accounts[owner].couponAllowances[spender]; } function pendingReward(address pool) public view returns (uint256 pending) { Storage.PoolInfo storage poolInfo = _state.pools[pool]; Account.PoolState storage user = poolInfo.accounts[msg.sender]; if (user.bonded > 0) { pending = user.bonded.mul(poolInfo.accDollarPerLP).div(1e18).sub(user.rewardDebt); } } /** * Epoch */ function epoch() public view returns (uint256) { return _state.epoch.current; } function epochTime() public view returns (uint256) { Constants.EpochStrategy memory current = Constants.getCurrentEpochStrategy(); return epochTimeWithStrategy(current); } function epochTimeWithStrategy(Constants.EpochStrategy memory strategy) private view returns (uint256) { return blockTimestamp() .sub(strategy.start) .div(strategy.period) .add(strategy.offset); } // Overridable for testing function blockTimestamp() internal view returns (uint256) { return block.timestamp; } function outstandingCoupons(uint256 epoch) public view returns (uint256) { return _state.epochs[epoch].coupons.outstanding; } function redeemedCoupons(uint256 epoch) public view returns (uint256) { return _state.epochs[epoch].coupons.couponRedeemed; } function redeemableVSDs(uint256 epoch) public view returns (uint256) { return _state.epochs[epoch].coupons.vsdRedeemable; } function bootstrappingAt(uint256 epoch) public view returns (bool) { return epoch <= Constants.getBootstrappingPeriod(); } function totalDollarSupplyAt(uint256 epoch) public view returns (uint256) { return _state.epochs[epoch].totalDollarSupply; } /** * Governance */ function recordedVoteInfo(address account, uint256 candidate) public view returns (Candidate.VoteInfo memory) { return _state.candidates[candidate].votes[account]; } function startFor(uint256 candidate) public view returns (uint256) { return _state.candidates[candidate].start; } function periodFor(uint256 candidate) public view returns (uint256) { return _state.candidates[candidate].period; } function approveFor(uint256 candidate) public view returns (uint256) { return _state.candidates[candidate].approve; } function rejectFor(uint256 candidate) public view returns (uint256) { return _state.candidates[candidate].reject; } function votesFor(uint256 candidate) public view returns (uint256) { return approveFor(candidate).add(rejectFor(candidate)); } function isNominated(uint256 candidate) public view returns (bool) { return _state.candidates[candidate].start > 0; } function isInitialized(uint256 candidate) public view returns (bool) { return _state.candidates[candidate].initialized; } function implementation() public view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * Collateral */ function _getDollarReserve(address pool, uint256 bonded) internal view returns (uint256 reserve, uint256 totalReserve) { (uint256 reserve0, uint256 reserve1,) = IUniswapV2Pair(pool).getReserves(); if (IUniswapV2Pair(pool).token0() == address(dollar())) { totalReserve = reserve0; } else { require(IUniswapV2Pair(pool).token1() == address(dollar()), "the pool does not contain dollar"); totalReserve = reserve1; } if (bonded == 0) { return (0, totalReserve); } reserve = totalReserve.mul(bonded).div(IUniswapV2Pair(pool).totalSupply()); } function _getSellAndReturnAmount( uint256 price, uint256 targetPrice, uint256 reserve ) internal pure returns (uint256 sellAmount, uint256 returnAmount) { // price in resolution 1e18 sellAmount = 0; returnAmount = 0; uint256 rootPoT = Babylonian.sqrt(price.mul(1e36).div(targetPrice)); if (rootPoT > 1e18) { // res error sellAmount = (rootPoT - 1e18).mul(reserve).div(1e18); } uint256 rootPT = Babylonian.sqrt(price.mul(targetPrice)); if (price > rootPT) { // res error returnAmount = (price - rootPT).mul(reserve).div(1e18); } if (sellAmount > returnAmount) { // res error sellAmount = returnAmount; } } function _getBuyAmount(uint256 price, uint256 targetPrice, uint256 reserve) internal pure returns (uint256 shouldBuy) { shouldBuy = 0; uint256 root = Babylonian.sqrt(price.mul(1e36).div(targetPrice)); if (root < 1e18) { // res error shouldBuy = (1e18 - root).mul(reserve).div(1e18); } } function getCollateralRatio() internal view returns (uint256) { return _state.collateralRatio; } } // File: contracts/external/UniswapV2Library.sol pragma solidity >=0.5.0; library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/dao/Setters.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Setters is State, Getters { using SafeMath for uint256; using SafeERC20 for IERC20; event Claim(address indexed pool, address indexed account, uint256 value); /** * Global */ function incrementTotalDebt(uint256 amount) internal { _state.balance.debt = _state.balance.debt.add(amount); } function decrementTotalDebt(uint256 amount) internal { _state.balance.debt = _state.balance.debt.sub(amount); } function incrementTotalRedeemable(uint256 amount) internal { _state.balance.redeemable = _state.balance.redeemable.add(amount); } function decrementTotalRedeemable(uint256 amount) internal { _state.balance.redeemable = _state.balance.redeemable.sub(amount); } function decrementTotalClippable(uint256 amount) internal { _state.balance.clippable = _state.balance.clippable.sub(amount); } function incrementTotalClippable(uint256 amount) internal { _state.balance.clippable = _state.balance.clippable.add(amount); } /** * Account */ function incrementBalanceOfBonded(address pool, address account, uint256 amount) internal { _state.pools[pool].accounts[account].bonded = _state.pools[pool].accounts[account].bonded.add(amount); _state.pools[pool].bonded = _state.pools[pool].bonded.add(amount); } function decrementBalanceOfBonded(address pool, address account, uint256 amount) internal { _state.pools[pool].accounts[account].bonded = _state.pools[pool].accounts[account].bonded.sub(amount); _state.pools[pool].bonded = _state.pools[pool].bonded.sub(amount); } function incrementBalanceOfStaged(address pool, address account, uint256 amount) internal { _state.pools[pool].accounts[account].staged = _state.pools[pool].accounts[account].staged.add(amount); _state.pools[pool].staged = _state.pools[pool].staged.add(amount); } function decrementBalanceOfStaged(address pool, address account, uint256 amount) internal { _state.pools[pool].accounts[account].staged = _state.pools[pool].accounts[account].staged.sub(amount); _state.pools[pool].staged = _state.pools[pool].staged.sub(amount); } function incrementBalanceOfCoupons(address account, uint256 epoch, uint256 amount) internal { _state.accounts[account].coupons[epoch] = _state.accounts[account].coupons[epoch].add(amount); _state.epochs[epoch].coupons.outstanding = _state.epochs[epoch].coupons.outstanding.add(amount); _state.balance.coupons = _state.balance.coupons.add(amount); } function decrementBalanceOfCoupons(address account, uint256 epoch, uint256 amount) internal { _state.accounts[account].coupons[epoch] = _state.accounts[account].coupons[epoch].sub(amount); _state.epochs[epoch].coupons.outstanding = _state.epochs[epoch].coupons.outstanding.sub(amount); _state.balance.coupons = _state.balance.coupons.sub(amount); } function clipRedeemedCoupon(address account, uint256 epoch) internal returns (uint256 vsdRedeemable) { uint256 couponRedeemed = _state.accounts[account].coupons[epoch]; _state.accounts[account].coupons[epoch] = 0; // require(_state.epochs[epoch].coupons.outstanding == 0); vsdRedeemable = _state.epochs[epoch].coupons.vsdRedeemable.mul(couponRedeemed).div(_state.epochs[epoch].coupons.couponRedeemed); } function unfreeze(address pool, address account) internal { _state.pools[pool].accounts[account].fluidUntil = epoch().add(Constants.getDAOExitLockupEpochs()); } function updateAllowanceCoupons(address owner, address spender, uint256 amount) internal { _state.accounts[owner].couponAllowances[spender] = amount; } function decrementAllowanceCoupons(address owner, address spender, uint256 amount) internal { _state.accounts[owner].couponAllowances[spender] = _state.accounts[owner].couponAllowances[spender].sub(amount); } /** * Epoch */ function incrementEpoch() internal { _state.epoch.current = _state.epoch.current.add(1); } function snapshotDollarTotalSupply() internal { _state.epochs[epoch()].totalDollarSupply = dollar().totalSupply(); } function redeemOutstandingCoupons(uint256 epoch) internal returns (uint256 couponRedeemed, uint256 vsdRedeemable) { uint256 outstandingCouponsForEpoch = outstandingCoupons(epoch); if(outstandingCouponsForEpoch == 0) { return (0, 0); } _state.balance.coupons = _state.balance.coupons.sub(outstandingCouponsForEpoch); uint256 totalRedeemable = totalRedeemable(); vsdRedeemable = outstandingCouponsForEpoch; couponRedeemed = outstandingCouponsForEpoch; if (totalRedeemable < vsdRedeemable) { // Partial redemption vsdRedeemable = totalRedeemable; } _state.epochs[epoch].coupons.couponRedeemed = outstandingCouponsForEpoch; _state.epochs[epoch].coupons.vsdRedeemable = vsdRedeemable; _state.epochs[epoch].coupons.outstanding = 0; } /** * Governance */ function createCandidate(uint256 candidate, uint256 period) internal { _state.candidates[candidate].start = epoch(); _state.candidates[candidate].period = period; } function recordVoteInfo(address account, uint256 candidate, Candidate.VoteInfo memory voteInfo) internal { _state.candidates[candidate].votes[account] = voteInfo; } function incrementApproveFor(uint256 candidate, uint256 amount) internal { _state.candidates[candidate].approve = _state.candidates[candidate].approve.add(amount); } function decrementApproveFor(uint256 candidate, uint256 amount) internal { _state.candidates[candidate].approve = _state.candidates[candidate].approve.sub(amount); } function incrementRejectFor(uint256 candidate, uint256 amount) internal { _state.candidates[candidate].reject = _state.candidates[candidate].reject.add(amount); } function decrementRejectFor(uint256 candidate, uint256 amount) internal { _state.candidates[candidate].reject = _state.candidates[candidate].reject.sub(amount); } function placeLock(address account, uint256 candidate) internal { uint256 currentLock = _state.accounts[account].lockedUntil; uint256 newLock = startFor(candidate).add(periodFor(candidate)); if (newLock > currentLock) { _state.accounts[account].lockedUntil = newLock; } } function initialized(uint256 candidate) internal { _state.candidates[candidate].initialized = true; } /** * Pool */ function _addPool(address pool) internal { uint256 len = _state.poolList.length; for (uint256 i = 0; i < len; i++) { require(pool != _state.poolList[i], "Must not be added"); } _state.pools[pool].flags = 0x1; // enable flag _state.poolList.push(pool); } function preClaimDollar(address pool) internal { Storage.PoolInfo storage poolInfo = _state.pools[pool]; Account.PoolState storage user = poolInfo.accounts[msg.sender]; require((poolInfo.flags & 0x1) == 0x1, "pool is disabled"); if (user.bonded > 0) { uint256 pending = user.bonded.mul(poolInfo.accDollarPerLP).div(1e18).sub(user.rewardDebt); if (pending > 0) { // Safe transfer to avoid resolution error. uint256 balance = dollar().balanceOf(address(this)); if (pending > balance) { pending = balance; } dollar().transfer(msg.sender, pending); emit Claim(msg.sender, pool, pending); } } } function postClaimDollar(address pool) internal { Storage.PoolInfo storage poolInfo = _state.pools[pool]; Account.PoolState storage user = poolInfo.accounts[msg.sender]; user.rewardDebt = user.bonded.mul(poolInfo.accDollarPerLP).div(1e18); } function _addLiquidity(address pool, address token, address anotherToken, uint256 amount) internal returns (uint256) { address token0 = IUniswapV2Pair(pool).token0(); address token1 = IUniswapV2Pair(pool).token1(); require(token == token0 || token == token1, "token must in pool"); require(anotherToken == token0 || anotherToken == token1, "atoken must in pool"); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pool).getReserves(); (uint256 reserveToken, uint256 reserveAnother) = token == token0 ? (reserve0, reserve1) : (reserve1, reserve0); uint256 anotherAmount = UniswapV2Library.quote(amount, reserveToken, reserveAnother); // throw if reserve is zero IERC20(token).safeTransferFrom(msg.sender, pool, amount); IERC20(anotherToken).safeTransferFrom(msg.sender, pool, anotherAmount); return IUniswapV2Pair(pool).mint(address(this)); } function _sellAndDepositCollateral(uint256 totalSellAmount, uint256 allReserve) internal { if (totalSellAmount == 0 || allReserve == 0) { return; } dollar().mint(address(this), totalSellAmount); uint256 len = _state.poolList.length; uint256 actualSold = 0; // Sell to pools according to their reserves for (uint256 i = 0; i < len; i++) { address pool = _state.poolList[i]; address token0 = IUniswapV2Pair(pool).token0(); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pool).getReserves(); uint256 reserveA = token0 == address(dollar()) ? reserve0 : reserve1; uint256 reserveB = token0 == address(dollar()) ? reserve1 : reserve0; uint256 sellAmount = totalSellAmount .mul(reserveA) .div(allReserve); actualSold = actualSold.add(sellAmount); if (reserveA == 0 || sellAmount == 0) { // The pool is not ready yet or insufficient lp in pool. continue; } uint256 assetAmount = UniswapV2Library.getAmountOut( sellAmount, reserveA, reserveB ); dollar().transfer(pool, sellAmount); // Non-Reentrancy? IUniswapV2Pair(pool).swap( token0 == address(dollar()) ? 0 : assetAmount, token0 == address(dollar()) ? assetAmount : 0, address(this), new bytes(0) ); } // Make sure we don't sell extra assert(actualSold <= totalSellAmount); } /** * Collateral */ function _addCollateral(address asset) internal { uint256 len = _state.collateralAssetList.length; for (uint256 i = 0; i < len; i++) { require(asset != _state.collateralAssetList[i], "Must not be added"); } _state.collateralAssetList.push(asset); } } // File: contracts/external/Require.sol /* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; /** * @title Require * @author dYdX * * Stringifies parameters to pretty-print revert messages. Costs more gas than regular require() */ library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } // File: contracts/dao/Comptroller.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Comptroller is Setters { using SafeMath for uint256; bytes32 private constant FILE = "Comptroller"; function mintToAccount(address account, uint256 amount) internal { dollar().mint(account, amount); increaseDebt(amount); balanceCheck(); } function burnFromAccount(address account, uint256 amount) internal { burnFromAccountForDebt(account, amount, amount); } function burnFromAccountForDebt(address account, uint256 amount, uint256 debtAmount) internal { dollar().transferFrom(account, address(this), amount); dollar().burn(amount); decrementTotalDebt(debtAmount); balanceCheck(); } function clipToAccount(address account, uint256 amount) internal { dollar().transfer(account, amount); decrementTotalClippable(amount); balanceCheck(); } function redeemToClippable(uint256 amount) internal { decrementTotalRedeemable(amount); incrementTotalClippable(amount); balanceCheck(); } function setDebt(uint256 amount) internal returns (uint256) { _state.balance.debt = amount; uint256 lessDebt = resetDebt(Constants.getDebtRatioCap()); balanceCheck(); return lessDebt > amount ? 0 : amount.sub(lessDebt); } function increaseDebt(uint256 amount) internal returns (uint256) { incrementTotalDebt(amount); uint256 lessDebt = resetDebt(Constants.getDebtRatioCap()); balanceCheck(); return lessDebt > amount ? 0 : amount.sub(lessDebt); } function decreaseDebt(uint256 amount) internal { decrementTotalDebt(amount); balanceCheck(); } function _updateReserve() internal returns (uint256 allReserve) { uint256 totalAllocPoint = 0; uint256 len = _state.poolList.length; allReserve = 0; for (uint256 i = 0; i < len; i++) { address pool = _state.poolList[i]; Storage.PoolInfo storage poolInfo = _state.pools[pool]; uint256 poolReserve; (poolInfo.allocPoint, poolReserve) = _getDollarReserve(pool, _state.pools[pool].bonded); totalAllocPoint = totalAllocPoint.add(poolInfo.allocPoint); allReserve = allReserve.add(poolReserve); } _state.totalAllocPoint = totalAllocPoint; } function increaseSupply(uint256 newSupply) internal returns (uint256, uint256, uint256) { // 0. Pay out to Fund uint256 rewards = newSupply.mul(getSupplyIncreaseFundRatio()).div(10000); uint256 devReward = rewards.mul(Constants.getFundDevPct()).div(100); uint256 treasuryReward = rewards.sub(devReward); if (devReward != 0) { dollar().mint(Constants.getDevAddress(), devReward); } if (treasuryReward != 0) { dollar().mint(Constants.getTreasuryAddress(), treasuryReward); } newSupply = newSupply > rewards ? newSupply.sub(rewards) : 0; // 1. True up redeemable pool uint256 newRedeemable = 0; uint256 totalRedeemable = totalRedeemable(); uint256 totalCoupons = totalCoupons(); if (totalRedeemable < totalCoupons) { newRedeemable = totalCoupons.sub(totalRedeemable); newRedeemable = newRedeemable > newSupply ? newSupply : newRedeemable; mintToRedeemable(newRedeemable); newSupply = newSupply.sub(newRedeemable); } // 2. Payout to LPs if (!mintToLPs(newSupply)) { newSupply = 0; } balanceCheck(); return (newRedeemable, newSupply.add(rewards), newSupply); } function resetDebt(Decimal.D256 memory targetDebtRatio) internal returns (uint256) { uint256 targetDebt = targetDebtRatio.mul(dollar().totalSupply()).asUint256(); uint256 currentDebt = totalDebt(); if (currentDebt > targetDebt) { uint256 lessDebt = currentDebt.sub(targetDebt); decreaseDebt(lessDebt); return lessDebt; } return 0; } function balanceCheck() private { // Require.that( // dollar().balanceOf(address(this)) >= totalBonded().add(totalStaged()).add(totalRedeemable()).add(totalClippable()), // FILE, // "Inconsistent balances" // ); } function mintToLPs(uint256 amount) private returns (bool) { if (amount == 0) { return false; } if (_state.totalAllocPoint == 0) { return false; } dollar().mint(address(this), amount); uint256 len = _state.poolList.length; for (uint256 i = 0; i < len; i++) { address pool = _state.poolList[i]; Storage.PoolInfo storage poolInfo = _state.pools[pool]; if (poolInfo.bonded == 0) { continue; } uint256 poolAmount = amount.mul(poolInfo.allocPoint).div(_state.totalAllocPoint); poolInfo.accDollarPerLP = poolInfo.accDollarPerLP.add(poolAmount.mul(1e18).div(poolInfo.bonded)); } return true; } function mintToRedeemable(uint256 amount) private { dollar().mint(address(this), amount); incrementTotalRedeemable(amount); balanceCheck(); } /* for testing purpose */ function getSupplyIncreaseFundRatio() internal view returns (uint256) { return Constants.getSupplyIncreaseFundRatio(); } } // File: contracts/dao/Market.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Market is Comptroller, Curve { using SafeMath for uint256; bytes32 private constant FILE = "Market"; event CouponRedemption(uint256 indexed epoch, uint256 couponRedeemed, uint256 vsdRedeemable); event CouponPurchase(address indexed account, uint256 indexed epochExpire, uint256 dollarAmount, uint256 couponAmount); event CouponClip(address indexed account, uint256 indexed epoch, uint256 couponAmount); event CouponTransfer(address indexed from, address indexed to, uint256 indexed epoch, uint256 value); event CouponApproval(address indexed owner, address indexed spender, uint256 value); event CouponExtended(address indexed owner, uint256 indexed epoch, uint256 couponAmount, uint256 newCouponAmount, uint256 newExpiration); function step() internal { // Automatically redeem prior coupons redeemCouponsForEpoch(epoch()); } function redeemCouponsForEpoch(uint256 epoch) private { (uint256 couponRedeemed, uint256 vsdRedeemable) = redeemOutstandingCoupons(epoch); redeemToClippable(vsdRedeemable); emit CouponRedemption(epoch, couponRedeemed, vsdRedeemable); } function couponPremium(uint256 amount) public view returns (uint256) { return calculateCouponPremium(dollar().totalSupply(), totalDebt(), amount); } function purchaseCoupons(uint256 dollarAmount) external returns (uint256) { Require.that( dollarAmount > 0, FILE, "Must purchase non-zero amount" ); Require.that( totalDebt() >= dollarAmount, FILE, "Not enough debt" ); uint256 epoch = epoch(); uint256 couponAmount = dollarAmount.add(couponPremium(dollarAmount)); burnFromAccount(msg.sender, dollarAmount); incrementBalanceOfCoupons(msg.sender, epoch.add(Constants.getCouponExpiration()), couponAmount); emit CouponPurchase(msg.sender, epoch.add(Constants.getCouponExpiration()), dollarAmount, couponAmount); return couponAmount; } /* * @dev Extend the expiration of a coupon by VSDs. */ function extendCoupon(uint256 couponExpireEpoch, uint256 couponAmount, uint256 dollarAmount) external { Require.that( dollarAmount > 0, FILE, "Must purchase non-zero amount" ); uint256 epoch = epoch(); decrementBalanceOfCoupons(msg.sender, couponExpireEpoch, couponAmount); uint256 liveness = couponAmount.mul(couponExpireEpoch.sub(epoch)); uint256 debtAmount = totalDebt(); if (debtAmount > dollarAmount) { debtAmount = dollarAmount; } burnFromAccountForDebt(msg.sender, dollarAmount, debtAmount); liveness = liveness.add(dollarAmount.mul(Constants.getCouponExpiration())); uint256 newExpiration = liveness.div(couponAmount).add(epoch); Require.that( newExpiration > epoch, FILE, "Must new exp. > current epoch" ); incrementBalanceOfCoupons(msg.sender, newExpiration, couponAmount); emit CouponExtended(msg.sender, couponExpireEpoch, couponAmount, couponAmount, newExpiration); } function clipCoupons(uint256 couponExpireEpoch) external { Require.that( outstandingCoupons(couponExpireEpoch) == 0, FILE, "Coupon is not redeemed" ); uint256 vsdAmount = clipRedeemedCoupon(msg.sender, couponExpireEpoch); clipToAccount(msg.sender, vsdAmount); emit CouponClip(msg.sender, couponExpireEpoch, vsdAmount); } function approveCoupons(address spender, uint256 amount) external { Require.that( spender != address(0), FILE, "Coupon approve to 0x0" ); updateAllowanceCoupons(msg.sender, spender, amount); emit CouponApproval(msg.sender, spender, amount); } function transferCoupons(address sender, address recipient, uint256 epoch, uint256 amount) external { Require.that( sender != address(0), FILE, "Coupon transfer from 0x0" ); Require.that( recipient != address(0), FILE, "Coupon transfer to 0x0" ); decrementBalanceOfCoupons(sender, epoch, amount); incrementBalanceOfCoupons(recipient, epoch, amount); if (msg.sender != sender && allowanceCoupons(sender, msg.sender) != uint256(-1)) { decrementAllowanceCoupons(sender, msg.sender, amount); } emit CouponTransfer(sender, recipient, epoch, amount); } } // File: contracts/dao/Regulator.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Regulator is Comptroller { using SafeMath for uint256; using Decimal for Decimal.D256; event Incentivization(address indexed account, uint256 amount); event SupplyIncrease(uint256 indexed epoch, uint256 price, uint256 newSell, uint256 newRedeemable, uint256 lessDebt, uint256 newSupply, uint256 newReward); event SupplyDecrease(uint256 indexed epoch, uint256 price, uint256 newDebt); event SupplyNeutral(uint256 indexed epoch); function step() internal { Decimal.D256 memory price = oracleCapture(); uint256 allReserve = _updateReserve(); if (price.greaterThan(Decimal.D256({value: getSupplyIncreasePriceThreshold()}))) { incentivize(msg.sender, Constants.getExpansionAdvanceIncentive()); growSupply(price, allReserve); return; } incentivize(msg.sender, Constants.getAdvanceIncentive()); if (price.lessThan(Decimal.D256({value: getSupplyDecreasePriceThreshold()}))) { shrinkSupply(price, allReserve); return; } emit SupplyNeutral(epoch()); } function incentivize(address account, uint256 amount) private { mintToAccount(account, amount); emit Incentivization(account, amount); } function shrinkSupply(Decimal.D256 memory price, uint256 allReserve) private { uint256 newDebt = _getBuyAmount(price.value, getSupplyDecreasePriceTarget(), allReserve); uint256 cappedNewDebt = setDebt(newDebt); emit SupplyDecrease(epoch(), price.value, cappedNewDebt); return; } function growSupply(Decimal.D256 memory price, uint256 allReserve) private { uint256 lessDebt = resetDebt(Decimal.zero()); (uint256 sellAmount, uint256 returnAmount) = _getSellAndReturnAmount( price.value, getSupplyIncreasePriceTarget(), allReserve ); _sellAndDepositCollateral(sellAmount, allReserve); uint256 mintAmount = returnAmount.mul(10000).div(getCollateralRatio()); (uint256 newRedeemable, uint256 newSupply, uint256 newReward) = increaseSupply(mintAmount.sub(sellAmount)); emit SupplyIncrease(epoch(), price.value, sellAmount, newRedeemable, lessDebt, newSupply, newReward); } function oracleCapture() private returns (Decimal.D256 memory) { (Decimal.D256 memory price, bool valid) = oracle().capture(); if (!valid) { return Decimal.one(); } return price; } /* for testing purpose */ function getSupplyIncreasePriceThreshold() internal view returns (uint256) { return Constants.getSupplyIncreasePriceThreshold(); } function getSupplyIncreasePriceTarget() internal view returns (uint256) { return Constants.getSupplyIncreasePriceTarget(); } function getSupplyDecreasePriceThreshold() internal view returns (uint256) { return Constants.getSupplyDecreasePriceThreshold(); } function getSupplyDecreasePriceTarget() internal view returns (uint256) { return Constants.getSupplyDecreasePriceTarget(); } } // File: contracts/dao/Permission.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Permission is Setters { bytes32 private constant FILE = "Permission"; // Can modify account state modifier onlyFrozenOrFluid(address pool, address account) { Require.that( statusOf(pool, account) != Account.Status.Locked, FILE, "Not frozen or fluid" ); _; } // Can participate in balance-dependant activities modifier onlyFrozen(address pool, address account) { Require.that( statusOf(pool, account) == Account.Status.Frozen, FILE, "Not frozen" ); _; } modifier initializer() { Require.that( !isInitialized(uint256(implementation())), FILE, "Already initialized" ); initialized(uint256(implementation())); _; } } // File: contracts/dao/Bonding.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Bonding is Setters, Permission { using SafeMath for uint256; bytes32 private constant FILE = "Bonding"; event Deposit(address indexed pool, address indexed account, uint256 value); event Withdraw(address indexed pool, address indexed account, uint256 value); event Bond(address indexed pool, address indexed account, uint256 start, uint256 value); event Unbond(address indexed pool, address indexed account, uint256 start, uint256 value); function step() internal { Require.that( epochTime() > epoch(), FILE, "Still current epoch" ); snapshotDollarTotalSupply(); incrementEpoch(); } function addPool(address pool) external { Require.that( msg.sender == address(this), FILE, "Must from governance" ); _addPool(pool); } function claim(address pool) external { preClaimDollar(pool); postClaimDollar(pool); } function deposit(address pool, uint256 value) external { IERC20(pool).transferFrom(msg.sender, address(this), value); incrementBalanceOfStaged(pool, msg.sender, value); emit Deposit(pool, msg.sender, value); } function withdraw(address pool, uint256 value) external onlyFrozen(pool, msg.sender) { IERC20(pool).transfer(msg.sender, value); decrementBalanceOfStaged(pool, msg.sender, value); emit Withdraw(pool, msg.sender, value); } function bond(address pool, uint256 value) external { preClaimDollar(pool); unfreeze(pool, msg.sender); incrementBalanceOfBonded(pool, msg.sender, value); decrementBalanceOfStaged(pool, msg.sender, value); emit Bond(pool, msg.sender, epoch().add(1), value); postClaimDollar(pool); } function unbond(address pool, uint256 value) external onlyFrozenOrFluid(pool, msg.sender) { preClaimDollar(pool); unfreeze(pool, msg.sender); incrementBalanceOfStaged(pool, msg.sender, value); decrementBalanceOfBonded(pool, msg.sender, value); emit Unbond(pool, msg.sender, epoch().add(1), value); postClaimDollar(pool); } function provide(address pool, address token, address another, uint256 amount) external { preClaimDollar(pool); unfreeze(pool, msg.sender); uint256 bondedLP = _addLiquidity(pool, token, another, amount); incrementBalanceOfBonded(pool, msg.sender, bondedLP); emit Bond(pool, msg.sender, epoch().add(1), bondedLP); postClaimDollar(pool); } } // File: @openzeppelin/upgrades/contracts/utils/Address.sol pragma solidity ^0.5.0; /** * Utility library of inline functions on addresses * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version. */ library OpenZeppelinUpgradesAddress { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: contracts/dao/Upgradeable.sol /* Copyright 2018-2019 zOS Global Limited Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; /** * Based off of, and designed to interface with, openzeppelin/upgrades package */ contract Upgradeable is State { /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); function initialize() public; /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) internal { setImplementation(newImplementation); (bool success, bytes memory reason) = newImplementation.delegatecall(abi.encodeWithSignature("initialize()")); require(success, string(reason)); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function setImplementation(address newImplementation) private { require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } // File: contracts/dao/Govern.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Govern is Setters, Permission, Upgradeable { using SafeMath for uint256; using Decimal for Decimal.D256; bytes32 private constant FILE = "Govern"; event Proposal(uint256 indexed candidate, address indexed account, uint256 indexed start, uint256 period); event Vote(address indexed account, uint256 indexed candidate, Candidate.Vote vote, uint256 bondedVotes); event Commit(address indexed account, uint256 indexed candidate, bool upgrade); /* * We allow voting as long as the token is bonded. */ function vote(uint256 candidate, Candidate.Vote vote) external { Require.that( msg.sender == tx.origin, FILE, "Must be a user tx" ); if (!isNominated(candidate)) { Require.that( canPropose(msg.sender), FILE, "Not enough stake to propose" ); createCandidate(candidate, Constants.getGovernancePeriod()); emit Proposal(candidate, msg.sender, epoch(), Constants.getGovernancePeriod()); } Require.that( epoch() < startFor(candidate).add(periodFor(candidate)), FILE, "Ended" ); uint256 bondedVotes = balanceOfBondedDollar(msg.sender); Candidate.VoteInfo memory recordedVoteInfo = recordedVoteInfo(msg.sender, candidate); Candidate.VoteInfo memory newVoteInfo = Candidate.VoteInfo({vote: vote, bondedVotes: bondedVotes}); if (newVoteInfo.vote == recordedVoteInfo.vote && newVoteInfo.bondedVotes == recordedVoteInfo.bondedVotes) { return; } if (recordedVoteInfo.vote == Candidate.Vote.REJECT) { decrementRejectFor(candidate, recordedVoteInfo.bondedVotes); } if (recordedVoteInfo.vote == Candidate.Vote.APPROVE) { decrementApproveFor(candidate, recordedVoteInfo.bondedVotes); } if (vote == Candidate.Vote.REJECT) { incrementRejectFor(candidate, newVoteInfo.bondedVotes); } if (vote == Candidate.Vote.APPROVE) { incrementApproveFor(candidate, newVoteInfo.bondedVotes); } recordVoteInfo(msg.sender, candidate, newVoteInfo); placeLock(msg.sender, candidate); emit Vote(msg.sender, candidate, vote, bondedVotes); } function commit(uint256 candidate) external { Require.that( isNominated(candidate), FILE, "Not nominated" ); uint256 endsAfter = startFor(candidate).add(periodFor(candidate)).sub(1); Require.that( epoch() > endsAfter, FILE, "Not ended" ); Require.that( epoch() <= endsAfter.add(1).add(Constants.getGovernanceExpiration()), FILE, "Expired" ); Require.that( Decimal.ratio(votesFor(candidate), dollar().totalSupply()).greaterThan(Constants.getGovernanceQuorum()), FILE, "Must have quorom" ); Require.that( approveFor(candidate) > rejectFor(candidate), FILE, "Not approved" ); Require.that( msg.sender == getGovernor(), FILE, "Must from governor" ); upgradeTo(address(candidate)); emit Commit(msg.sender, candidate, true); } function emergencyCommit(uint256 candidate) external { Require.that( isNominated(candidate), FILE, "Not nominated" ); Require.that( Decimal.ratio(approveFor(candidate), dollar().totalSupply()).greaterThan(Constants.getGovernanceSuperMajority()), FILE, "Must have super majority" ); Require.that( approveFor(candidate) > rejectFor(candidate), FILE, "Not approved" ); Require.that( msg.sender == getGovernor(), FILE, "Must from governor" ); upgradeTo(address(candidate)); emit Commit(msg.sender, candidate, true); } function canPropose(address account) private view returns (bool) { Decimal.D256 memory stake = Decimal.ratio( balanceOfBondedDollar(account), dollar().totalSupply() ); return stake.greaterThan(Constants.getGovernanceProposalThreshold()); } function getGovernor() internal view returns (address) { return Constants.getGovernor(); } } // File: contracts/dao/ReentrancyGuard.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: contracts/dao/Collateral.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Collateral is Comptroller, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; bytes32 private constant FILE = "Collateral"; function redeem(uint256 value) external nonReentrant { uint256 actual = value; uint256 debt = totalDebt(); if (debt > value) { // if there is debt, redeem at no cost debt = value; } else { // redeem with cost actual = value.sub((10000 - Constants.getRedemptionRate()).mul(value.sub(debt)).div(10000)); uint256 fundReward = value.sub(actual); uint256 devReward = fundReward.mul(Constants.getFundDevPct()).div(100); uint256 treasuryReward = fundReward.sub(devReward); dollar().transferFrom(msg.sender, Constants.getDevAddress(), devReward); dollar().transferFrom(msg.sender, Constants.getTreasuryAddress(), treasuryReward); } uint256 len = _state.collateralAssetList.length; uint256 dollarTotalSupply = dollar().totalSupply(); for (uint256 i = 0; i < len; i++) { address addr = _state.collateralAssetList[i]; IERC20(addr).safeTransfer( msg.sender, actual.mul(IERC20(addr).balanceOf(address(this))).div(dollarTotalSupply) ); } burnFromAccountForDebt(msg.sender, actual, debt); } function addCollateral(address asset) external { Require.that( msg.sender == address(this), FILE, "Must from governance" ); _addCollateral(asset); } function _getMinterAddress() internal view returns (address) { return Constants.getMinterAddress(); } } // File: contracts/dao/Implementation.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Implementation is State, Bonding, Market, Regulator, Govern, Collateral { using SafeMath for uint256; event Advance(uint256 indexed epoch, uint256 block, uint256 timestamp); function initialize() initializer public { /* uint256 len = _state.poolList.length; for (uint256 i = 0; i < len; i++) { address pool = _state.poolList[i]; Storage.PoolInfo storage poolInfo = _state.pools[pool]; poolInfo.flags = 0x1; } */ } function advance() nonReentrant external { require (msg.sender == tx.origin, "Must from user"); Bonding.step(); Regulator.step(); Market.step(); emit Advance(epoch(), block.number, block.timestamp); } }
for testing purpose /
function getSupplyIncreasePriceThreshold() internal view returns (uint256) { return Constants.getSupplyIncreasePriceThreshold(); }
1,966,537
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "./openzeppelin/EnumerableSet.sol"; import "./IMaticulum.sol"; import "./ISchool.sol"; contract MaticulumSchool is ISchool, Ownable { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; struct School { string name; string town; string country; uint8 juryValidationThreshold; } IMaticulum private maticulum; address private trainingContract; /// Schools list School[] public schools; /// Fees when a school is registered /// @dev As Matic faucet deliver only 0.1 TMATIC / request, this is a low amount uint256 public schoolRegistrationFees = 0.1 ether; /// Number of Maticulum admin to approve a school registration, or a school admin request uint8 public schoolValidationThreshold = 2; /// List of (school, school administrator) mapping(uint256 => EnumerableSet.AddressSet) schoolAdministrators; mapping(address => EnumerableSet.UintSet) administratorSchools; /// List of (school, school administrator) waiting validation from superAdmin mapping(uint256 => EnumerableSet.AddressSet) schoolAdministratorsWaitingValidation; mapping(address => EnumerableSet.UintSet) administratorSchoolsWaitingValidation; mapping(uint256 => mapping(address => EnumerableSet.AddressSet)) adminValidations; /// List of trainings for a school mapping(uint256 => EnumerableSet.UintSet) schoolTrainings; event SchoolAdded(uint256 schoolId, string name, string town, string country, uint8 juryValidationThreshold, address addedBy); event SchoolUpdated(uint256 schoolId, string name, string town, string country, uint8 juryValidationThreshold, address updatedBy); event SchoolAdminAdded(uint256 schoolId, address admin, address updatedBy); event SchoolAdminValidated(uint256 schoolId, address admin, uint256 count, address updatedBy); event SchoolValidationThresholdUpdated(uint8 validationThreshold, address updatedBy); event SchoolRegistrationFeesUpdated(uint256 registrationFees, address updatedBy); modifier onlySuperAdmin() { require(maticulum.isSuperAdmin(msg.sender), "!SuperAdmin"); _; } modifier onlyRegistered() { require(maticulum.isRegistered(msg.sender), "!Registered"); _; } constructor(address _maticulum) { maticulum = IMaticulum(_maticulum); } function registerTrainingContract(address _trainingContract) external onlyOwner { trainingContract = _trainingContract; } /** * @notice Checks that a user is admin of a given school * @param _user user address * @param _schoolId id of the school * @return true if the user is admin of the school */ function isSchoolAdmin(uint256 _schoolId, address _user) external view override returns (bool) { return _isSchoolAdmin(_schoolId, _user); } /// @dev Duplicate of above function, needed as override function must be external... function _isSchoolAdmin(uint256 _schoolId, address _user) internal view returns (bool) { return schoolAdministrators[_schoolId].contains(_user); } /** * @notice Get the number of juries needed to validate a training registration * @dev This value is common for all the trainings in a school * @param _schoolId id of school * @return Number of juries */ function getJuryValidationThreshold(uint256 _schoolId) external view override returns (uint8) { return schools[_schoolId].juryValidationThreshold; } /** * @notice Add a new school * @dev 2 admins must be provided at creation * @param _name School name * @param _town School town * @param _country School country * @param _juryValidationThreshold number of juries to validate a training * @param _admin1 address of first school admin * @param _admin2 address of second school admin */ function addSchool(string memory _name, string memory _town, string memory _country, uint8 _juryValidationThreshold, address _admin1, address _admin2) external payable onlyRegistered { require(msg.value == schoolRegistrationFees, "MissingFees"); if (!maticulum.getFeesReceiver().send(msg.value)) { revert("Error sending fess"); } schools.push(School(_name, _town, _country, _juryValidationThreshold)); uint256 id = schools.length - 1; addSchoolAdministrator(id, _admin1); addSchoolAdministrator(id, _admin2); emit SchoolAdded(id, _name, _town, _country, _juryValidationThreshold, msg.sender); } /** * @notice Update a school * @param _name School name * @param _town School town * @param _country School country * @param _juryValidationThreshold number of juries to validate a training */ function updateSchool(uint256 _schoolId, string memory _name, string memory _town, string memory _country, uint8 _juryValidationThreshold) external { require(_isSchoolAdmin(_schoolId, msg.sender), "!SchoolAdmin"); School storage school = schools[_schoolId]; school.name = _name; school.town = _town; school.country = _country; school.juryValidationThreshold = _juryValidationThreshold; emit SchoolUpdated(_schoolId, _name, _town, _country, _juryValidationThreshold, msg.sender); } /** * @notice Add a school admin for a specified school * @param _schoolId id of school * @param _user user address */ function addSchoolAdministrator(uint256 _schoolId, address _user) public onlyRegistered { schoolAdministratorsWaitingValidation[_schoolId].add(_user); administratorSchoolsWaitingValidation[_user].add(_schoolId); emit SchoolAdminAdded(_schoolId, _user, msg.sender); } /** * @notice Validate an administrator (By a Maticulum admin). Require schoolValidationThreshold validations. * @param _schoolId id of school * @param _user user address */ function validateAdministrator(uint256 _schoolId, address _user) internal { require(!schoolAdministrators[_schoolId].contains(_user), "Already admin"); require(!adminValidations[_schoolId][_user].contains(msg.sender), "Already validated by this superadmin"); adminValidations[_schoolId][_user].add(msg.sender); uint256 count = adminValidations[_schoolId][_user].length(); if (count >= schoolValidationThreshold) { schoolAdministrators[_schoolId].add(_user); administratorSchools[_user].add(_schoolId); schoolAdministratorsWaitingValidation[_schoolId].remove(_user); administratorSchoolsWaitingValidation[_user].remove(_schoolId); } emit SchoolAdminValidated(_schoolId, _user, count, msg.sender); } /** * @notice Validate multiple administrators * @param _schoolId id of school * @param _users users addresses */ function validateAdministratorMultiple(uint256 _schoolId, address[] memory _users) external { require(maticulum.isSuperAdmin(msg.sender), "!SuperAdmin"); for (uint256 i = 0; i < _users.length; i++) { validateAdministrator(_schoolId, _users[i]); } } /** * @notice Update the number of Maticulum admins needed to validate a school admin * @param _validationThreshold validation admin number */ function updateSchoolValidationThreshold(uint8 _validationThreshold) external onlySuperAdmin { schoolValidationThreshold = _validationThreshold; emit SchoolValidationThresholdUpdated(_validationThreshold, msg.sender); } /** * @notice Update the school registration fees * @param _registrationFees fees (in wei) */ function updateSchoolRegistrationFees(uint256 _registrationFees) external onlySuperAdmin { schoolRegistrationFees = _registrationFees; emit SchoolRegistrationFeesUpdated(_registrationFees, msg.sender); } /** * @notice Get the number of schools * @return school count */ function getSchoolsCount() external view returns (uint256) { return schools.length; } /** * @notice Get the admins list for a given school * @param _schoolId id of school * @return addresses of admin */ function getSchoolAdministrators(uint256 _schoolId) external view returns (address[] memory) { return schoolAdministrators[_schoolId].values(); } /** * @notice Get the admins list waiting validation for a given school * @param _schoolId id of school * @return addresses of admin */ function getSchoolAdministratorsWaitingValidation(uint256 _schoolId) external view returns (address[] memory) { return schoolAdministratorsWaitingValidation[_schoolId].values(); } /** * @notice Get the schools for a given admin and index * @param _admin user address * @return schools id */ function getAdministratorSchools(address _admin) external view returns (uint256[] memory) { return administratorSchools[_admin].values(); } /** * @notice Get the status of an admin validation * @param _schoolId id of school * @param _admin admin address * @return validated true if the admin is validated * @return count nb of super admins who have validated this admin */ function getAdminValidationStatus(uint256 _schoolId, address _admin) external view returns (bool validated, uint256 count) { count = adminValidations[_schoolId][_admin].length(); validated = count >= schoolValidationThreshold; } /** * @notice Get the address who validates this admin, for the given school * @param _schoolId id of school * @param _admin admin address * @return the addresses of validators */ function getAdminValidators(uint256 _schoolId, address _admin) external view returns (address[] memory) { return adminValidations[_schoolId][_admin].values(); } /** * @notice Get trainings list for specified school * @param _schoolId id of school * @return address of jury */ function getSchoolTrainings(uint256 _schoolId) external view returns (uint256[] memory) { return schoolTrainings[_schoolId].values(); } /** * @notice link a training to a school * @dev this function is only accessible to Training smartcontract * @param _schoolId id of school * @param _trainingId id of training */ function linkTraining(uint256 _schoolId, uint256 _trainingId) external override { require(msg.sender == trainingContract, "!auth"); schoolTrainings[_schoolId].add(_trainingId); } }
Update a school _name School name _town School town _country School country _juryValidationThreshold number of juries to validate a training/
function updateSchool(uint256 _schoolId, string memory _name, string memory _town, string memory _country, uint8 _juryValidationThreshold) external { require(_isSchoolAdmin(_schoolId, msg.sender), "!SchoolAdmin"); School storage school = schools[_schoolId]; school.name = _name; school.town = _town; school.country = _country; school.juryValidationThreshold = _juryValidationThreshold; emit SchoolUpdated(_schoolId, _name, _town, _country, _juryValidationThreshold, msg.sender); }
12,654,479
./full_match/1/0x66d97FD4DefEcD79904B3D3587dC4f8ed66Cf4Ab/sources/src/erc721/LSSVMPairERC721.sol
Takes NFTs from the caller and sends them into the pair's asset recipient This is used by the LSSVMPair's swapNFTForToken function. _nft The NFT collection to take from nftIds The specific NFT IDs to take isRouter True if calling from LSSVMRouter, false otherwise. Not used for ETH pairs. routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for ETH pairs./ Verify if router is allowed Call router to pull NFTs If more than 1 NFT is being transfered, and there is no property checker, we can do a balance check instead of an ownership check, as pools are indifferent between NFTs from the same collection Otherwise we need to pull each asset 1 at a time and verify ownership Pull NFTs directly from sender
function _takeNFTsFromSender( IERC721 _nft, uint256[] calldata nftIds, ILSSVMPairFactoryLike _factory, bool isRouter, address routerCaller ) internal virtual { { address _assetRecipient = getAssetRecipient(); uint256 numNFTs = nftIds.length; if (isRouter) { LSSVMRouter router = LSSVMRouter(payable(msg.sender)); (bool routerAllowed,) = _factory.routerStatus(router); if (!routerAllowed) revert LSSVMPair__NotRouter(); if ((numNFTs > 1) && (propertyChecker() == address(0))) { uint256 beforeBalance = _nft.balanceOf(_assetRecipient); for (uint256 i; i < numNFTs;) { router.pairTransferNFTFrom(_nft, routerCaller, _assetRecipient, nftIds[i]); unchecked { ++i; } } if (_nft.balanceOf(_assetRecipient) - beforeBalance != numNFTs) { revert LSSVMPair__NftNotTransferred(); } } else { for (uint256 i; i < numNFTs;) { router.pairTransferNFTFrom(_nft, routerCaller, _assetRecipient, nftIds[i]); if (_nft.ownerOf(nftIds[i]) != _assetRecipient) revert LSSVMPair__NftNotTransferred(); unchecked { ++i; } } } for (uint256 i; i < numNFTs;) { _nft.transferFrom(msg.sender, _assetRecipient, nftIds[i]); unchecked { ++i; } } } } }
8,298,094
./full_match/5/0xC3232001206D040bCbde74aa980258eF9294b0Dd/sources/contracts/Flashloan.sol
? call to request a flashloan from the pool
function requestFlashloan(address _token, uint256 _amount) public { address receiverAddress = address(this); address asset = _token; uint256 amount = _amount; bytes memory params = ""; uint16 referralCode = 0; POOL.flashLoanSimple( receiverAddress, asset, amount, params, referralCode ); }
1,931,688
./partial_match/1/0x1C2243aef55a316CaA0B6a1715B607B898987483/sources/NUXAsset.sol
Passes execution into virtual function. Can only be called by assigned asset proxy. return success. function is final, and must not be overridden./
function _performTransferFromToICAPWithReference( address _from, bytes32 _icap, uint _value, string memory _reference, address _sender) public onlyProxy() returns(bool) { return _transferFromToICAPWithReference( _from, _icap, _value, _reference, _sender); }
2,625,587
./partial_match/1/0x10d2740FFb6c38f14221dF8346d07253cEf8902d/sources/StrategySushiEthUsdtLp.sol
interface for Sushiswap MasterChef contract
interface ISushiChef { function BONUS_MULTIPLIER() external view returns (uint256); function add( uint256 _allocPoint, address _lpToken, bool _withUpdate ) external; function bonusEndBlock() external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; function dev(address _devaddr) external; function devFundDivRate() external view returns (uint256); function devaddr() external view returns (address); function emergencyWithdraw(uint256 _pid) external; function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); function massUpdatePools() external; function owner() external view returns (address); function pendingSushi(uint256 _pid, address _user) external view returns (uint256); function sushi() external view returns (address); function sushiPerBlock() external view returns (uint256); function poolInfo(uint256) external view returns ( address lpToken, uint256 allocPoint, uint256 lastRewardBlock, uint256 accsushiPerShare ); function poolLength() external view returns (uint256); function renounceOwnership() external; function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; function setBonusEndBlock(uint256 _bonusEndBlock) external; function setDevFundDivRate(uint256 _devFundDivRate) external; function setsushiPerBlock(uint256 _sushiPerBlock) external; function startBlock() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function transferOwnership(address newOwner) external; function updatePool(uint256 _pid) external; function userInfo(uint256, address) external view returns (uint256 amount, uint256 rewardDebt); function withdraw(uint256 _pid, uint256 _amount) external; }
4,311,631
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./lib/ReEncryptionValidator.sol"; import "./lib/SignatureVerifier.sol"; import "./StakingEscrow.sol"; import "./proxy/Upgradeable.sol"; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/math/Math.sol"; /** * @title Adjudicator * @notice Supervises stakers' behavior and punishes when something's wrong. * @dev |v2.1.2| */ contract Adjudicator is Upgradeable { using SafeMath for uint256; using UmbralDeserializer for bytes; event CFragEvaluated( bytes32 indexed evaluationHash, address indexed investigator, bool correctness ); event IncorrectCFragVerdict( bytes32 indexed evaluationHash, address indexed worker, address indexed staker ); // used only for upgrading bytes32 constant RESERVED_CAPSULE_AND_CFRAG_BYTES = bytes32(0); address constant RESERVED_ADDRESS = address(0); StakingEscrow public immutable escrow; SignatureVerifier.HashAlgorithm public immutable hashAlgorithm; uint256 public immutable basePenalty; uint256 public immutable penaltyHistoryCoefficient; uint256 public immutable percentagePenaltyCoefficient; uint256 public immutable rewardCoefficient; mapping (address => uint256) public penaltyHistory; mapping (bytes32 => bool) public evaluatedCFrags; /** * @param _escrow Escrow contract * @param _hashAlgorithm Hashing algorithm * @param _basePenalty Base for the penalty calculation * @param _penaltyHistoryCoefficient Coefficient for calculating the penalty depending on the history * @param _percentagePenaltyCoefficient Coefficient for calculating the percentage penalty * @param _rewardCoefficient Coefficient for calculating the reward */ constructor( StakingEscrow _escrow, SignatureVerifier.HashAlgorithm _hashAlgorithm, uint256 _basePenalty, uint256 _penaltyHistoryCoefficient, uint256 _percentagePenaltyCoefficient, uint256 _rewardCoefficient ) { // Sanity checks. require(_escrow.secondsPerPeriod() > 0 && // This contract has an escrow, and it's not the null address. // The reward and penalty coefficients are set. _percentagePenaltyCoefficient != 0 && _rewardCoefficient != 0); escrow = _escrow; hashAlgorithm = _hashAlgorithm; basePenalty = _basePenalty; percentagePenaltyCoefficient = _percentagePenaltyCoefficient; penaltyHistoryCoefficient = _penaltyHistoryCoefficient; rewardCoefficient = _rewardCoefficient; } /** * @notice Submit proof that a worker created wrong CFrag * @param _capsuleBytes Serialized capsule * @param _cFragBytes Serialized CFrag * @param _cFragSignature Signature of CFrag by worker * @param _taskSignature Signature of task specification by Bob * @param _requesterPublicKey Bob's signing public key, also known as "stamp" * @param _workerPublicKey Worker's signing public key, also known as "stamp" * @param _workerIdentityEvidence Signature of worker's public key by worker's eth-key * @param _preComputedData Additional pre-computed data for CFrag correctness verification */ function evaluateCFrag( bytes memory _capsuleBytes, bytes memory _cFragBytes, bytes memory _cFragSignature, bytes memory _taskSignature, bytes memory _requesterPublicKey, bytes memory _workerPublicKey, bytes memory _workerIdentityEvidence, bytes memory _preComputedData ) public { // 1. Check that CFrag is not evaluated yet bytes32 evaluationHash = SignatureVerifier.hash( abi.encodePacked(_capsuleBytes, _cFragBytes), hashAlgorithm); require(!evaluatedCFrags[evaluationHash], "This CFrag has already been evaluated."); evaluatedCFrags[evaluationHash] = true; // 2. Verify correctness of re-encryption bool cFragIsCorrect = ReEncryptionValidator.validateCFrag(_capsuleBytes, _cFragBytes, _preComputedData); emit CFragEvaluated(evaluationHash, msg.sender, cFragIsCorrect); // 3. Verify associated public keys and signatures require(ReEncryptionValidator.checkSerializedCoordinates(_workerPublicKey), "Staker's public key is invalid"); require(ReEncryptionValidator.checkSerializedCoordinates(_requesterPublicKey), "Requester's public key is invalid"); UmbralDeserializer.PreComputedData memory precomp = _preComputedData.toPreComputedData(); // Verify worker's signature of CFrag require(SignatureVerifier.verify( _cFragBytes, abi.encodePacked(_cFragSignature, precomp.lostBytes[1]), _workerPublicKey, hashAlgorithm), "CFrag signature is invalid" ); // Verify worker's signature of taskSignature and that it corresponds to cfrag.proof.metadata UmbralDeserializer.CapsuleFrag memory cFrag = _cFragBytes.toCapsuleFrag(); require(SignatureVerifier.verify( _taskSignature, abi.encodePacked(cFrag.proof.metadata, precomp.lostBytes[2]), _workerPublicKey, hashAlgorithm), "Task signature is invalid" ); // Verify that _taskSignature is bob's signature of the task specification. // A task specification is: capsule + ursula pubkey + alice address + blockhash bytes32 stampXCoord; assembly { stampXCoord := mload(add(_workerPublicKey, 32)) } bytes memory stamp = abi.encodePacked(precomp.lostBytes[4], stampXCoord); require(SignatureVerifier.verify( abi.encodePacked(_capsuleBytes, stamp, _workerIdentityEvidence, precomp.alicesKeyAsAddress, bytes32(0)), abi.encodePacked(_taskSignature, precomp.lostBytes[3]), _requesterPublicKey, hashAlgorithm), "Specification signature is invalid" ); // 4. Extract worker address from stamp signature. address worker = SignatureVerifier.recover( SignatureVerifier.hashEIP191(stamp, byte(0x45)), // Currently, we use version E (0x45) of EIP191 signatures _workerIdentityEvidence); address staker = escrow.stakerFromWorker(worker); require(staker != address(0), "Worker must be related to a staker"); // 5. Check that staker can be slashed uint256 stakerValue = escrow.getAllTokens(staker); require(stakerValue > 0, "Staker has no tokens"); // 6. If CFrag was incorrect, slash staker if (!cFragIsCorrect) { (uint256 penalty, uint256 reward) = calculatePenaltyAndReward(staker, stakerValue); escrow.slashStaker(staker, penalty, msg.sender, reward); emit IncorrectCFragVerdict(evaluationHash, worker, staker); } } /** * @notice Calculate penalty to the staker and reward to the investigator * @param _staker Staker's address * @param _stakerValue Amount of tokens that belong to the staker */ function calculatePenaltyAndReward(address _staker, uint256 _stakerValue) internal returns (uint256 penalty, uint256 reward) { penalty = basePenalty.add(penaltyHistoryCoefficient.mul(penaltyHistory[_staker])); penalty = Math.min(penalty, _stakerValue.div(percentagePenaltyCoefficient)); reward = penalty.div(rewardCoefficient); // TODO add maximum condition or other overflow protection or other penalty condition (#305?) penaltyHistory[_staker] = penaltyHistory[_staker].add(1); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); bytes32 evaluationCFragHash = SignatureVerifier.hash( abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256); require(delegateGet(_testTarget, this.evaluatedCFrags.selector, evaluationCFragHash) == (evaluatedCFrags[evaluationCFragHash] ? 1 : 0)); require(delegateGet(_testTarget, this.penaltyHistory.selector, bytes32(bytes20(RESERVED_ADDRESS))) == penaltyHistory[RESERVED_ADDRESS]); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // preparation for the verifyState method bytes32 evaluationCFragHash = SignatureVerifier.hash( abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256); evaluatedCFrags[evaluationCFragHash] = true; penaltyHistory[RESERVED_ADDRESS] = 123; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./UmbralDeserializer.sol"; import "./SignatureVerifier.sol"; /** * @notice Validates re-encryption correctness. */ library ReEncryptionValidator { using UmbralDeserializer for bytes; //------------------------------// // Umbral-specific constants // //------------------------------// // See parameter `u` of `UmbralParameters` class in pyUmbral // https://github.com/nucypher/pyUmbral/blob/master/umbral/params.py uint8 public constant UMBRAL_PARAMETER_U_SIGN = 0x02; uint256 public constant UMBRAL_PARAMETER_U_XCOORD = 0x03c98795773ff1c241fc0b1cced85e80f8366581dda5c9452175ebd41385fa1f; uint256 public constant UMBRAL_PARAMETER_U_YCOORD = 0x7880ed56962d7c0ae44d6f14bb53b5fe64b31ea44a41d0316f3a598778f0f936; //------------------------------// // SECP256K1-specific constants // //------------------------------// // Base field order uint256 constant FIELD_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; // -2 mod FIELD_ORDER uint256 constant MINUS_2 = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2d; // (-1/2) mod FIELD_ORDER uint256 constant MINUS_ONE_HALF = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff7ffffe17; // /** * @notice Check correctness of re-encryption * @param _capsuleBytes Capsule * @param _cFragBytes Capsule frag * @param _precomputedBytes Additional precomputed data */ function validateCFrag( bytes memory _capsuleBytes, bytes memory _cFragBytes, bytes memory _precomputedBytes ) internal pure returns (bool) { UmbralDeserializer.Capsule memory _capsule = _capsuleBytes.toCapsule(); UmbralDeserializer.CapsuleFrag memory _cFrag = _cFragBytes.toCapsuleFrag(); UmbralDeserializer.PreComputedData memory _precomputed = _precomputedBytes.toPreComputedData(); // Extract Alice's address and check that it corresponds to the one provided address alicesAddress = SignatureVerifier.recover( _precomputed.hashedKFragValidityMessage, abi.encodePacked(_cFrag.proof.kFragSignature, _precomputed.lostBytes[0]) ); require(alicesAddress == _precomputed.alicesKeyAsAddress, "Bad KFrag signature"); // Compute proof's challenge scalar h, used in all ZKP verification equations uint256 h = computeProofChallengeScalar(_capsule, _cFrag); ////// // Verifying 1st equation: z*E == h*E_1 + E_2 ////// // Input validation: E require(checkCompressedPoint( _capsule.pointE.sign, _capsule.pointE.xCoord, _precomputed.pointEyCoord), "Precomputed Y coordinate of E doesn't correspond to compressed E point" ); // Input validation: z*E require(isOnCurve(_precomputed.pointEZxCoord, _precomputed.pointEZyCoord), "Point zE is not a valid EC point" ); require(ecmulVerify( _capsule.pointE.xCoord, // E_x _precomputed.pointEyCoord, // E_y _cFrag.proof.bnSig, // z _precomputed.pointEZxCoord, // zE_x _precomputed.pointEZyCoord), // zE_y "Precomputed z*E value is incorrect" ); // Input validation: E1 require(checkCompressedPoint( _cFrag.pointE1.sign, // E1_sign _cFrag.pointE1.xCoord, // E1_x _precomputed.pointE1yCoord), // E1_y "Precomputed Y coordinate of E1 doesn't correspond to compressed E1 point" ); // Input validation: h*E1 require(isOnCurve(_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord), "Point h*E1 is not a valid EC point" ); require(ecmulVerify( _cFrag.pointE1.xCoord, // E1_x _precomputed.pointE1yCoord, // E1_y h, _precomputed.pointE1HxCoord, // hE1_x _precomputed.pointE1HyCoord), // hE1_y "Precomputed h*E1 value is incorrect" ); // Input validation: E2 require(checkCompressedPoint( _cFrag.proof.pointE2.sign, // E2_sign _cFrag.proof.pointE2.xCoord, // E2_x _precomputed.pointE2yCoord), // E2_y "Precomputed Y coordinate of E2 doesn't correspond to compressed E2 point" ); bool equation_holds = eqAffineJacobian( [_precomputed.pointEZxCoord, _precomputed.pointEZyCoord], addAffineJacobian( [_cFrag.proof.pointE2.xCoord, _precomputed.pointE2yCoord], [_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord] ) ); if (!equation_holds){ return false; } ////// // Verifying 2nd equation: z*V == h*V_1 + V_2 ////// // Input validation: V require(checkCompressedPoint( _capsule.pointV.sign, _capsule.pointV.xCoord, _precomputed.pointVyCoord), "Precomputed Y coordinate of V doesn't correspond to compressed V point" ); // Input validation: z*V require(isOnCurve(_precomputed.pointVZxCoord, _precomputed.pointVZyCoord), "Point zV is not a valid EC point" ); require(ecmulVerify( _capsule.pointV.xCoord, // V_x _precomputed.pointVyCoord, // V_y _cFrag.proof.bnSig, // z _precomputed.pointVZxCoord, // zV_x _precomputed.pointVZyCoord), // zV_y "Precomputed z*V value is incorrect" ); // Input validation: V1 require(checkCompressedPoint( _cFrag.pointV1.sign, // V1_sign _cFrag.pointV1.xCoord, // V1_x _precomputed.pointV1yCoord), // V1_y "Precomputed Y coordinate of V1 doesn't correspond to compressed V1 point" ); // Input validation: h*V1 require(isOnCurve(_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord), "Point h*V1 is not a valid EC point" ); require(ecmulVerify( _cFrag.pointV1.xCoord, // V1_x _precomputed.pointV1yCoord, // V1_y h, _precomputed.pointV1HxCoord, // h*V1_x _precomputed.pointV1HyCoord), // h*V1_y "Precomputed h*V1 value is incorrect" ); // Input validation: V2 require(checkCompressedPoint( _cFrag.proof.pointV2.sign, // V2_sign _cFrag.proof.pointV2.xCoord, // V2_x _precomputed.pointV2yCoord), // V2_y "Precomputed Y coordinate of V2 doesn't correspond to compressed V2 point" ); equation_holds = eqAffineJacobian( [_precomputed.pointVZxCoord, _precomputed.pointVZyCoord], addAffineJacobian( [_cFrag.proof.pointV2.xCoord, _precomputed.pointV2yCoord], [_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord] ) ); if (!equation_holds){ return false; } ////// // Verifying 3rd equation: z*U == h*U_1 + U_2 ////// // We don't have to validate U since it's fixed and hard-coded // Input validation: z*U require(isOnCurve(_precomputed.pointUZxCoord, _precomputed.pointUZyCoord), "Point z*U is not a valid EC point" ); require(ecmulVerify( UMBRAL_PARAMETER_U_XCOORD, // U_x UMBRAL_PARAMETER_U_YCOORD, // U_y _cFrag.proof.bnSig, // z _precomputed.pointUZxCoord, // zU_x _precomputed.pointUZyCoord), // zU_y "Precomputed z*U value is incorrect" ); // Input validation: U1 (a.k.a. KFragCommitment) require(checkCompressedPoint( _cFrag.proof.pointKFragCommitment.sign, // U1_sign _cFrag.proof.pointKFragCommitment.xCoord, // U1_x _precomputed.pointU1yCoord), // U1_y "Precomputed Y coordinate of U1 doesn't correspond to compressed U1 point" ); // Input validation: h*U1 require(isOnCurve(_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord), "Point h*U1 is not a valid EC point" ); require(ecmulVerify( _cFrag.proof.pointKFragCommitment.xCoord, // U1_x _precomputed.pointU1yCoord, // U1_y h, _precomputed.pointU1HxCoord, // h*V1_x _precomputed.pointU1HyCoord), // h*V1_y "Precomputed h*V1 value is incorrect" ); // Input validation: U2 (a.k.a. KFragPok ("proof of knowledge")) require(checkCompressedPoint( _cFrag.proof.pointKFragPok.sign, // U2_sign _cFrag.proof.pointKFragPok.xCoord, // U2_x _precomputed.pointU2yCoord), // U2_y "Precomputed Y coordinate of U2 doesn't correspond to compressed U2 point" ); equation_holds = eqAffineJacobian( [_precomputed.pointUZxCoord, _precomputed.pointUZyCoord], addAffineJacobian( [_cFrag.proof.pointKFragPok.xCoord, _precomputed.pointU2yCoord], [_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord] ) ); return equation_holds; } function computeProofChallengeScalar( UmbralDeserializer.Capsule memory _capsule, UmbralDeserializer.CapsuleFrag memory _cFrag ) internal pure returns (uint256) { // Compute h = hash_to_bignum(e, e1, e2, v, v1, v2, u, u1, u2, metadata) bytes memory hashInput = abi.encodePacked( // Point E _capsule.pointE.sign, _capsule.pointE.xCoord, // Point E1 _cFrag.pointE1.sign, _cFrag.pointE1.xCoord, // Point E2 _cFrag.proof.pointE2.sign, _cFrag.proof.pointE2.xCoord ); hashInput = abi.encodePacked( hashInput, // Point V _capsule.pointV.sign, _capsule.pointV.xCoord, // Point V1 _cFrag.pointV1.sign, _cFrag.pointV1.xCoord, // Point V2 _cFrag.proof.pointV2.sign, _cFrag.proof.pointV2.xCoord ); hashInput = abi.encodePacked( hashInput, // Point U bytes1(UMBRAL_PARAMETER_U_SIGN), bytes32(UMBRAL_PARAMETER_U_XCOORD), // Point U1 _cFrag.proof.pointKFragCommitment.sign, _cFrag.proof.pointKFragCommitment.xCoord, // Point U2 _cFrag.proof.pointKFragPok.sign, _cFrag.proof.pointKFragPok.xCoord, // Re-encryption metadata _cFrag.proof.metadata ); uint256 h = extendedKeccakToBN(hashInput); return h; } function extendedKeccakToBN (bytes memory _data) internal pure returns (uint256) { bytes32 upper; bytes32 lower; // Umbral prepends to the data a customization string of 64-bytes. // In the case of hash_to_curvebn is 'hash_to_curvebn', padded with zeroes. bytes memory input = abi.encodePacked(bytes32("hash_to_curvebn"), bytes32(0x00), _data); (upper, lower) = (keccak256(abi.encodePacked(uint8(0x00), input)), keccak256(abi.encodePacked(uint8(0x01), input))); // Let n be the order of secp256k1's group (n = 2^256 - 0x1000003D1) // n_minus_1 = n - 1 // delta = 2^256 mod n_minus_1 uint256 delta = 0x14551231950b75fc4402da1732fc9bec0; uint256 n_minus_1 = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140; uint256 upper_half = mulmod(uint256(upper), delta, n_minus_1); return 1 + addmod(upper_half, uint256(lower), n_minus_1); } /// @notice Tests if a compressed point is valid, wrt to its corresponding Y coordinate /// @param _pointSign The sign byte from the compressed notation: 0x02 if the Y coord is even; 0x03 otherwise /// @param _pointX The X coordinate of an EC point in affine representation /// @param _pointY The Y coordinate of an EC point in affine representation /// @return true iff _pointSign and _pointX are the compressed representation of (_pointX, _pointY) function checkCompressedPoint( uint8 _pointSign, uint256 _pointX, uint256 _pointY ) internal pure returns(bool) { bool correct_sign = _pointY % 2 == _pointSign - 2; return correct_sign && isOnCurve(_pointX, _pointY); } /// @notice Tests if the given serialized coordinates represent a valid EC point /// @param _coords The concatenation of serialized X and Y coordinates /// @return true iff coordinates X and Y are a valid point function checkSerializedCoordinates(bytes memory _coords) internal pure returns(bool) { require(_coords.length == 64, "Serialized coordinates should be 64 B"); uint256 coordX; uint256 coordY; assembly { coordX := mload(add(_coords, 32)) coordY := mload(add(_coords, 64)) } return isOnCurve(coordX, coordY); } /// @notice Tests if a point is on the secp256k1 curve /// @param Px The X coordinate of an EC point in affine representation /// @param Py The Y coordinate of an EC point in affine representation /// @return true if (Px, Py) is a valid secp256k1 point; false otherwise function isOnCurve(uint256 Px, uint256 Py) internal pure returns (bool) { uint256 p = FIELD_ORDER; if (Px >= p || Py >= p){ return false; } uint256 y2 = mulmod(Py, Py, p); uint256 x3_plus_7 = addmod(mulmod(mulmod(Px, Px, p), Px, p), 7, p); return y2 == x3_plus_7; } // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/4 function ecmulVerify( uint256 x1, uint256 y1, uint256 scalar, uint256 qx, uint256 qy ) internal pure returns(bool) { uint256 curve_order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; address signer = ecrecover(0, uint8(27 + (y1 % 2)), bytes32(x1), bytes32(mulmod(scalar, x1, curve_order))); address xyAddress = address(uint256(keccak256(abi.encodePacked(qx, qy))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return xyAddress == signer; } /// @notice Equality test of two points, in affine and Jacobian coordinates respectively /// @param P An EC point in affine coordinates /// @param Q An EC point in Jacobian coordinates /// @return true if P and Q represent the same point in affine coordinates; false otherwise function eqAffineJacobian( uint256[2] memory P, uint256[3] memory Q ) internal pure returns(bool){ uint256 Qz = Q[2]; if(Qz == 0){ return false; // Q is zero but P isn't. } uint256 p = FIELD_ORDER; uint256 Q_z_squared = mulmod(Qz, Qz, p); return mulmod(P[0], Q_z_squared, p) == Q[0] && mulmod(P[1], mulmod(Q_z_squared, Qz, p), p) == Q[1]; } /// @notice Adds two points in affine coordinates, with the result in Jacobian /// @dev Based on the addition formulas from http://www.hyperelliptic.org/EFD/g1p/auto-code/shortw/jacobian-0/addition/add-2001-b.op3 /// @param P An EC point in affine coordinates /// @param Q An EC point in affine coordinates /// @return R An EC point in Jacobian coordinates with the sum, represented by an array of 3 uint256 function addAffineJacobian( uint[2] memory P, uint[2] memory Q ) internal pure returns (uint[3] memory R) { uint256 p = FIELD_ORDER; uint256 a = P[0]; uint256 c = P[1]; uint256 t0 = Q[0]; uint256 t1 = Q[1]; if ((a == t0) && (c == t1)){ return doubleJacobian([a, c, 1]); } uint256 d = addmod(t1, p-c, p); // d = t1 - c uint256 b = addmod(t0, p-a, p); // b = t0 - a uint256 e = mulmod(b, b, p); // e = b^2 uint256 f = mulmod(e, b, p); // f = b^3 uint256 g = mulmod(a, e, p); R[0] = addmod(mulmod(d, d, p), p-addmod(mulmod(2, g, p), f, p), p); R[1] = addmod(mulmod(d, addmod(g, p-R[0], p), p), p-mulmod(c, f, p), p); R[2] = b; } /// @notice Point doubling in Jacobian coordinates /// @param P An EC point in Jacobian coordinates. /// @return Q An EC point in Jacobian coordinates function doubleJacobian(uint[3] memory P) internal pure returns (uint[3] memory Q) { uint256 z = P[2]; if (z == 0) return Q; uint256 p = FIELD_ORDER; uint256 x = P[0]; uint256 _2y = mulmod(2, P[1], p); uint256 _4yy = mulmod(_2y, _2y, p); uint256 s = mulmod(_4yy, x, p); uint256 m = mulmod(3, mulmod(x, x, p), p); uint256 t = addmod(mulmod(m, m, p), mulmod(MINUS_2, s, p),p); Q[0] = t; Q[1] = addmod(mulmod(m, addmod(s, p - t, p), p), mulmod(MINUS_ONE_HALF, mulmod(_4yy, _4yy, p), p), p); Q[2] = mulmod(_2y, z, p); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @notice Deserialization library for Umbral objects */ library UmbralDeserializer { struct Point { uint8 sign; uint256 xCoord; } struct Capsule { Point pointE; Point pointV; uint256 bnSig; } struct CorrectnessProof { Point pointE2; Point pointV2; Point pointKFragCommitment; Point pointKFragPok; uint256 bnSig; bytes kFragSignature; // 64 bytes bytes metadata; // any length } struct CapsuleFrag { Point pointE1; Point pointV1; bytes32 kFragId; Point pointPrecursor; CorrectnessProof proof; } struct PreComputedData { uint256 pointEyCoord; uint256 pointEZxCoord; uint256 pointEZyCoord; uint256 pointE1yCoord; uint256 pointE1HxCoord; uint256 pointE1HyCoord; uint256 pointE2yCoord; uint256 pointVyCoord; uint256 pointVZxCoord; uint256 pointVZyCoord; uint256 pointV1yCoord; uint256 pointV1HxCoord; uint256 pointV1HyCoord; uint256 pointV2yCoord; uint256 pointUZxCoord; uint256 pointUZyCoord; uint256 pointU1yCoord; uint256 pointU1HxCoord; uint256 pointU1HyCoord; uint256 pointU2yCoord; bytes32 hashedKFragValidityMessage; address alicesKeyAsAddress; bytes5 lostBytes; } uint256 constant BIGNUM_SIZE = 32; uint256 constant POINT_SIZE = 33; uint256 constant SIGNATURE_SIZE = 64; uint256 constant CAPSULE_SIZE = 2 * POINT_SIZE + BIGNUM_SIZE; uint256 constant CORRECTNESS_PROOF_SIZE = 4 * POINT_SIZE + BIGNUM_SIZE + SIGNATURE_SIZE; uint256 constant CAPSULE_FRAG_SIZE = 3 * POINT_SIZE + BIGNUM_SIZE; uint256 constant FULL_CAPSULE_FRAG_SIZE = CAPSULE_FRAG_SIZE + CORRECTNESS_PROOF_SIZE; uint256 constant PRECOMPUTED_DATA_SIZE = (20 * BIGNUM_SIZE) + 32 + 20 + 5; /** * @notice Deserialize to capsule (not activated) */ function toCapsule(bytes memory _capsuleBytes) internal pure returns (Capsule memory capsule) { require(_capsuleBytes.length == CAPSULE_SIZE); uint256 pointer = getPointer(_capsuleBytes); pointer = copyPoint(pointer, capsule.pointE); pointer = copyPoint(pointer, capsule.pointV); capsule.bnSig = uint256(getBytes32(pointer)); } /** * @notice Deserialize to correctness proof * @param _pointer Proof bytes memory pointer * @param _proofBytesLength Proof bytes length */ function toCorrectnessProof(uint256 _pointer, uint256 _proofBytesLength) internal pure returns (CorrectnessProof memory proof) { require(_proofBytesLength >= CORRECTNESS_PROOF_SIZE); _pointer = copyPoint(_pointer, proof.pointE2); _pointer = copyPoint(_pointer, proof.pointV2); _pointer = copyPoint(_pointer, proof.pointKFragCommitment); _pointer = copyPoint(_pointer, proof.pointKFragPok); proof.bnSig = uint256(getBytes32(_pointer)); _pointer += BIGNUM_SIZE; proof.kFragSignature = new bytes(SIGNATURE_SIZE); // TODO optimize, just two mload->mstore (#1500) _pointer = copyBytes(_pointer, proof.kFragSignature, SIGNATURE_SIZE); if (_proofBytesLength > CORRECTNESS_PROOF_SIZE) { proof.metadata = new bytes(_proofBytesLength - CORRECTNESS_PROOF_SIZE); copyBytes(_pointer, proof.metadata, proof.metadata.length); } } /** * @notice Deserialize to correctness proof */ function toCorrectnessProof(bytes memory _proofBytes) internal pure returns (CorrectnessProof memory proof) { uint256 pointer = getPointer(_proofBytes); return toCorrectnessProof(pointer, _proofBytes.length); } /** * @notice Deserialize to CapsuleFrag */ function toCapsuleFrag(bytes memory _cFragBytes) internal pure returns (CapsuleFrag memory cFrag) { uint256 cFragBytesLength = _cFragBytes.length; require(cFragBytesLength >= FULL_CAPSULE_FRAG_SIZE); uint256 pointer = getPointer(_cFragBytes); pointer = copyPoint(pointer, cFrag.pointE1); pointer = copyPoint(pointer, cFrag.pointV1); cFrag.kFragId = getBytes32(pointer); pointer += BIGNUM_SIZE; pointer = copyPoint(pointer, cFrag.pointPrecursor); cFrag.proof = toCorrectnessProof(pointer, cFragBytesLength - CAPSULE_FRAG_SIZE); } /** * @notice Deserialize to precomputed data */ function toPreComputedData(bytes memory _preComputedData) internal pure returns (PreComputedData memory data) { require(_preComputedData.length == PRECOMPUTED_DATA_SIZE); uint256 initial_pointer = getPointer(_preComputedData); uint256 pointer = initial_pointer; data.pointEyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointEZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointEZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointUZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointUZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.hashedKFragValidityMessage = getBytes32(pointer); pointer += 32; data.alicesKeyAsAddress = address(bytes20(getBytes32(pointer))); pointer += 20; // Lost bytes: a bytes5 variable holding the following byte values: // 0: kfrag signature recovery value v // 1: cfrag signature recovery value v // 2: metadata signature recovery value v // 3: specification signature recovery value v // 4: ursula pubkey sign byte data.lostBytes = bytes5(getBytes32(pointer)); pointer += 5; require(pointer == initial_pointer + PRECOMPUTED_DATA_SIZE); } // TODO extract to external library if needed (#1500) /** * @notice Get the memory pointer for start of array */ function getPointer(bytes memory _bytes) internal pure returns (uint256 pointer) { assembly { pointer := add(_bytes, 32) // skip array length } } /** * @notice Copy point data from memory in the pointer position */ function copyPoint(uint256 _pointer, Point memory _point) internal pure returns (uint256 resultPointer) { // TODO optimize, copy to point memory directly (#1500) uint8 temp; uint256 xCoord; assembly { temp := byte(0, mload(_pointer)) xCoord := mload(add(_pointer, 1)) } _point.sign = temp; _point.xCoord = xCoord; resultPointer = _pointer + POINT_SIZE; } /** * @notice Read 1 byte from memory in the pointer position */ function getByte(uint256 _pointer) internal pure returns (byte result) { bytes32 word; assembly { word := mload(_pointer) } result = word[0]; return result; } /** * @notice Read 32 bytes from memory in the pointer position */ function getBytes32(uint256 _pointer) internal pure returns (bytes32 result) { assembly { result := mload(_pointer) } } /** * @notice Copy bytes from the source pointer to the target array * @dev Assumes that enough memory has been allocated to store in target. * Also assumes that '_target' was the last thing that was allocated * @param _bytesPointer Source memory pointer * @param _target Target array * @param _bytesLength Number of bytes to copy */ function copyBytes(uint256 _bytesPointer, bytes memory _target, uint256 _bytesLength) internal pure returns (uint256 resultPointer) { // Exploiting the fact that '_target' was the last thing to be allocated, // we can write entire words, and just overwrite any excess. assembly { // evm operations on words let words := div(add(_bytesLength, 31), 32) let source := _bytesPointer let destination := add(_target, 32) for { let i := 0 } // start at arr + 32 -> first byte corresponds to length lt(i, words) { i := add(i, 1) } { let offset := mul(i, 32) mstore(add(destination, offset), mload(add(source, offset))) } mstore(add(_target, add(32, mload(_target))), 0) } resultPointer = _bytesPointer + _bytesLength; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @notice Library to recover address and verify signatures * @dev Simple wrapper for `ecrecover` */ library SignatureVerifier { enum HashAlgorithm {KECCAK256, SHA256, RIPEMD160} // Header for Version E as defined by EIP191. First byte ('E') is also the version bytes25 constant EIP191_VERSION_E_HEADER = "Ethereum Signed Message:\n"; /** * @notice Recover signer address from hash and signature * @param _hash 32 bytes message hash * @param _signature Signature of hash - 32 bytes r + 32 bytes s + 1 byte v (could be 0, 1, 27, 28) */ function recover(bytes32 _hash, bytes memory _signature) internal pure returns (address) { require(_signature.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } require(v == 27 || v == 28); return ecrecover(_hash, v, r, s); } /** * @notice Transform public key to address * @param _publicKey secp256k1 public key */ function toAddress(bytes memory _publicKey) internal pure returns (address) { return address(uint160(uint256(keccak256(_publicKey)))); } /** * @notice Hash using one of pre built hashing algorithm * @param _message Signed message * @param _algorithm Hashing algorithm */ function hash(bytes memory _message, HashAlgorithm _algorithm) internal pure returns (bytes32 result) { if (_algorithm == HashAlgorithm.KECCAK256) { result = keccak256(_message); } else if (_algorithm == HashAlgorithm.SHA256) { result = sha256(_message); } else { result = ripemd160(_message); } } /** * @notice Verify ECDSA signature * @dev Uses one of pre built hashing algorithm * @param _message Signed message * @param _signature Signature of message hash * @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes) * @param _algorithm Hashing algorithm */ function verify( bytes memory _message, bytes memory _signature, bytes memory _publicKey, HashAlgorithm _algorithm ) internal pure returns (bool) { require(_publicKey.length == 64); return toAddress(_publicKey) == recover(hash(_message, _algorithm), _signature); } /** * @notice Hash message according to EIP191 signature specification * @dev It always assumes Keccak256 is used as hashing algorithm * @dev Only supports version 0 and version E (0x45) * @param _message Message to sign * @param _version EIP191 version to use */ function hashEIP191( bytes memory _message, byte _version ) internal view returns (bytes32 result) { if(_version == byte(0x00)){ // Version 0: Data with intended validator address validator = address(this); return keccak256(abi.encodePacked(byte(0x19), byte(0x00), validator, _message)); } else if (_version == byte(0x45)){ // Version E: personal_sign messages uint256 length = _message.length; require(length > 0, "Empty message not allowed for version E"); // Compute text-encoded length of message uint256 digits = 0; while (length != 0) { digits++; length /= 10; } bytes memory lengthAsText = new bytes(digits); length = _message.length; uint256 index = digits - 1; while (length != 0) { lengthAsText[index--] = byte(uint8(48 + length % 10)); length /= 10; } return keccak256(abi.encodePacked(byte(0x19), EIP191_VERSION_E_HEADER, lengthAsText, _message)); } else { revert("Unsupported EIP191 version"); } } /** * @notice Verify EIP191 signature * @dev It always assumes Keccak256 is used as hashing algorithm * @dev Only supports version 0 and version E (0x45) * @param _message Signed message * @param _signature Signature of message hash * @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes) * @param _version EIP191 version to use */ function verifyEIP191( bytes memory _message, bytes memory _signature, bytes memory _publicKey, byte _version ) internal view returns (bool) { require(_publicKey.length == 64); return toAddress(_publicKey) == recover(hashEIP191(_message, _version), _signature); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../aragon/interfaces/IERC900History.sol"; import "./Issuer.sol"; import "./lib/Bits.sol"; import "./lib/Snapshot.sol"; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/token/ERC20/SafeERC20.sol"; /** * @notice PolicyManager interface */ interface PolicyManagerInterface { function secondsPerPeriod() external view returns (uint32); function register(address _node, uint16 _period) external; function migrate(address _node) external; function ping( address _node, uint16 _processedPeriod1, uint16 _processedPeriod2, uint16 _periodToSetDefault ) external; } /** * @notice Adjudicator interface */ interface AdjudicatorInterface { function rewardCoefficient() external view returns (uint32); } /** * @notice WorkLock interface */ interface WorkLockInterface { function token() external view returns (NuCypherToken); } /** * @title StakingEscrowStub * @notice Stub is used to deploy main StakingEscrow after all other contract and make some variables immutable * @dev |v1.0.0| */ contract StakingEscrowStub is Upgradeable { using AdditionalMath for uint32; NuCypherToken public immutable token; uint32 public immutable genesisSecondsPerPeriod; uint32 public immutable secondsPerPeriod; uint16 public immutable minLockedPeriods; uint256 public immutable minAllowableLockedTokens; uint256 public immutable maxAllowableLockedTokens; /** * @notice Predefines some variables for use when deploying other contracts * @param _token Token contract * @param _genesisHoursPerPeriod Size of period in hours at genesis * @param _hoursPerPeriod Size of period in hours * @param _minLockedPeriods Min amount of periods during which tokens can be locked * @param _minAllowableLockedTokens Min amount of tokens that can be locked * @param _maxAllowableLockedTokens Max amount of tokens that can be locked */ constructor( NuCypherToken _token, uint32 _genesisHoursPerPeriod, uint32 _hoursPerPeriod, uint16 _minLockedPeriods, uint256 _minAllowableLockedTokens, uint256 _maxAllowableLockedTokens ) { require(_token.totalSupply() > 0 && _hoursPerPeriod != 0 && _genesisHoursPerPeriod != 0 && _genesisHoursPerPeriod <= _hoursPerPeriod && _minLockedPeriods > 1 && _maxAllowableLockedTokens != 0); token = _token; secondsPerPeriod = _hoursPerPeriod.mul32(1 hours); genesisSecondsPerPeriod = _genesisHoursPerPeriod.mul32(1 hours); minLockedPeriods = _minLockedPeriods; minAllowableLockedTokens = _minAllowableLockedTokens; maxAllowableLockedTokens = _maxAllowableLockedTokens; } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); // we have to use real values even though this is a stub require(address(delegateGet(_testTarget, this.token.selector)) == address(token)); // TODO uncomment after merging this PR #2579 // require(uint32(delegateGet(_testTarget, this.genesisSecondsPerPeriod.selector)) == genesisSecondsPerPeriod); require(uint32(delegateGet(_testTarget, this.secondsPerPeriod.selector)) == secondsPerPeriod); require(uint16(delegateGet(_testTarget, this.minLockedPeriods.selector)) == minLockedPeriods); require(delegateGet(_testTarget, this.minAllowableLockedTokens.selector) == minAllowableLockedTokens); require(delegateGet(_testTarget, this.maxAllowableLockedTokens.selector) == maxAllowableLockedTokens); } } /** * @title StakingEscrow * @notice Contract holds and locks stakers tokens. * Each staker that locks their tokens will receive some compensation * @dev |v5.7.1| */ contract StakingEscrow is Issuer, IERC900History { using AdditionalMath for uint256; using AdditionalMath for uint16; using Bits for uint256; using SafeMath for uint256; using Snapshot for uint128[]; using SafeERC20 for NuCypherToken; /** * @notice Signals that tokens were deposited * @param staker Staker address * @param value Amount deposited (in NuNits) * @param periods Number of periods tokens will be locked */ event Deposited(address indexed staker, uint256 value, uint16 periods); /** * @notice Signals that tokens were stake locked * @param staker Staker address * @param value Amount locked (in NuNits) * @param firstPeriod Starting lock period * @param periods Number of periods tokens will be locked */ event Locked(address indexed staker, uint256 value, uint16 firstPeriod, uint16 periods); /** * @notice Signals that a sub-stake was divided * @param staker Staker address * @param oldValue Old sub-stake value (in NuNits) * @param lastPeriod Final locked period of old sub-stake * @param newValue New sub-stake value (in NuNits) * @param periods Number of periods to extend sub-stake */ event Divided( address indexed staker, uint256 oldValue, uint16 lastPeriod, uint256 newValue, uint16 periods ); /** * @notice Signals that two sub-stakes were merged * @param staker Staker address * @param value1 Value of first sub-stake (in NuNits) * @param value2 Value of second sub-stake (in NuNits) * @param lastPeriod Final locked period of merged sub-stake */ event Merged(address indexed staker, uint256 value1, uint256 value2, uint16 lastPeriod); /** * @notice Signals that a sub-stake was prolonged * @param staker Staker address * @param value Value of sub-stake * @param lastPeriod Final locked period of old sub-stake * @param periods Number of periods sub-stake was extended */ event Prolonged(address indexed staker, uint256 value, uint16 lastPeriod, uint16 periods); /** * @notice Signals that tokens were withdrawn to the staker * @param staker Staker address * @param value Amount withdraws (in NuNits) */ event Withdrawn(address indexed staker, uint256 value); /** * @notice Signals that the worker associated with the staker made a commitment to next period * @param staker Staker address * @param period Period committed to * @param value Amount of tokens staked for the committed period */ event CommitmentMade(address indexed staker, uint16 indexed period, uint256 value); /** * @notice Signals that tokens were minted for previous periods * @param staker Staker address * @param period Previous period tokens minted for * @param value Amount minted (in NuNits) */ event Minted(address indexed staker, uint16 indexed period, uint256 value); /** * @notice Signals that the staker was slashed * @param staker Staker address * @param penalty Slashing penalty * @param investigator Investigator address * @param reward Value of reward provided to investigator (in NuNits) */ event Slashed(address indexed staker, uint256 penalty, address indexed investigator, uint256 reward); /** * @notice Signals that the restake parameter was activated/deactivated * @param staker Staker address * @param reStake Updated parameter value */ event ReStakeSet(address indexed staker, bool reStake); /** * @notice Signals that a worker was bonded to the staker * @param staker Staker address * @param worker Worker address * @param startPeriod Period bonding occurred */ event WorkerBonded(address indexed staker, address indexed worker, uint16 indexed startPeriod); /** * @notice Signals that the winddown parameter was activated/deactivated * @param staker Staker address * @param windDown Updated parameter value */ event WindDownSet(address indexed staker, bool windDown); /** * @notice Signals that the snapshot parameter was activated/deactivated * @param staker Staker address * @param snapshotsEnabled Updated parameter value */ event SnapshotSet(address indexed staker, bool snapshotsEnabled); /** * @notice Signals that the staker migrated their stake to the new period length * @param staker Staker address * @param period Period when migration happened */ event Migrated(address indexed staker, uint16 indexed period); /// internal event event WorkMeasurementSet(address indexed staker, bool measureWork); struct SubStakeInfo { uint16 firstPeriod; uint16 lastPeriod; uint16 unlockingDuration; uint128 lockedValue; } struct Downtime { uint16 startPeriod; uint16 endPeriod; } struct StakerInfo { uint256 value; /* * Stores periods that are committed but not yet rewarded. * In order to optimize storage, only two values are used instead of an array. * commitToNextPeriod() method invokes mint() method so there can only be two committed * periods that are not yet rewarded: the current and the next periods. */ uint16 currentCommittedPeriod; uint16 nextCommittedPeriod; uint16 lastCommittedPeriod; uint16 stub1; // former slot for lockReStakeUntilPeriod uint256 completedWork; uint16 workerStartPeriod; // period when worker was bonded address worker; uint256 flags; // uint256 to acquire whole slot and minimize operations on it uint256 reservedSlot1; uint256 reservedSlot2; uint256 reservedSlot3; uint256 reservedSlot4; uint256 reservedSlot5; Downtime[] pastDowntime; SubStakeInfo[] subStakes; uint128[] history; } // used only for upgrading uint16 internal constant RESERVED_PERIOD = 0; uint16 internal constant MAX_CHECKED_VALUES = 5; // to prevent high gas consumption in loops for slashing uint16 public constant MAX_SUB_STAKES = 30; uint16 internal constant MAX_UINT16 = 65535; // indices for flags uint8 internal constant RE_STAKE_DISABLED_INDEX = 0; uint8 internal constant WIND_DOWN_INDEX = 1; uint8 internal constant MEASURE_WORK_INDEX = 2; uint8 internal constant SNAPSHOTS_DISABLED_INDEX = 3; uint8 internal constant MIGRATED_INDEX = 4; uint16 public immutable minLockedPeriods; uint16 public immutable minWorkerPeriods; uint256 public immutable minAllowableLockedTokens; uint256 public immutable maxAllowableLockedTokens; PolicyManagerInterface public immutable policyManager; AdjudicatorInterface public immutable adjudicator; WorkLockInterface public immutable workLock; mapping (address => StakerInfo) public stakerInfo; address[] public stakers; mapping (address => address) public stakerFromWorker; mapping (uint16 => uint256) stub4; // former slot for lockedPerPeriod uint128[] public balanceHistory; address stub1; // former slot for PolicyManager address stub2; // former slot for Adjudicator address stub3; // former slot for WorkLock mapping (uint16 => uint256) _lockedPerPeriod; // only to make verifyState from previous version work, temporary // TODO remove after upgrade #2579 function lockedPerPeriod(uint16 _period) public view returns (uint256) { return _period != RESERVED_PERIOD ? _lockedPerPeriod[_period] : 111; } /** * @notice Constructor sets address of token contract and coefficients for minting * @param _token Token contract * @param _policyManager Policy Manager contract * @param _adjudicator Adjudicator contract * @param _workLock WorkLock contract. Zero address if there is no WorkLock * @param _genesisHoursPerPeriod Size of period in hours at genesis * @param _hoursPerPeriod Size of period in hours * @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays, * only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2. * See Equation 10 in Staking Protocol & Economics paper * @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier) * where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration * no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1. * See Equation 8 in Staking Protocol & Economics paper. * @param _firstPhaseTotalSupply Total supply for the first phase * @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1. * See Equation 7 in Staking Protocol & Economics paper. * @param _minLockedPeriods Min amount of periods during which tokens can be locked * @param _minAllowableLockedTokens Min amount of tokens that can be locked * @param _maxAllowableLockedTokens Max amount of tokens that can be locked * @param _minWorkerPeriods Min amount of periods while a worker can't be changed */ constructor( NuCypherToken _token, PolicyManagerInterface _policyManager, AdjudicatorInterface _adjudicator, WorkLockInterface _workLock, uint32 _genesisHoursPerPeriod, uint32 _hoursPerPeriod, uint256 _issuanceDecayCoefficient, uint256 _lockDurationCoefficient1, uint256 _lockDurationCoefficient2, uint16 _maximumRewardedPeriods, uint256 _firstPhaseTotalSupply, uint256 _firstPhaseMaxIssuance, uint16 _minLockedPeriods, uint256 _minAllowableLockedTokens, uint256 _maxAllowableLockedTokens, uint16 _minWorkerPeriods ) Issuer( _token, _genesisHoursPerPeriod, _hoursPerPeriod, _issuanceDecayCoefficient, _lockDurationCoefficient1, _lockDurationCoefficient2, _maximumRewardedPeriods, _firstPhaseTotalSupply, _firstPhaseMaxIssuance ) { // constant `1` in the expression `_minLockedPeriods > 1` uses to simplify the `lock` method require(_minLockedPeriods > 1 && _maxAllowableLockedTokens != 0); minLockedPeriods = _minLockedPeriods; minAllowableLockedTokens = _minAllowableLockedTokens; maxAllowableLockedTokens = _maxAllowableLockedTokens; minWorkerPeriods = _minWorkerPeriods; require((_policyManager.secondsPerPeriod() == _hoursPerPeriod * (1 hours) || _policyManager.secondsPerPeriod() == _genesisHoursPerPeriod * (1 hours)) && _adjudicator.rewardCoefficient() != 0 && (address(_workLock) == address(0) || _workLock.token() == _token)); policyManager = _policyManager; adjudicator = _adjudicator; workLock = _workLock; } /** * @dev Checks the existence of a staker in the contract */ modifier onlyStaker() { StakerInfo storage info = stakerInfo[msg.sender]; require((info.value > 0 || info.nextCommittedPeriod != 0) && info.flags.bitSet(MIGRATED_INDEX)); _; } //------------------------Main getters------------------------ /** * @notice Get all tokens belonging to the staker */ function getAllTokens(address _staker) external view returns (uint256) { return stakerInfo[_staker].value; } /** * @notice Get all flags for the staker */ function getFlags(address _staker) external view returns ( bool windDown, bool reStake, bool measureWork, bool snapshots, bool migrated ) { StakerInfo storage info = stakerInfo[_staker]; windDown = info.flags.bitSet(WIND_DOWN_INDEX); reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX); measureWork = info.flags.bitSet(MEASURE_WORK_INDEX); snapshots = !info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX); migrated = info.flags.bitSet(MIGRATED_INDEX); } /** * @notice Get the start period. Use in the calculation of the last period of the sub stake * @param _info Staker structure * @param _currentPeriod Current period */ function getStartPeriod(StakerInfo storage _info, uint16 _currentPeriod) internal view returns (uint16) { // if the next period (after current) is committed if (_info.flags.bitSet(WIND_DOWN_INDEX) && _info.nextCommittedPeriod > _currentPeriod) { return _currentPeriod + 1; } return _currentPeriod; } /** * @notice Get the last period of the sub stake * @param _subStake Sub stake structure * @param _startPeriod Pre-calculated start period */ function getLastPeriodOfSubStake(SubStakeInfo storage _subStake, uint16 _startPeriod) internal view returns (uint16) { if (_subStake.lastPeriod != 0) { return _subStake.lastPeriod; } uint32 lastPeriod = uint32(_startPeriod) + _subStake.unlockingDuration; if (lastPeriod > uint32(MAX_UINT16)) { return MAX_UINT16; } return uint16(lastPeriod); } /** * @notice Get the last period of the sub stake * @param _staker Staker * @param _index Stake index */ function getLastPeriodOfSubStake(address _staker, uint256 _index) public view returns (uint16) { StakerInfo storage info = stakerInfo[_staker]; SubStakeInfo storage subStake = info.subStakes[_index]; uint16 startPeriod = getStartPeriod(info, getCurrentPeriod()); return getLastPeriodOfSubStake(subStake, startPeriod); } /** * @notice Get the value of locked tokens for a staker in a specified period * @dev Information may be incorrect for rewarded or not committed surpassed period * @param _info Staker structure * @param _currentPeriod Current period * @param _period Next period */ function getLockedTokens(StakerInfo storage _info, uint16 _currentPeriod, uint16 _period) internal view returns (uint256 lockedValue) { lockedValue = 0; uint16 startPeriod = getStartPeriod(_info, _currentPeriod); for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.firstPeriod <= _period && getLastPeriodOfSubStake(subStake, startPeriod) >= _period) { lockedValue += subStake.lockedValue; } } } /** * @notice Get the value of locked tokens for a staker in a future period * @dev This function is used by PreallocationEscrow so its signature can't be updated. * @param _staker Staker * @param _offsetPeriods Amount of periods that will be added to the current period */ function getLockedTokens(address _staker, uint16 _offsetPeriods) external view returns (uint256 lockedValue) { StakerInfo storage info = stakerInfo[_staker]; uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod.add16(_offsetPeriods); return getLockedTokens(info, currentPeriod, nextPeriod); } /** * @notice Get the last committed staker's period * @param _staker Staker */ function getLastCommittedPeriod(address _staker) public view returns (uint16) { StakerInfo storage info = stakerInfo[_staker]; return info.nextCommittedPeriod != 0 ? info.nextCommittedPeriod : info.lastCommittedPeriod; } /** * @notice Get the value of locked tokens for active stakers in (getCurrentPeriod() + _offsetPeriods) period * as well as stakers and their locked tokens * @param _offsetPeriods Amount of periods for locked tokens calculation * @param _startIndex Start index for looking in stakers array * @param _maxStakers Max stakers for looking, if set 0 then all will be used * @return allLockedTokens Sum of locked tokens for active stakers * @return activeStakers Array of stakers and their locked tokens. Stakers addresses stored as uint256 * @dev Note that activeStakers[0] in an array of uint256, but you want addresses. Careful when used directly! */ function getActiveStakers(uint16 _offsetPeriods, uint256 _startIndex, uint256 _maxStakers) external view returns (uint256 allLockedTokens, uint256[2][] memory activeStakers) { require(_offsetPeriods > 0); uint256 endIndex = stakers.length; require(_startIndex < endIndex); if (_maxStakers != 0 && _startIndex + _maxStakers < endIndex) { endIndex = _startIndex + _maxStakers; } activeStakers = new uint256[2][](endIndex - _startIndex); allLockedTokens = 0; uint256 resultIndex = 0; uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod.add16(_offsetPeriods); for (uint256 i = _startIndex; i < endIndex; i++) { address staker = stakers[i]; StakerInfo storage info = stakerInfo[staker]; if (info.currentCommittedPeriod != currentPeriod && info.nextCommittedPeriod != currentPeriod) { continue; } uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); if (lockedTokens != 0) { activeStakers[resultIndex][0] = uint256(staker); activeStakers[resultIndex++][1] = lockedTokens; allLockedTokens += lockedTokens; } } assembly { mstore(activeStakers, resultIndex) } } /** * @notice Get worker using staker's address */ function getWorkerFromStaker(address _staker) external view returns (address) { return stakerInfo[_staker].worker; } /** * @notice Get work that completed by the staker */ function getCompletedWork(address _staker) external view returns (uint256) { return stakerInfo[_staker].completedWork; } /** * @notice Find index of downtime structure that includes specified period * @dev If specified period is outside all downtime periods, the length of the array will be returned * @param _staker Staker * @param _period Specified period number */ function findIndexOfPastDowntime(address _staker, uint16 _period) external view returns (uint256 index) { StakerInfo storage info = stakerInfo[_staker]; for (index = 0; index < info.pastDowntime.length; index++) { if (_period <= info.pastDowntime[index].endPeriod) { return index; } } } //------------------------Main methods------------------------ /** * @notice Start or stop measuring the work of a staker * @param _staker Staker * @param _measureWork Value for `measureWork` parameter * @return Work that was previously done */ function setWorkMeasurement(address _staker, bool _measureWork) external returns (uint256) { require(msg.sender == address(workLock)); StakerInfo storage info = stakerInfo[_staker]; if (info.flags.bitSet(MEASURE_WORK_INDEX) == _measureWork) { return info.completedWork; } info.flags = info.flags.toggleBit(MEASURE_WORK_INDEX); emit WorkMeasurementSet(_staker, _measureWork); return info.completedWork; } /** * @notice Bond worker * @param _worker Worker address. Must be a real address, not a contract */ function bondWorker(address _worker) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; // Specified worker is already bonded with this staker require(_worker != info.worker); uint16 currentPeriod = getCurrentPeriod(); if (info.worker != address(0)) { // If this staker had a worker ... // Check that enough time has passed to change it require(currentPeriod >= info.workerStartPeriod.add16(minWorkerPeriods)); // Remove the old relation "worker->staker" stakerFromWorker[info.worker] = address(0); } if (_worker != address(0)) { // Specified worker is already in use require(stakerFromWorker[_worker] == address(0)); // Specified worker is a staker require(stakerInfo[_worker].subStakes.length == 0 || _worker == msg.sender); // Set new worker->staker relation stakerFromWorker[_worker] = msg.sender; } // Bond new worker (or unbond if _worker == address(0)) info.worker = _worker; info.workerStartPeriod = currentPeriod; emit WorkerBonded(msg.sender, _worker, currentPeriod); } /** * @notice Set `reStake` parameter. If true then all staking rewards will be added to locked stake * @param _reStake Value for parameter */ function setReStake(bool _reStake) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(RE_STAKE_DISABLED_INDEX) == !_reStake) { return; } info.flags = info.flags.toggleBit(RE_STAKE_DISABLED_INDEX); emit ReStakeSet(msg.sender, _reStake); } /** * @notice Deposit tokens from WorkLock contract * @param _staker Staker address * @param _value Amount of tokens to deposit * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function depositFromWorkLock( address _staker, uint256 _value, uint16 _unlockingDuration ) external { require(msg.sender == address(workLock)); StakerInfo storage info = stakerInfo[_staker]; if (!info.flags.bitSet(WIND_DOWN_INDEX) && info.subStakes.length == 0) { info.flags = info.flags.toggleBit(WIND_DOWN_INDEX); emit WindDownSet(_staker, true); } // WorkLock still uses the genesis period length (24h) _unlockingDuration = recalculatePeriod(_unlockingDuration); deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration); } /** * @notice Set `windDown` parameter. * If true then stake's duration will be decreasing in each period with `commitToNextPeriod()` * @param _windDown Value for parameter */ function setWindDown(bool _windDown) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(WIND_DOWN_INDEX) == _windDown) { return; } info.flags = info.flags.toggleBit(WIND_DOWN_INDEX); emit WindDownSet(msg.sender, _windDown); // duration adjustment if next period is committed uint16 nextPeriod = getCurrentPeriod() + 1; if (info.nextCommittedPeriod != nextPeriod) { return; } // adjust sub-stakes duration for the new value of winding down parameter for (uint256 index = 0; index < info.subStakes.length; index++) { SubStakeInfo storage subStake = info.subStakes[index]; // sub-stake does not have fixed last period when winding down is disabled if (!_windDown && subStake.lastPeriod == nextPeriod) { subStake.lastPeriod = 0; subStake.unlockingDuration = 1; continue; } // this sub-stake is no longer affected by winding down parameter if (subStake.lastPeriod != 0 || subStake.unlockingDuration == 0) { continue; } subStake.unlockingDuration = _windDown ? subStake.unlockingDuration - 1 : subStake.unlockingDuration + 1; if (subStake.unlockingDuration == 0) { subStake.lastPeriod = nextPeriod; } } } /** * @notice Activate/deactivate taking snapshots of balances * @param _enableSnapshots True to activate snapshots, False to deactivate */ function setSnapshots(bool _enableSnapshots) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX) == !_enableSnapshots) { return; } uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); if(_enableSnapshots){ info.history.addSnapshot(info.value); balanceHistory.addSnapshot(lastGlobalBalance + info.value); } else { info.history.addSnapshot(0); balanceHistory.addSnapshot(lastGlobalBalance - info.value); } info.flags = info.flags.toggleBit(SNAPSHOTS_DISABLED_INDEX); emit SnapshotSet(msg.sender, _enableSnapshots); } /** * @notice Adds a new snapshot to both the staker and global balance histories, * assuming the staker's balance was already changed * @param _info Reference to affected staker's struct * @param _addition Variance in balance. It can be positive or negative. */ function addSnapshot(StakerInfo storage _info, int256 _addition) internal { if(!_info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX)){ _info.history.addSnapshot(_info.value); uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); balanceHistory.addSnapshot(lastGlobalBalance.addSigned(_addition)); } } /** * @notice Implementation of the receiveApproval(address,uint256,address,bytes) method * (see NuCypherToken contract). Deposit all tokens that were approved to transfer * @param _from Staker * @param _value Amount of tokens to deposit * @param _tokenContract Token contract address * @notice (param _extraData) Amount of periods during which tokens will be unlocked when wind down is enabled */ function receiveApproval( address _from, uint256 _value, address _tokenContract, bytes calldata /* _extraData */ ) external { require(_tokenContract == address(token) && msg.sender == address(token)); // Copy first 32 bytes from _extraData, according to calldata memory layout: // // 0x00: method signature 4 bytes // 0x04: _from 32 bytes after encoding // 0x24: _value 32 bytes after encoding // 0x44: _tokenContract 32 bytes after encoding // 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter) // 0x84: _extraData length 32 bytes // 0xA4: _extraData data Length determined by previous variable // // See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples uint256 payloadSize; uint256 payload; assembly { payloadSize := calldataload(0x84) payload := calldataload(0xA4) } payload = payload >> 8*(32 - payloadSize); deposit(_from, _from, MAX_SUB_STAKES, _value, uint16(payload)); } /** * @notice Deposit tokens and create new sub-stake. Use this method to become a staker * @param _staker Staker * @param _value Amount of tokens to deposit * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function deposit(address _staker, uint256 _value, uint16 _unlockingDuration) external { deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration); } /** * @notice Deposit tokens and increase lock amount of an existing sub-stake * @dev This is preferable way to stake tokens because will be fewer active sub-stakes in the result * @param _index Index of the sub stake * @param _value Amount of tokens which will be locked */ function depositAndIncrease(uint256 _index, uint256 _value) external onlyStaker { require(_index < MAX_SUB_STAKES); deposit(msg.sender, msg.sender, _index, _value, 0); } /** * @notice Deposit tokens * @dev Specify either index and zero periods (for an existing sub-stake) * or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both * @param _staker Staker * @param _payer Owner of tokens * @param _index Index of the sub stake * @param _value Amount of tokens to deposit * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function deposit(address _staker, address _payer, uint256 _index, uint256 _value, uint16 _unlockingDuration) internal { require(_value != 0); StakerInfo storage info = stakerInfo[_staker]; // A staker can't be a worker for another staker require(stakerFromWorker[_staker] == address(0) || stakerFromWorker[_staker] == info.worker); // initial stake of the staker if (info.subStakes.length == 0 && info.lastCommittedPeriod == 0) { stakers.push(_staker); policyManager.register(_staker, getCurrentPeriod() - 1); info.flags = info.flags.toggleBit(MIGRATED_INDEX); } require(info.flags.bitSet(MIGRATED_INDEX)); token.safeTransferFrom(_payer, address(this), _value); info.value += _value; lock(_staker, _index, _value, _unlockingDuration); addSnapshot(info, int256(_value)); if (_index >= MAX_SUB_STAKES) { emit Deposited(_staker, _value, _unlockingDuration); } else { uint16 lastPeriod = getLastPeriodOfSubStake(_staker, _index); emit Deposited(_staker, _value, lastPeriod - getCurrentPeriod()); } } /** * @notice Lock some tokens as a new sub-stake * @param _value Amount of tokens which will be locked * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function lockAndCreate(uint256 _value, uint16 _unlockingDuration) external onlyStaker { lock(msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration); } /** * @notice Increase lock amount of an existing sub-stake * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease(uint256 _index, uint256 _value) external onlyStaker { require(_index < MAX_SUB_STAKES); lock(msg.sender, _index, _value, 0); } /** * @notice Lock some tokens as a stake * @dev Specify either index and zero periods (for an existing sub-stake) * or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both * @param _staker Staker * @param _index Index of the sub stake * @param _value Amount of tokens which will be locked * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function lock(address _staker, uint256 _index, uint256 _value, uint16 _unlockingDuration) internal { if (_index < MAX_SUB_STAKES) { require(_value > 0); } else { require(_value >= minAllowableLockedTokens && _unlockingDuration >= minLockedPeriods); } uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; StakerInfo storage info = stakerInfo[_staker]; uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); uint256 requestedLockedTokens = _value.add(lockedTokens); require(requestedLockedTokens <= info.value && requestedLockedTokens <= maxAllowableLockedTokens); // next period is committed if (info.nextCommittedPeriod == nextPeriod) { _lockedPerPeriod[nextPeriod] += _value; emit CommitmentMade(_staker, nextPeriod, _value); } // if index was provided then increase existing sub-stake if (_index < MAX_SUB_STAKES) { lockAndIncrease(info, currentPeriod, nextPeriod, _staker, _index, _value); // otherwise create new } else { lockAndCreate(info, nextPeriod, _staker, _value, _unlockingDuration); } } /** * @notice Lock some tokens as a new sub-stake * @param _info Staker structure * @param _nextPeriod Next period * @param _staker Staker * @param _value Amount of tokens which will be locked * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function lockAndCreate( StakerInfo storage _info, uint16 _nextPeriod, address _staker, uint256 _value, uint16 _unlockingDuration ) internal { uint16 duration = _unlockingDuration; // if winding down is enabled and next period is committed // then sub-stakes duration were decreased if (_info.nextCommittedPeriod == _nextPeriod && _info.flags.bitSet(WIND_DOWN_INDEX)) { duration -= 1; } saveSubStake(_info, _nextPeriod, 0, duration, _value); emit Locked(_staker, _value, _nextPeriod, _unlockingDuration); } /** * @notice Increase lock amount of an existing sub-stake * @dev Probably will be created a new sub-stake but it will be active only one period * @param _info Staker structure * @param _currentPeriod Current period * @param _nextPeriod Next period * @param _staker Staker * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease( StakerInfo storage _info, uint16 _currentPeriod, uint16 _nextPeriod, address _staker, uint256 _index, uint256 _value ) internal { SubStakeInfo storage subStake = _info.subStakes[_index]; (, uint16 lastPeriod) = checkLastPeriodOfSubStake(_info, subStake, _currentPeriod); // create temporary sub-stake for current or previous committed periods // to leave locked amount in this period unchanged if (_info.currentCommittedPeriod != 0 && _info.currentCommittedPeriod <= _currentPeriod || _info.nextCommittedPeriod != 0 && _info.nextCommittedPeriod <= _currentPeriod) { saveSubStake(_info, subStake.firstPeriod, _currentPeriod, 0, subStake.lockedValue); } subStake.lockedValue += uint128(_value); // all new locks should start from the next period subStake.firstPeriod = _nextPeriod; emit Locked(_staker, _value, _nextPeriod, lastPeriod - _currentPeriod); } /** * @notice Checks that last period of sub-stake is greater than the current period * @param _info Staker structure * @param _subStake Sub-stake structure * @param _currentPeriod Current period * @return startPeriod Start period. Use in the calculation of the last period of the sub stake * @return lastPeriod Last period of the sub stake */ function checkLastPeriodOfSubStake( StakerInfo storage _info, SubStakeInfo storage _subStake, uint16 _currentPeriod ) internal view returns (uint16 startPeriod, uint16 lastPeriod) { startPeriod = getStartPeriod(_info, _currentPeriod); lastPeriod = getLastPeriodOfSubStake(_subStake, startPeriod); // The sub stake must be active at least in the next period require(lastPeriod > _currentPeriod); } /** * @notice Save sub stake. First tries to override inactive sub stake * @dev Inactive sub stake means that last period of sub stake has been surpassed and already rewarded * @param _info Staker structure * @param _firstPeriod First period of the sub stake * @param _lastPeriod Last period of the sub stake * @param _unlockingDuration Duration of the sub stake in periods * @param _lockedValue Amount of locked tokens */ function saveSubStake( StakerInfo storage _info, uint16 _firstPeriod, uint16 _lastPeriod, uint16 _unlockingDuration, uint256 _lockedValue ) internal { for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.lastPeriod != 0 && (_info.currentCommittedPeriod == 0 || subStake.lastPeriod < _info.currentCommittedPeriod) && (_info.nextCommittedPeriod == 0 || subStake.lastPeriod < _info.nextCommittedPeriod)) { subStake.firstPeriod = _firstPeriod; subStake.lastPeriod = _lastPeriod; subStake.unlockingDuration = _unlockingDuration; subStake.lockedValue = uint128(_lockedValue); return; } } require(_info.subStakes.length < MAX_SUB_STAKES); _info.subStakes.push(SubStakeInfo(_firstPeriod, _lastPeriod, _unlockingDuration, uint128(_lockedValue))); } /** * @notice Divide sub stake into two parts * @param _index Index of the sub stake * @param _newValue New sub stake value * @param _additionalDuration Amount of periods for extending sub stake */ function divideStake(uint256 _index, uint256 _newValue, uint16 _additionalDuration) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; require(_newValue >= minAllowableLockedTokens && _additionalDuration > 0); SubStakeInfo storage subStake = info.subStakes[_index]; uint16 currentPeriod = getCurrentPeriod(); (, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod); uint256 oldValue = subStake.lockedValue; subStake.lockedValue = uint128(oldValue.sub(_newValue)); require(subStake.lockedValue >= minAllowableLockedTokens); uint16 requestedPeriods = subStake.unlockingDuration.add16(_additionalDuration); saveSubStake(info, subStake.firstPeriod, 0, requestedPeriods, _newValue); emit Divided(msg.sender, oldValue, lastPeriod, _newValue, _additionalDuration); emit Locked(msg.sender, _newValue, subStake.firstPeriod, requestedPeriods); } /** * @notice Prolong active sub stake * @param _index Index of the sub stake * @param _additionalDuration Amount of periods for extending sub stake */ function prolongStake(uint256 _index, uint16 _additionalDuration) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; // Incorrect parameters require(_additionalDuration > 0); SubStakeInfo storage subStake = info.subStakes[_index]; uint16 currentPeriod = getCurrentPeriod(); (uint16 startPeriod, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod); subStake.unlockingDuration = subStake.unlockingDuration.add16(_additionalDuration); // if the sub stake ends in the next committed period then reset the `lastPeriod` field if (lastPeriod == startPeriod) { subStake.lastPeriod = 0; } // The extended sub stake must not be less than the minimum value require(uint32(lastPeriod - currentPeriod) + _additionalDuration >= minLockedPeriods); emit Locked(msg.sender, subStake.lockedValue, lastPeriod + 1, _additionalDuration); emit Prolonged(msg.sender, subStake.lockedValue, lastPeriod, _additionalDuration); } /** * @notice Merge two sub-stakes into one if their last periods are equal * @dev It's possible that both sub-stakes will be active after this transaction. * But only one of them will be active until next call `commitToNextPeriod` (in the next period) * @param _index1 Index of the first sub-stake * @param _index2 Index of the second sub-stake */ function mergeStake(uint256 _index1, uint256 _index2) external onlyStaker { require(_index1 != _index2); // must be different sub-stakes StakerInfo storage info = stakerInfo[msg.sender]; SubStakeInfo storage subStake1 = info.subStakes[_index1]; SubStakeInfo storage subStake2 = info.subStakes[_index2]; uint16 currentPeriod = getCurrentPeriod(); (, uint16 lastPeriod1) = checkLastPeriodOfSubStake(info, subStake1, currentPeriod); (, uint16 lastPeriod2) = checkLastPeriodOfSubStake(info, subStake2, currentPeriod); // both sub-stakes must have equal last period to be mergeable require(lastPeriod1 == lastPeriod2); emit Merged(msg.sender, subStake1.lockedValue, subStake2.lockedValue, lastPeriod1); if (subStake1.firstPeriod == subStake2.firstPeriod) { subStake1.lockedValue += subStake2.lockedValue; subStake2.lastPeriod = 1; subStake2.unlockingDuration = 0; } else if (subStake1.firstPeriod > subStake2.firstPeriod) { subStake1.lockedValue += subStake2.lockedValue; subStake2.lastPeriod = subStake1.firstPeriod - 1; subStake2.unlockingDuration = 0; } else { subStake2.lockedValue += subStake1.lockedValue; subStake1.lastPeriod = subStake2.firstPeriod - 1; subStake1.unlockingDuration = 0; } } /** * @notice Remove unused sub-stake to decrease gas cost for several methods */ function removeUnusedSubStake(uint16 _index) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; uint256 lastIndex = info.subStakes.length - 1; SubStakeInfo storage subStake = info.subStakes[_index]; require(subStake.lastPeriod != 0 && (info.currentCommittedPeriod == 0 || subStake.lastPeriod < info.currentCommittedPeriod) && (info.nextCommittedPeriod == 0 || subStake.lastPeriod < info.nextCommittedPeriod)); if (_index != lastIndex) { SubStakeInfo storage lastSubStake = info.subStakes[lastIndex]; subStake.firstPeriod = lastSubStake.firstPeriod; subStake.lastPeriod = lastSubStake.lastPeriod; subStake.unlockingDuration = lastSubStake.unlockingDuration; subStake.lockedValue = lastSubStake.lockedValue; } info.subStakes.pop(); } /** * @notice Withdraw available amount of tokens to staker * @param _value Amount of tokens to withdraw */ function withdraw(uint256 _value) external onlyStaker { uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; StakerInfo storage info = stakerInfo[msg.sender]; // the max locked tokens in most cases will be in the current period // but when the staker locks more then we should use the next period uint256 lockedTokens = Math.max(getLockedTokens(info, currentPeriod, nextPeriod), getLockedTokens(info, currentPeriod, currentPeriod)); require(_value <= info.value.sub(lockedTokens)); info.value -= _value; addSnapshot(info, - int256(_value)); token.safeTransfer(msg.sender, _value); emit Withdrawn(msg.sender, _value); // unbond worker if staker withdraws last portion of NU if (info.value == 0 && info.nextCommittedPeriod == 0 && info.worker != address(0)) { stakerFromWorker[info.worker] = address(0); info.worker = address(0); emit WorkerBonded(msg.sender, address(0), currentPeriod); } } /** * @notice Make a commitment to the next period and mint for the previous period */ function commitToNextPeriod() external isInitialized { address staker = stakerFromWorker[msg.sender]; StakerInfo storage info = stakerInfo[staker]; // Staker must have a stake to make a commitment require(info.value > 0); // Only worker with real address can make a commitment require(msg.sender == tx.origin); migrate(staker); uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; // the period has already been committed require(info.nextCommittedPeriod != nextPeriod); uint16 lastCommittedPeriod = getLastCommittedPeriod(staker); (uint16 processedPeriod1, uint16 processedPeriod2) = mint(staker); uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); require(lockedTokens > 0); _lockedPerPeriod[nextPeriod] += lockedTokens; info.currentCommittedPeriod = info.nextCommittedPeriod; info.nextCommittedPeriod = nextPeriod; decreaseSubStakesDuration(info, nextPeriod); // staker was inactive for several periods if (lastCommittedPeriod < currentPeriod) { info.pastDowntime.push(Downtime(lastCommittedPeriod + 1, currentPeriod)); } policyManager.ping(staker, processedPeriod1, processedPeriod2, nextPeriod); emit CommitmentMade(staker, nextPeriod, lockedTokens); } /** * @notice Migrate from the old period length to the new one. Can be done only once * @param _staker Staker */ function migrate(address _staker) public { StakerInfo storage info = stakerInfo[_staker]; // check that provided address is/was a staker require(info.subStakes.length != 0 || info.lastCommittedPeriod != 0); if (info.flags.bitSet(MIGRATED_INDEX)) { return; } // reset state info.currentCommittedPeriod = 0; info.nextCommittedPeriod = 0; // maintain case when no more sub-stakes and need to avoid re-registering this staker during deposit info.lastCommittedPeriod = 1; info.workerStartPeriod = recalculatePeriod(info.workerStartPeriod); delete info.pastDowntime; // recalculate all sub-stakes uint16 currentPeriod = getCurrentPeriod(); for (uint256 i = 0; i < info.subStakes.length; i++) { SubStakeInfo storage subStake = info.subStakes[i]; subStake.firstPeriod = recalculatePeriod(subStake.firstPeriod); // sub-stake has fixed last period if (subStake.lastPeriod != 0) { subStake.lastPeriod = recalculatePeriod(subStake.lastPeriod); if (subStake.lastPeriod == 0) { subStake.lastPeriod = 1; } subStake.unlockingDuration = 0; // sub-stake has no fixed ending but possible that with new period length will have } else { uint16 oldCurrentPeriod = uint16(block.timestamp / genesisSecondsPerPeriod); uint16 lastPeriod = recalculatePeriod(oldCurrentPeriod + subStake.unlockingDuration); subStake.unlockingDuration = lastPeriod - currentPeriod; if (subStake.unlockingDuration == 0) { subStake.lastPeriod = lastPeriod; } } } policyManager.migrate(_staker); info.flags = info.flags.toggleBit(MIGRATED_INDEX); emit Migrated(_staker, currentPeriod); } /** * @notice Decrease sub-stakes duration if `windDown` is enabled */ function decreaseSubStakesDuration(StakerInfo storage _info, uint16 _nextPeriod) internal { if (!_info.flags.bitSet(WIND_DOWN_INDEX)) { return; } for (uint256 index = 0; index < _info.subStakes.length; index++) { SubStakeInfo storage subStake = _info.subStakes[index]; if (subStake.lastPeriod != 0 || subStake.unlockingDuration == 0) { continue; } subStake.unlockingDuration--; if (subStake.unlockingDuration == 0) { subStake.lastPeriod = _nextPeriod; } } } /** * @notice Mint tokens for previous periods if staker locked their tokens and made a commitment */ function mint() external onlyStaker { // save last committed period to the storage if both periods will be empty after minting // because we won't be able to calculate last committed period // see getLastCommittedPeriod(address) StakerInfo storage info = stakerInfo[msg.sender]; uint16 previousPeriod = getCurrentPeriod() - 1; if (info.nextCommittedPeriod <= previousPeriod && info.nextCommittedPeriod != 0) { info.lastCommittedPeriod = info.nextCommittedPeriod; } (uint16 processedPeriod1, uint16 processedPeriod2) = mint(msg.sender); if (processedPeriod1 != 0 || processedPeriod2 != 0) { policyManager.ping(msg.sender, processedPeriod1, processedPeriod2, 0); } } /** * @notice Mint tokens for previous periods if staker locked their tokens and made a commitment * @param _staker Staker * @return processedPeriod1 Processed period: currentCommittedPeriod or zero * @return processedPeriod2 Processed period: nextCommittedPeriod or zero */ function mint(address _staker) internal returns (uint16 processedPeriod1, uint16 processedPeriod2) { uint16 currentPeriod = getCurrentPeriod(); uint16 previousPeriod = currentPeriod - 1; StakerInfo storage info = stakerInfo[_staker]; if (info.nextCommittedPeriod == 0 || info.currentCommittedPeriod == 0 && info.nextCommittedPeriod > previousPeriod || info.currentCommittedPeriod > previousPeriod) { return (0, 0); } uint16 startPeriod = getStartPeriod(info, currentPeriod); uint256 reward = 0; bool reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX); if (info.currentCommittedPeriod != 0) { reward = mint(info, info.currentCommittedPeriod, currentPeriod, startPeriod, reStake); processedPeriod1 = info.currentCommittedPeriod; info.currentCommittedPeriod = 0; if (reStake) { _lockedPerPeriod[info.nextCommittedPeriod] += reward; } } if (info.nextCommittedPeriod <= previousPeriod) { reward += mint(info, info.nextCommittedPeriod, currentPeriod, startPeriod, reStake); processedPeriod2 = info.nextCommittedPeriod; info.nextCommittedPeriod = 0; } info.value += reward; if (info.flags.bitSet(MEASURE_WORK_INDEX)) { info.completedWork += reward; } addSnapshot(info, int256(reward)); emit Minted(_staker, previousPeriod, reward); } /** * @notice Calculate reward for one period * @param _info Staker structure * @param _mintingPeriod Period for minting calculation * @param _currentPeriod Current period * @param _startPeriod Pre-calculated start period */ function mint( StakerInfo storage _info, uint16 _mintingPeriod, uint16 _currentPeriod, uint16 _startPeriod, bool _reStake ) internal returns (uint256 reward) { reward = 0; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (subStake.firstPeriod <= _mintingPeriod && lastPeriod >= _mintingPeriod) { uint256 subStakeReward = mint( _currentPeriod, subStake.lockedValue, _lockedPerPeriod[_mintingPeriod], lastPeriod.sub16(_mintingPeriod)); reward += subStakeReward; if (_reStake) { subStake.lockedValue += uint128(subStakeReward); } } } return reward; } //-------------------------Slashing------------------------- /** * @notice Slash the staker's stake and reward the investigator * @param _staker Staker's address * @param _penalty Penalty * @param _investigator Investigator * @param _reward Reward for the investigator */ function slashStaker( address _staker, uint256 _penalty, address _investigator, uint256 _reward ) public isInitialized { require(msg.sender == address(adjudicator)); require(_penalty > 0); StakerInfo storage info = stakerInfo[_staker]; require(info.flags.bitSet(MIGRATED_INDEX)); if (info.value <= _penalty) { _penalty = info.value; } info.value -= _penalty; if (_reward > _penalty) { _reward = _penalty; } uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; uint16 startPeriod = getStartPeriod(info, currentPeriod); (uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex) = getLockedTokensAndShortestSubStake(info, currentPeriod, nextPeriod, startPeriod); // Decrease the stake if amount of locked tokens in the current period more than staker has uint256 lockedTokens = currentLock + currentAndNextLock; if (info.value < lockedTokens) { decreaseSubStakes(info, lockedTokens - info.value, currentPeriod, startPeriod, shortestSubStakeIndex); } // Decrease the stake if amount of locked tokens in the next period more than staker has if (nextLock > 0) { lockedTokens = nextLock + currentAndNextLock - (currentAndNextLock > info.value ? currentAndNextLock - info.value : 0); if (info.value < lockedTokens) { decreaseSubStakes(info, lockedTokens - info.value, nextPeriod, startPeriod, MAX_SUB_STAKES); } } emit Slashed(_staker, _penalty, _investigator, _reward); if (_penalty > _reward) { unMint(_penalty - _reward); } // TODO change to withdrawal pattern (#1499) if (_reward > 0) { token.safeTransfer(_investigator, _reward); } addSnapshot(info, - int256(_penalty)); } /** * @notice Get the value of locked tokens for a staker in the current and the next period * and find the shortest sub stake * @param _info Staker structure * @param _currentPeriod Current period * @param _nextPeriod Next period * @param _startPeriod Pre-calculated start period * @return currentLock Amount of tokens that locked in the current period and unlocked in the next period * @return nextLock Amount of tokens that locked in the next period and not locked in the current period * @return currentAndNextLock Amount of tokens that locked in the current period and in the next period * @return shortestSubStakeIndex Index of the shortest sub stake */ function getLockedTokensAndShortestSubStake( StakerInfo storage _info, uint16 _currentPeriod, uint16 _nextPeriod, uint16 _startPeriod ) internal view returns ( uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex ) { uint16 minDuration = MAX_UINT16; uint16 minLastPeriod = MAX_UINT16; shortestSubStakeIndex = MAX_SUB_STAKES; currentLock = 0; nextLock = 0; currentAndNextLock = 0; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (lastPeriod < subStake.firstPeriod) { continue; } if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _nextPeriod) { currentAndNextLock += subStake.lockedValue; } else if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod) { currentLock += subStake.lockedValue; } else if (subStake.firstPeriod <= _nextPeriod && lastPeriod >= _nextPeriod) { nextLock += subStake.lockedValue; } uint16 duration = lastPeriod - subStake.firstPeriod; if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod && (lastPeriod < minLastPeriod || lastPeriod == minLastPeriod && duration < minDuration)) { shortestSubStakeIndex = i; minDuration = duration; minLastPeriod = lastPeriod; } } } /** * @notice Decrease short sub stakes * @param _info Staker structure * @param _penalty Penalty rate * @param _decreasePeriod The period when the decrease begins * @param _startPeriod Pre-calculated start period * @param _shortestSubStakeIndex Index of the shortest period */ function decreaseSubStakes( StakerInfo storage _info, uint256 _penalty, uint16 _decreasePeriod, uint16 _startPeriod, uint256 _shortestSubStakeIndex ) internal { SubStakeInfo storage shortestSubStake = _info.subStakes[0]; uint16 minSubStakeLastPeriod = MAX_UINT16; uint16 minSubStakeDuration = MAX_UINT16; while(_penalty > 0) { if (_shortestSubStakeIndex < MAX_SUB_STAKES) { shortestSubStake = _info.subStakes[_shortestSubStakeIndex]; minSubStakeLastPeriod = getLastPeriodOfSubStake(shortestSubStake, _startPeriod); minSubStakeDuration = minSubStakeLastPeriod - shortestSubStake.firstPeriod; _shortestSubStakeIndex = MAX_SUB_STAKES; } else { (shortestSubStake, minSubStakeDuration, minSubStakeLastPeriod) = getShortestSubStake(_info, _decreasePeriod, _startPeriod); } if (minSubStakeDuration == MAX_UINT16) { break; } uint256 appliedPenalty = _penalty; if (_penalty < shortestSubStake.lockedValue) { shortestSubStake.lockedValue -= uint128(_penalty); saveOldSubStake(_info, shortestSubStake.firstPeriod, _penalty, _decreasePeriod); _penalty = 0; } else { shortestSubStake.lastPeriod = _decreasePeriod - 1; _penalty -= shortestSubStake.lockedValue; appliedPenalty = shortestSubStake.lockedValue; } if (_info.currentCommittedPeriod >= _decreasePeriod && _info.currentCommittedPeriod <= minSubStakeLastPeriod) { _lockedPerPeriod[_info.currentCommittedPeriod] -= appliedPenalty; } if (_info.nextCommittedPeriod >= _decreasePeriod && _info.nextCommittedPeriod <= minSubStakeLastPeriod) { _lockedPerPeriod[_info.nextCommittedPeriod] -= appliedPenalty; } } } /** * @notice Get the shortest sub stake * @param _info Staker structure * @param _currentPeriod Current period * @param _startPeriod Pre-calculated start period * @return shortestSubStake The shortest sub stake * @return minSubStakeDuration Duration of the shortest sub stake * @return minSubStakeLastPeriod Last period of the shortest sub stake */ function getShortestSubStake( StakerInfo storage _info, uint16 _currentPeriod, uint16 _startPeriod ) internal view returns ( SubStakeInfo storage shortestSubStake, uint16 minSubStakeDuration, uint16 minSubStakeLastPeriod ) { shortestSubStake = shortestSubStake; minSubStakeDuration = MAX_UINT16; minSubStakeLastPeriod = MAX_UINT16; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (lastPeriod < subStake.firstPeriod) { continue; } uint16 duration = lastPeriod - subStake.firstPeriod; if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod && (lastPeriod < minSubStakeLastPeriod || lastPeriod == minSubStakeLastPeriod && duration < minSubStakeDuration)) { shortestSubStake = subStake; minSubStakeDuration = duration; minSubStakeLastPeriod = lastPeriod; } } } /** * @notice Save the old sub stake values to prevent decreasing reward for the previous period * @dev Saving happens only if the previous period is committed * @param _info Staker structure * @param _firstPeriod First period of the old sub stake * @param _lockedValue Locked value of the old sub stake * @param _currentPeriod Current period, when the old sub stake is already unlocked */ function saveOldSubStake( StakerInfo storage _info, uint16 _firstPeriod, uint256 _lockedValue, uint16 _currentPeriod ) internal { // Check that the old sub stake should be saved bool oldCurrentCommittedPeriod = _info.currentCommittedPeriod != 0 && _info.currentCommittedPeriod < _currentPeriod; bool oldnextCommittedPeriod = _info.nextCommittedPeriod != 0 && _info.nextCommittedPeriod < _currentPeriod; bool crosscurrentCommittedPeriod = oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= _firstPeriod; bool crossnextCommittedPeriod = oldnextCommittedPeriod && _info.nextCommittedPeriod >= _firstPeriod; if (!crosscurrentCommittedPeriod && !crossnextCommittedPeriod) { return; } // Try to find already existent proper old sub stake uint16 previousPeriod = _currentPeriod - 1; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.lastPeriod == previousPeriod && ((crosscurrentCommittedPeriod == (oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= subStake.firstPeriod)) && (crossnextCommittedPeriod == (oldnextCommittedPeriod && _info.nextCommittedPeriod >= subStake.firstPeriod)))) { subStake.lockedValue += uint128(_lockedValue); return; } } saveSubStake(_info, _firstPeriod, previousPeriod, 0, _lockedValue); } //-------------Additional getters for stakers info------------- /** * @notice Return the length of the array of stakers */ function getStakersLength() external view returns (uint256) { return stakers.length; } /** * @notice Return the length of the array of sub stakes */ function getSubStakesLength(address _staker) external view returns (uint256) { return stakerInfo[_staker].subStakes.length; } /** * @notice Return the information about sub stake */ function getSubStakeInfo(address _staker, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (SubStakeInfo) // TODO "virtual" only for tests, probably will be removed after #1512 external view virtual returns ( uint16 firstPeriod, uint16 lastPeriod, uint16 unlockingDuration, uint128 lockedValue ) { SubStakeInfo storage info = stakerInfo[_staker].subStakes[_index]; firstPeriod = info.firstPeriod; lastPeriod = info.lastPeriod; unlockingDuration = info.unlockingDuration; lockedValue = info.lockedValue; } /** * @notice Return the length of the array of past downtime */ function getPastDowntimeLength(address _staker) external view returns (uint256) { return stakerInfo[_staker].pastDowntime.length; } /** * @notice Return the information about past downtime */ function getPastDowntime(address _staker, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (Downtime) external view returns (uint16 startPeriod, uint16 endPeriod) { Downtime storage downtime = stakerInfo[_staker].pastDowntime[_index]; startPeriod = downtime.startPeriod; endPeriod = downtime.endPeriod; } //------------------ ERC900 connectors ---------------------- function totalStakedForAt(address _owner, uint256 _blockNumber) public view override returns (uint256){ return stakerInfo[_owner].history.getValueAt(_blockNumber); } function totalStakedAt(uint256 _blockNumber) public view override returns (uint256){ return balanceHistory.getValueAt(_blockNumber); } function supportsHistory() external pure override returns (bool){ return true; } //------------------------Upgradeable------------------------ /** * @dev Get StakerInfo structure by delegatecall */ function delegateGetStakerInfo(address _target, bytes32 _staker) internal returns (StakerInfo memory result) { bytes32 memoryAddress = delegateGetData(_target, this.stakerInfo.selector, 1, _staker, 0); assembly { result := memoryAddress } } /** * @dev Get SubStakeInfo structure by delegatecall */ function delegateGetSubStakeInfo(address _target, bytes32 _staker, uint256 _index) internal returns (SubStakeInfo memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getSubStakeInfo.selector, 2, _staker, bytes32(_index)); assembly { result := memoryAddress } } /** * @dev Get Downtime structure by delegatecall */ function delegateGetPastDowntime(address _target, bytes32 _staker, uint256 _index) internal returns (Downtime memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getPastDowntime.selector, 2, _staker, bytes32(_index)); assembly { result := memoryAddress } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(delegateGet(_testTarget, this.lockedPerPeriod.selector, bytes32(bytes2(RESERVED_PERIOD))) == lockedPerPeriod(RESERVED_PERIOD)); require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(0))) == stakerFromWorker[address(0)]); require(delegateGet(_testTarget, this.getStakersLength.selector) == stakers.length); if (stakers.length == 0) { return; } address stakerAddress = stakers[0]; require(address(uint160(delegateGet(_testTarget, this.stakers.selector, 0))) == stakerAddress); StakerInfo storage info = stakerInfo[stakerAddress]; bytes32 staker = bytes32(uint256(stakerAddress)); StakerInfo memory infoToCheck = delegateGetStakerInfo(_testTarget, staker); require(infoToCheck.value == info.value && infoToCheck.currentCommittedPeriod == info.currentCommittedPeriod && infoToCheck.nextCommittedPeriod == info.nextCommittedPeriod && infoToCheck.flags == info.flags && infoToCheck.lastCommittedPeriod == info.lastCommittedPeriod && infoToCheck.completedWork == info.completedWork && infoToCheck.worker == info.worker && infoToCheck.workerStartPeriod == info.workerStartPeriod); require(delegateGet(_testTarget, this.getPastDowntimeLength.selector, staker) == info.pastDowntime.length); for (uint256 i = 0; i < info.pastDowntime.length && i < MAX_CHECKED_VALUES; i++) { Downtime storage downtime = info.pastDowntime[i]; Downtime memory downtimeToCheck = delegateGetPastDowntime(_testTarget, staker, i); require(downtimeToCheck.startPeriod == downtime.startPeriod && downtimeToCheck.endPeriod == downtime.endPeriod); } require(delegateGet(_testTarget, this.getSubStakesLength.selector, staker) == info.subStakes.length); for (uint256 i = 0; i < info.subStakes.length && i < MAX_CHECKED_VALUES; i++) { SubStakeInfo storage subStakeInfo = info.subStakes[i]; SubStakeInfo memory subStakeInfoToCheck = delegateGetSubStakeInfo(_testTarget, staker, i); require(subStakeInfoToCheck.firstPeriod == subStakeInfo.firstPeriod && subStakeInfoToCheck.lastPeriod == subStakeInfo.lastPeriod && subStakeInfoToCheck.unlockingDuration == subStakeInfo.unlockingDuration && subStakeInfoToCheck.lockedValue == subStakeInfo.lockedValue); } // it's not perfect because checks not only slot value but also decoding // at least without additional functions require(delegateGet(_testTarget, this.totalStakedForAt.selector, staker, bytes32(block.number)) == totalStakedForAt(stakerAddress, block.number)); require(delegateGet(_testTarget, this.totalStakedAt.selector, bytes32(block.number)) == totalStakedAt(block.number)); if (info.worker != address(0)) { require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(uint256(info.worker)))) == stakerFromWorker[info.worker]); } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // Create fake period _lockedPerPeriod[RESERVED_PERIOD] = 111; // Create fake worker stakerFromWorker[address(0)] = address(this); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; // Minimum interface to interact with Aragon's Aggregator interface IERC900History { function totalStakedForAt(address addr, uint256 blockNumber) external view returns (uint256); function totalStakedAt(uint256 blockNumber) external view returns (uint256); function supportsHistory() external pure returns (bool); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./NuCypherToken.sol"; import "../zeppelin/math/Math.sol"; import "./proxy/Upgradeable.sol"; import "./lib/AdditionalMath.sol"; import "../zeppelin/token/ERC20/SafeERC20.sol"; /** * @title Issuer * @notice Contract for calculation of issued tokens * @dev |v3.4.1| */ abstract contract Issuer is Upgradeable { using SafeERC20 for NuCypherToken; using AdditionalMath for uint32; event Donated(address indexed sender, uint256 value); /// Issuer is initialized with a reserved reward event Initialized(uint256 reservedReward); uint128 constant MAX_UINT128 = uint128(0) - 1; NuCypherToken public immutable token; uint128 public immutable totalSupply; // d * k2 uint256 public immutable mintingCoefficient; // k1 uint256 public immutable lockDurationCoefficient1; // k2 uint256 public immutable lockDurationCoefficient2; uint32 public immutable genesisSecondsPerPeriod; uint32 public immutable secondsPerPeriod; // kmax uint16 public immutable maximumRewardedPeriods; uint256 public immutable firstPhaseMaxIssuance; uint256 public immutable firstPhaseTotalSupply; /** * Current supply is used in the minting formula and is stored to prevent different calculation * for stakers which get reward in the same period. There are two values - * supply for previous period (used in formula) and supply for current period which accumulates value * before end of period. */ uint128 public previousPeriodSupply; uint128 public currentPeriodSupply; uint16 public currentMintingPeriod; /** * @notice Constructor sets address of token contract and coefficients for minting * @dev Minting formula for one sub-stake in one period for the first phase firstPhaseMaxIssuance * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2 * @dev Minting formula for one sub-stake in one period for the second phase (totalSupply - currentSupply) / d * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2 if allLockedPeriods > maximumRewardedPeriods then allLockedPeriods = maximumRewardedPeriods * @param _token Token contract * @param _genesisHoursPerPeriod Size of period in hours at genesis * @param _hoursPerPeriod Size of period in hours * @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays, * only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2. * See Equation 10 in Staking Protocol & Economics paper * @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier) * where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration * no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1. * See Equation 8 in Staking Protocol & Economics paper. * @param _firstPhaseTotalSupply Total supply for the first phase * @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1. * See Equation 7 in Staking Protocol & Economics paper. */ constructor( NuCypherToken _token, uint32 _genesisHoursPerPeriod, uint32 _hoursPerPeriod, uint256 _issuanceDecayCoefficient, uint256 _lockDurationCoefficient1, uint256 _lockDurationCoefficient2, uint16 _maximumRewardedPeriods, uint256 _firstPhaseTotalSupply, uint256 _firstPhaseMaxIssuance ) { uint256 localTotalSupply = _token.totalSupply(); require(localTotalSupply > 0 && _issuanceDecayCoefficient != 0 && _hoursPerPeriod != 0 && _genesisHoursPerPeriod != 0 && _genesisHoursPerPeriod <= _hoursPerPeriod && _lockDurationCoefficient1 != 0 && _lockDurationCoefficient2 != 0 && _maximumRewardedPeriods != 0); require(localTotalSupply <= uint256(MAX_UINT128), "Token contract has supply more than supported"); uint256 maxLockDurationCoefficient = _maximumRewardedPeriods + _lockDurationCoefficient1; uint256 localMintingCoefficient = _issuanceDecayCoefficient * _lockDurationCoefficient2; require(maxLockDurationCoefficient > _maximumRewardedPeriods && localMintingCoefficient / _issuanceDecayCoefficient == _lockDurationCoefficient2 && // worst case for `totalLockedValue * d * k2`, when totalLockedValue == totalSupply localTotalSupply * localMintingCoefficient / localTotalSupply == localMintingCoefficient && // worst case for `(totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax))`, // when currentSupply == 0, lockedValue == totalSupply localTotalSupply * localTotalSupply * maxLockDurationCoefficient / localTotalSupply / localTotalSupply == maxLockDurationCoefficient, "Specified parameters cause overflow"); require(maxLockDurationCoefficient <= _lockDurationCoefficient2, "Resulting locking duration coefficient must be less than 1"); require(_firstPhaseTotalSupply <= localTotalSupply, "Too many tokens for the first phase"); require(_firstPhaseMaxIssuance <= _firstPhaseTotalSupply, "Reward for the first phase is too high"); token = _token; secondsPerPeriod = _hoursPerPeriod.mul32(1 hours); genesisSecondsPerPeriod = _genesisHoursPerPeriod.mul32(1 hours); lockDurationCoefficient1 = _lockDurationCoefficient1; lockDurationCoefficient2 = _lockDurationCoefficient2; maximumRewardedPeriods = _maximumRewardedPeriods; firstPhaseTotalSupply = _firstPhaseTotalSupply; firstPhaseMaxIssuance = _firstPhaseMaxIssuance; totalSupply = uint128(localTotalSupply); mintingCoefficient = localMintingCoefficient; } /** * @dev Checks contract initialization */ modifier isInitialized() { require(currentMintingPeriod != 0); _; } /** * @return Number of current period */ function getCurrentPeriod() public view returns (uint16) { return uint16(block.timestamp / secondsPerPeriod); } /** * @return Recalculate period value using new basis */ function recalculatePeriod(uint16 _period) internal view returns (uint16) { return uint16(uint256(_period) * genesisSecondsPerPeriod / secondsPerPeriod); } /** * @notice Initialize reserved tokens for reward */ function initialize(uint256 _reservedReward, address _sourceOfFunds) external onlyOwner { require(currentMintingPeriod == 0); // Reserved reward must be sufficient for at least one period of the first phase require(firstPhaseMaxIssuance <= _reservedReward); currentMintingPeriod = getCurrentPeriod(); currentPeriodSupply = totalSupply - uint128(_reservedReward); previousPeriodSupply = currentPeriodSupply; token.safeTransferFrom(_sourceOfFunds, address(this), _reservedReward); emit Initialized(_reservedReward); } /** * @notice Function to mint tokens for one period. * @param _currentPeriod Current period number. * @param _lockedValue The amount of tokens that were locked by user in specified period. * @param _totalLockedValue The amount of tokens that were locked by all users in specified period. * @param _allLockedPeriods The max amount of periods during which tokens will be locked after specified period. * @return amount Amount of minted tokens. */ function mint( uint16 _currentPeriod, uint256 _lockedValue, uint256 _totalLockedValue, uint16 _allLockedPeriods ) internal returns (uint256 amount) { if (currentPeriodSupply == totalSupply) { return 0; } if (_currentPeriod > currentMintingPeriod) { previousPeriodSupply = currentPeriodSupply; currentMintingPeriod = _currentPeriod; } uint256 currentReward; uint256 coefficient; // first phase // firstPhaseMaxIssuance * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * k2) if (previousPeriodSupply + firstPhaseMaxIssuance <= firstPhaseTotalSupply) { currentReward = firstPhaseMaxIssuance; coefficient = lockDurationCoefficient2; // second phase // (totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * d * k2) } else { currentReward = totalSupply - previousPeriodSupply; coefficient = mintingCoefficient; } uint256 allLockedPeriods = AdditionalMath.min16(_allLockedPeriods, maximumRewardedPeriods) + lockDurationCoefficient1; amount = (uint256(currentReward) * _lockedValue * allLockedPeriods) / (_totalLockedValue * coefficient); // rounding the last reward uint256 maxReward = getReservedReward(); if (amount == 0) { amount = 1; } else if (amount > maxReward) { amount = maxReward; } currentPeriodSupply += uint128(amount); } /** * @notice Return tokens for future minting * @param _amount Amount of tokens */ function unMint(uint256 _amount) internal { previousPeriodSupply -= uint128(_amount); currentPeriodSupply -= uint128(_amount); } /** * @notice Donate sender's tokens. Amount of tokens will be returned for future minting * @param _value Amount to donate */ function donate(uint256 _value) external isInitialized { token.safeTransferFrom(msg.sender, address(this), _value); unMint(_value); emit Donated(msg.sender, _value); } /** * @notice Returns the number of tokens that can be minted */ function getReservedReward() public view returns (uint256) { return totalSupply - currentPeriodSupply; } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(uint16(delegateGet(_testTarget, this.currentMintingPeriod.selector)) == currentMintingPeriod); require(uint128(delegateGet(_testTarget, this.previousPeriodSupply.selector)) == previousPeriodSupply); require(uint128(delegateGet(_testTarget, this.currentPeriodSupply.selector)) == currentPeriodSupply); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // recalculate currentMintingPeriod if needed if (currentMintingPeriod > getCurrentPeriod()) { currentMintingPeriod = recalculatePeriod(currentMintingPeriod); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/token/ERC20/ERC20.sol"; import "../zeppelin/token/ERC20/ERC20Detailed.sol"; /** * @title NuCypherToken * @notice ERC20 token * @dev Optional approveAndCall() functionality to notify a contract if an approve() has occurred. */ contract NuCypherToken is ERC20, ERC20Detailed('NuCypher', 'NU', 18) { /** * @notice Set amount of tokens * @param _totalSupplyOfTokens Total number of tokens */ constructor (uint256 _totalSupplyOfTokens) { _mint(msg.sender, _totalSupplyOfTokens); } /** * @notice Approves and then calls the receiving contract * * @dev call the receiveApproval function on the contract you want to be notified. * receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) */ function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external returns (bool success) { approve(_spender, _value); TokenRecipient(_spender).receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } /** * @dev Interface to use the receiveApproval method */ interface TokenRecipient { /** * @notice Receives a notification of approval of the transfer * @param _from Sender of approval * @param _value The amount of tokens to be spent * @param _tokenContract Address of the token contract * @param _extraData Extra data */ function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes calldata _extraData) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view override returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view override returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public override returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(value == 0 || _allowed[msg.sender][spender] == 0); _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public override returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ abstract contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title Math * @dev Assorted math operations */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; /** * @notice Base contract for upgradeable contract * @dev Inherited contract should implement verifyState(address) method by checking storage variables * (see verifyState(address) in Dispatcher). Also contract should implement finishUpgrade(address) * if it is using constructor parameters by coping this parameters to the dispatcher storage */ abstract contract Upgradeable is Ownable { event StateVerified(address indexed testTarget, address sender); event UpgradeFinished(address indexed target, address sender); /** * @dev Contracts at the target must reserve the same location in storage for this address as in Dispatcher * Stored data actually lives in the Dispatcher * However the storage layout is specified here in the implementing contracts */ address public target; /** * @dev Previous contract address (if available). Used for rollback */ address public previousTarget; /** * @dev Upgrade status. Explicit `uint8` type is used instead of `bool` to save gas by excluding 0 value */ uint8 public isUpgrade; /** * @dev Guarantees that next slot will be separated from the previous */ uint256 stubSlot; /** * @dev Constants for `isUpgrade` field */ uint8 constant UPGRADE_FALSE = 1; uint8 constant UPGRADE_TRUE = 2; /** * @dev Checks that function executed while upgrading * Recommended to add to `verifyState` and `finishUpgrade` methods */ modifier onlyWhileUpgrading() { require(isUpgrade == UPGRADE_TRUE); _; } /** * @dev Method for verifying storage state. * Should check that new target contract returns right storage value */ function verifyState(address _testTarget) public virtual onlyWhileUpgrading { emit StateVerified(_testTarget, msg.sender); } /** * @dev Copy values from the new target to the current storage * @param _target New target contract address */ function finishUpgrade(address _target) public virtual onlyWhileUpgrading { emit UpgradeFinished(_target, msg.sender); } /** * @dev Base method to get data * @param _target Target to call * @param _selector Method selector * @param _numberOfArguments Number of used arguments * @param _argument1 First method argument * @param _argument2 Second method argument * @return memoryAddress Address in memory where the data is located */ function delegateGetData( address _target, bytes4 _selector, uint8 _numberOfArguments, bytes32 _argument1, bytes32 _argument2 ) internal returns (bytes32 memoryAddress) { assembly { memoryAddress := mload(0x40) mstore(memoryAddress, _selector) if gt(_numberOfArguments, 0) { mstore(add(memoryAddress, 0x04), _argument1) } if gt(_numberOfArguments, 1) { mstore(add(memoryAddress, 0x24), _argument2) } switch delegatecall(gas(), _target, memoryAddress, add(0x04, mul(0x20, _numberOfArguments)), 0, 0) case 0 { revert(memoryAddress, 0) } default { returndatacopy(memoryAddress, 0x0, returndatasize()) } } } /** * @dev Call "getter" without parameters. * Result should not exceed 32 bytes */ function delegateGet(address _target, bytes4 _selector) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 0, 0, 0); assembly { result := mload(memoryAddress) } } /** * @dev Call "getter" with one parameter. * Result should not exceed 32 bytes */ function delegateGet(address _target, bytes4 _selector, bytes32 _argument) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 1, _argument, 0); assembly { result := mload(memoryAddress) } } /** * @dev Call "getter" with two parameters. * Result should not exceed 32 bytes */ function delegateGet( address _target, bytes4 _selector, bytes32 _argument1, bytes32 _argument2 ) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 2, _argument1, _argument2); assembly { result := mload(memoryAddress) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public virtual onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/math/SafeMath.sol"; /** * @notice Additional math operations */ library AdditionalMath { using SafeMath for uint256; function max16(uint16 a, uint16 b) internal pure returns (uint16) { return a >= b ? a : b; } function min16(uint16 a, uint16 b) internal pure returns (uint16) { return a < b ? a : b; } /** * @notice Division and ceil */ function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { return (a.add(b) - 1) / b; } /** * @dev Adds signed value to unsigned value, throws on overflow. */ function addSigned(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return a.add(uint256(b)); } else { return a.sub(uint256(-b)); } } /** * @dev Subtracts signed value from unsigned value, throws on overflow. */ function subSigned(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return a.sub(uint256(b)); } else { return a.add(uint256(-b)); } } /** * @dev Multiplies two numbers, throws on overflow. */ function mul32(uint32 a, uint32 b) internal pure returns (uint32) { if (a == 0) { return 0; } uint32 c = a * b; assert(c / a == b); return c; } /** * @dev Adds two numbers, throws on overflow. */ function add16(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a + b; assert(c >= a); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub16(uint16 a, uint16 b) internal pure returns (uint16) { assert(b <= a); return a - b; } /** * @dev Adds signed value to unsigned value, throws on overflow. */ function addSigned16(uint16 a, int16 b) internal pure returns (uint16) { if (b >= 0) { return add16(a, uint16(b)); } else { return sub16(a, uint16(-b)); } } /** * @dev Subtracts signed value from unsigned value, throws on overflow. */ function subSigned16(uint16 a, int16 b) internal pure returns (uint16) { if (b >= 0) { return sub16(a, uint16(b)); } else { return add16(a, uint16(-b)); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @dev Taken from https://github.com/ethereum/solidity-examples/blob/master/src/bits/Bits.sol */ library Bits { uint256 internal constant ONE = uint256(1); /** * @notice Sets the bit at the given 'index' in 'self' to: * '1' - if the bit is '0' * '0' - if the bit is '1' * @return The modified value */ function toggleBit(uint256 self, uint8 index) internal pure returns (uint256) { return self ^ ONE << index; } /** * @notice Get the value of the bit at the given 'index' in 'self'. */ function bit(uint256 self, uint8 index) internal pure returns (uint8) { return uint8(self >> index & 1); } /** * @notice Check if the bit at the given 'index' in 'self' is set. * @return 'true' - if the value of the bit is '1', * 'false' - if the value of the bit is '0' */ function bitSet(uint256 self, uint8 index) internal pure returns (bool) { return self >> index & 1 == 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @title Snapshot * @notice Manages snapshots of size 128 bits (32 bits for timestamp, 96 bits for value) * 96 bits is enough for storing NU token values, and 32 bits should be OK for block numbers * @dev Since each storage slot can hold two snapshots, new slots are allocated every other TX. Thus, gas cost of adding snapshots is 51400 and 36400 gas, alternately. * Based on Aragon's Checkpointing (https://https://github.com/aragonone/voting-connectors/blob/master/shared/contract-utils/contracts/Checkpointing.sol) * On average, adding snapshots spends ~6500 less gas than the 256-bit checkpoints of Aragon's Checkpointing */ library Snapshot { function encodeSnapshot(uint32 _time, uint96 _value) internal pure returns(uint128) { return uint128(uint256(_time) << 96 | uint256(_value)); } function decodeSnapshot(uint128 _snapshot) internal pure returns(uint32 time, uint96 value){ time = uint32(bytes4(bytes16(_snapshot))); value = uint96(_snapshot); } function addSnapshot(uint128[] storage _self, uint256 _value) internal { addSnapshot(_self, block.number, _value); } function addSnapshot(uint128[] storage _self, uint256 _time, uint256 _value) internal { uint256 length = _self.length; if (length != 0) { (uint32 currentTime, ) = decodeSnapshot(_self[length - 1]); if (uint32(_time) == currentTime) { _self[length - 1] = encodeSnapshot(uint32(_time), uint96(_value)); return; } else if (uint32(_time) < currentTime){ revert(); } } _self.push(encodeSnapshot(uint32(_time), uint96(_value))); } function lastSnapshot(uint128[] storage _self) internal view returns (uint32, uint96) { uint256 length = _self.length; if (length > 0) { return decodeSnapshot(_self[length - 1]); } return (0, 0); } function lastValue(uint128[] storage _self) internal view returns (uint96) { (, uint96 value) = lastSnapshot(_self); return value; } function getValueAt(uint128[] storage _self, uint256 _time256) internal view returns (uint96) { uint32 _time = uint32(_time256); uint256 length = _self.length; // Short circuit if there's no checkpoints yet // Note that this also lets us avoid using SafeMath later on, as we've established that // there must be at least one checkpoint if (length == 0) { return 0; } // Check last checkpoint uint256 lastIndex = length - 1; (uint32 snapshotTime, uint96 snapshotValue) = decodeSnapshot(_self[length - 1]); if (_time >= snapshotTime) { return snapshotValue; } // Check first checkpoint (if not already checked with the above check on last) (snapshotTime, snapshotValue) = decodeSnapshot(_self[0]); if (length == 1 || _time < snapshotTime) { return 0; } // Do binary search // As we've already checked both ends, we don't need to check the last checkpoint again uint256 low = 0; uint256 high = lastIndex - 1; uint32 midTime; uint96 midValue; while (high > low) { uint256 mid = (high + low + 1) / 2; // average, ceil round (midTime, midValue) = decodeSnapshot(_self[mid]); if (_time > midTime) { low = mid; } else if (_time < midTime) { // Note that we don't need SafeMath here because mid must always be greater than 0 // from the while condition high = mid - 1; } else { // _time == midTime return midValue; } } (, snapshotValue) = decodeSnapshot(_self[low]); return snapshotValue; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; interface IForwarder { function isForwarder() external pure returns (bool); function canForward(address sender, bytes calldata evmCallScript) external view returns (bool); function forward(bytes calldata evmCallScript) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; interface TokenManager { function mint(address _receiver, uint256 _amount) external; function issue(uint256 _amount) external; function assign(address _receiver, uint256 _amount) external; function burn(address _holder, uint256 _amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; import "./IForwarder.sol"; // Interface for Voting contract, as found in https://github.com/aragon/aragon-apps/blob/master/apps/voting/contracts/Voting.sol interface Voting is IForwarder{ enum VoterState { Absent, Yea, Nay } // Public getters function token() external returns (address); function supportRequiredPct() external returns (uint64); function minAcceptQuorumPct() external returns (uint64); function voteTime() external returns (uint64); function votesLength() external returns (uint256); // Setters function changeSupportRequiredPct(uint64 _supportRequiredPct) external; function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external; // Creating new votes function newVote(bytes calldata _executionScript, string memory _metadata) external returns (uint256 voteId); function newVote(bytes calldata _executionScript, string memory _metadata, bool _castVote, bool _executesIfDecided) external returns (uint256 voteId); // Voting function canVote(uint256 _voteId, address _voter) external view returns (bool); function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external; // Executing a passed vote function canExecute(uint256 _voteId) external view returns (bool); function executeVote(uint256 _voteId) external; // Additional info function getVote(uint256 _voteId) external view returns ( bool open, bool executed, uint64 startDate, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 yea, uint256 nay, uint256 votingPower, bytes memory script ); function getVoterState(uint256 _voteId, address _voter) external view returns (VoterState); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/math/SafeMath.sol"; /** * @notice Multi-signature contract with off-chain signing */ contract MultiSig { using SafeMath for uint256; event Executed(address indexed sender, uint256 indexed nonce, address indexed destination, uint256 value); event OwnerAdded(address indexed owner); event OwnerRemoved(address indexed owner); event RequirementChanged(uint16 required); uint256 constant public MAX_OWNER_COUNT = 50; uint256 public nonce; uint8 public required; mapping (address => bool) public isOwner; address[] public owners; /** * @notice Only this contract can call method */ modifier onlyThisContract() { require(msg.sender == address(this)); _; } receive() external payable {} /** * @param _required Number of required signings * @param _owners List of initial owners. */ constructor (uint8 _required, address[] memory _owners) { require(_owners.length <= MAX_OWNER_COUNT && _required <= _owners.length && _required > 0); for (uint256 i = 0; i < _owners.length; i++) { address owner = _owners[i]; require(!isOwner[owner] && owner != address(0)); isOwner[owner] = true; } owners = _owners; required = _required; } /** * @notice Get unsigned hash for transaction parameters * @dev Follows ERC191 signature scheme: https://github.com/ethereum/EIPs/issues/191 * @param _sender Trustee who will execute the transaction * @param _destination Destination address * @param _value Amount of ETH to transfer * @param _data Call data * @param _nonce Nonce */ function getUnsignedTransactionHash( address _sender, address _destination, uint256 _value, bytes memory _data, uint256 _nonce ) public view returns (bytes32) { return keccak256( abi.encodePacked(byte(0x19), byte(0), address(this), _sender, _destination, _value, _data, _nonce)); } /** * @dev Note that address recovered from signatures must be strictly increasing * @param _sigV Array of signatures values V * @param _sigR Array of signatures values R * @param _sigS Array of signatures values S * @param _destination Destination address * @param _value Amount of ETH to transfer * @param _data Call data */ function execute( uint8[] calldata _sigV, bytes32[] calldata _sigR, bytes32[] calldata _sigS, address _destination, uint256 _value, bytes calldata _data ) external { require(_sigR.length >= required && _sigR.length == _sigS.length && _sigR.length == _sigV.length); bytes32 txHash = getUnsignedTransactionHash(msg.sender, _destination, _value, _data, nonce); address lastAdd = address(0); for (uint256 i = 0; i < _sigR.length; i++) { address recovered = ecrecover(txHash, _sigV[i], _sigR[i], _sigS[i]); require(recovered > lastAdd && isOwner[recovered]); lastAdd = recovered; } emit Executed(msg.sender, nonce, _destination, _value); nonce = nonce.add(1); (bool callSuccess,) = _destination.call{value: _value}(_data); require(callSuccess); } /** * @notice Allows to add a new owner * @dev Transaction has to be sent by `execute` method. * @param _owner Address of new owner */ function addOwner(address _owner) external onlyThisContract { require(owners.length < MAX_OWNER_COUNT && _owner != address(0) && !isOwner[_owner]); isOwner[_owner] = true; owners.push(_owner); emit OwnerAdded(_owner); } /** * @notice Allows to remove an owner * @dev Transaction has to be sent by `execute` method. * @param _owner Address of owner */ function removeOwner(address _owner) external onlyThisContract { require(owners.length > required && isOwner[_owner]); isOwner[_owner] = false; for (uint256 i = 0; i < owners.length - 1; i++) { if (owners[i] == _owner) { owners[i] = owners[owners.length - 1]; break; } } owners.pop(); emit OwnerRemoved(_owner); } /** * @notice Returns the number of owners of this MultiSig */ function getNumberOfOwners() external view returns (uint256) { return owners.length; } /** * @notice Allows to change the number of required signatures * @dev Transaction has to be sent by `execute` method * @param _required Number of required signatures */ function changeRequirement(uint8 _required) external onlyThisContract { require(_required <= owners.length && _required > 0); required = _required; emit RequirementChanged(_required); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/token/ERC20/SafeERC20.sol"; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/math/Math.sol"; import "../zeppelin/utils/Address.sol"; import "./lib/AdditionalMath.sol"; import "./lib/SignatureVerifier.sol"; import "./StakingEscrow.sol"; import "./NuCypherToken.sol"; import "./proxy/Upgradeable.sol"; /** * @title PolicyManager * @notice Contract holds policy data and locks accrued policy fees * @dev |v6.3.1| */ contract PolicyManager is Upgradeable { using SafeERC20 for NuCypherToken; using SafeMath for uint256; using AdditionalMath for uint256; using AdditionalMath for int256; using AdditionalMath for uint16; using Address for address payable; event PolicyCreated( bytes16 indexed policyId, address indexed sponsor, address indexed owner, uint256 feeRate, uint64 startTimestamp, uint64 endTimestamp, uint256 numberOfNodes ); event ArrangementRevoked( bytes16 indexed policyId, address indexed sender, address indexed node, uint256 value ); event RefundForArrangement( bytes16 indexed policyId, address indexed sender, address indexed node, uint256 value ); event PolicyRevoked(bytes16 indexed policyId, address indexed sender, uint256 value); event RefundForPolicy(bytes16 indexed policyId, address indexed sender, uint256 value); event MinFeeRateSet(address indexed node, uint256 value); // TODO #1501 // Range range event FeeRateRangeSet(address indexed sender, uint256 min, uint256 defaultValue, uint256 max); event Withdrawn(address indexed node, address indexed recipient, uint256 value); struct ArrangementInfo { address node; uint256 indexOfDowntimePeriods; uint16 lastRefundedPeriod; } struct Policy { bool disabled; address payable sponsor; address owner; uint128 feeRate; uint64 startTimestamp; uint64 endTimestamp; uint256 reservedSlot1; uint256 reservedSlot2; uint256 reservedSlot3; uint256 reservedSlot4; uint256 reservedSlot5; ArrangementInfo[] arrangements; } struct NodeInfo { uint128 fee; uint16 previousFeePeriod; uint256 feeRate; uint256 minFeeRate; mapping (uint16 => int256) stub; // former slot for feeDelta mapping (uint16 => int256) feeDelta; } // TODO used only for `delegateGetNodeInfo`, probably will be removed after #1512 struct MemoryNodeInfo { uint128 fee; uint16 previousFeePeriod; uint256 feeRate; uint256 minFeeRate; } struct Range { uint128 min; uint128 defaultValue; uint128 max; } bytes16 internal constant RESERVED_POLICY_ID = bytes16(0); address internal constant RESERVED_NODE = address(0); uint256 internal constant MAX_BALANCE = uint256(uint128(0) - 1); // controlled overflow to get max int256 int256 public constant DEFAULT_FEE_DELTA = int256((uint256(0) - 1) >> 1); StakingEscrow public immutable escrow; uint32 public immutable genesisSecondsPerPeriod; uint32 public immutable secondsPerPeriod; mapping (bytes16 => Policy) public policies; mapping (address => NodeInfo) public nodes; Range public feeRateRange; uint64 public resetTimestamp; /** * @notice Constructor sets address of the escrow contract * @dev Put same address in both inputs variables except when migration is happening * @param _escrowDispatcher Address of escrow dispatcher * @param _escrowImplementation Address of escrow implementation */ constructor(StakingEscrow _escrowDispatcher, StakingEscrow _escrowImplementation) { escrow = _escrowDispatcher; // if the input address is not the StakingEscrow then calling `secondsPerPeriod` will throw error uint32 localSecondsPerPeriod = _escrowImplementation.secondsPerPeriod(); require(localSecondsPerPeriod > 0); secondsPerPeriod = localSecondsPerPeriod; uint32 localgenesisSecondsPerPeriod = _escrowImplementation.genesisSecondsPerPeriod(); require(localgenesisSecondsPerPeriod > 0); genesisSecondsPerPeriod = localgenesisSecondsPerPeriod; // handle case when we deployed new StakingEscrow but not yet upgraded if (_escrowDispatcher != _escrowImplementation) { require(_escrowDispatcher.secondsPerPeriod() == localSecondsPerPeriod || _escrowDispatcher.secondsPerPeriod() == localgenesisSecondsPerPeriod); } } /** * @dev Checks that sender is the StakingEscrow contract */ modifier onlyEscrowContract() { require(msg.sender == address(escrow)); _; } /** * @return Number of current period */ function getCurrentPeriod() public view returns (uint16) { return uint16(block.timestamp / secondsPerPeriod); } /** * @return Recalculate period value using new basis */ function recalculatePeriod(uint16 _period) internal view returns (uint16) { return uint16(uint256(_period) * genesisSecondsPerPeriod / secondsPerPeriod); } /** * @notice Register a node * @param _node Node address * @param _period Initial period */ function register(address _node, uint16 _period) external onlyEscrowContract { NodeInfo storage nodeInfo = nodes[_node]; require(nodeInfo.previousFeePeriod == 0 && _period < getCurrentPeriod()); nodeInfo.previousFeePeriod = _period; } /** * @notice Migrate from the old period length to the new one * @param _node Node address */ function migrate(address _node) external onlyEscrowContract { NodeInfo storage nodeInfo = nodes[_node]; // with previous period length any previousFeePeriod will be greater than current period // this is a sign of not migrated node require(nodeInfo.previousFeePeriod >= getCurrentPeriod()); nodeInfo.previousFeePeriod = recalculatePeriod(nodeInfo.previousFeePeriod); nodeInfo.feeRate = 0; } /** * @notice Set minimum, default & maximum fee rate for all stakers and all policies ('global fee range') */ // TODO # 1501 // function setFeeRateRange(Range calldata _range) external onlyOwner { function setFeeRateRange(uint128 _min, uint128 _default, uint128 _max) external onlyOwner { require(_min <= _default && _default <= _max); feeRateRange = Range(_min, _default, _max); emit FeeRateRangeSet(msg.sender, _min, _default, _max); } /** * @notice Set the minimum acceptable fee rate (set by staker for their associated worker) * @dev Input value must fall within `feeRateRange` (global fee range) */ function setMinFeeRate(uint256 _minFeeRate) external { require(_minFeeRate >= feeRateRange.min && _minFeeRate <= feeRateRange.max, "The staker's min fee rate must fall within the global fee range"); NodeInfo storage nodeInfo = nodes[msg.sender]; if (nodeInfo.minFeeRate == _minFeeRate) { return; } nodeInfo.minFeeRate = _minFeeRate; emit MinFeeRateSet(msg.sender, _minFeeRate); } /** * @notice Get the minimum acceptable fee rate (set by staker for their associated worker) */ function getMinFeeRate(NodeInfo storage _nodeInfo) internal view returns (uint256) { // if minFeeRate has not been set or chosen value falls outside the global fee range // a default value is returned instead if (_nodeInfo.minFeeRate == 0 || _nodeInfo.minFeeRate < feeRateRange.min || _nodeInfo.minFeeRate > feeRateRange.max) { return feeRateRange.defaultValue; } else { return _nodeInfo.minFeeRate; } } /** * @notice Get the minimum acceptable fee rate (set by staker for their associated worker) */ function getMinFeeRate(address _node) public view returns (uint256) { NodeInfo storage nodeInfo = nodes[_node]; return getMinFeeRate(nodeInfo); } /** * @notice Create policy * @dev Generate policy id before creation * @param _policyId Policy id * @param _policyOwner Policy owner. Zero address means sender is owner * @param _endTimestamp End timestamp of the policy in seconds * @param _nodes Nodes that will handle policy */ function createPolicy( bytes16 _policyId, address _policyOwner, uint64 _endTimestamp, address[] calldata _nodes ) external payable { require( _endTimestamp > block.timestamp && msg.value > 0 ); require(address(this).balance <= MAX_BALANCE); uint16 currentPeriod = getCurrentPeriod(); uint16 endPeriod = uint16(_endTimestamp / secondsPerPeriod) + 1; uint256 numberOfPeriods = endPeriod - currentPeriod; uint128 feeRate = uint128(msg.value.div(_nodes.length) / numberOfPeriods); require(feeRate > 0 && feeRate * numberOfPeriods * _nodes.length == msg.value); Policy storage policy = createPolicy(_policyId, _policyOwner, _endTimestamp, feeRate, _nodes.length); for (uint256 i = 0; i < _nodes.length; i++) { address node = _nodes[i]; addFeeToNode(currentPeriod, endPeriod, node, feeRate, int256(feeRate)); policy.arrangements.push(ArrangementInfo(node, 0, 0)); } } /** * @notice Create multiple policies with the same owner, nodes and length * @dev Generate policy ids before creation * @param _policyIds Policy ids * @param _policyOwner Policy owner. Zero address means sender is owner * @param _endTimestamp End timestamp of all policies in seconds * @param _nodes Nodes that will handle all policies */ function createPolicies( bytes16[] calldata _policyIds, address _policyOwner, uint64 _endTimestamp, address[] calldata _nodes ) external payable { require( _endTimestamp > block.timestamp && msg.value > 0 && _policyIds.length > 1 ); require(address(this).balance <= MAX_BALANCE); uint16 currentPeriod = getCurrentPeriod(); uint16 endPeriod = uint16(_endTimestamp / secondsPerPeriod) + 1; uint256 numberOfPeriods = endPeriod - currentPeriod; uint128 feeRate = uint128(msg.value.div(_nodes.length) / numberOfPeriods / _policyIds.length); require(feeRate > 0 && feeRate * numberOfPeriods * _nodes.length * _policyIds.length == msg.value); for (uint256 i = 0; i < _policyIds.length; i++) { Policy storage policy = createPolicy(_policyIds[i], _policyOwner, _endTimestamp, feeRate, _nodes.length); for (uint256 j = 0; j < _nodes.length; j++) { policy.arrangements.push(ArrangementInfo(_nodes[j], 0, 0)); } } int256 fee = int256(_policyIds.length * feeRate); for (uint256 i = 0; i < _nodes.length; i++) { address node = _nodes[i]; addFeeToNode(currentPeriod, endPeriod, node, feeRate, fee); } } /** * @notice Create policy * @param _policyId Policy id * @param _policyOwner Policy owner. Zero address means sender is owner * @param _endTimestamp End timestamp of the policy in seconds * @param _feeRate Fee rate for policy * @param _nodesLength Number of nodes that will handle policy */ function createPolicy( bytes16 _policyId, address _policyOwner, uint64 _endTimestamp, uint128 _feeRate, uint256 _nodesLength ) internal returns (Policy storage policy) { policy = policies[_policyId]; require( _policyId != RESERVED_POLICY_ID && policy.feeRate == 0 && !policy.disabled ); policy.sponsor = msg.sender; policy.startTimestamp = uint64(block.timestamp); policy.endTimestamp = _endTimestamp; policy.feeRate = _feeRate; if (_policyOwner != msg.sender && _policyOwner != address(0)) { policy.owner = _policyOwner; } emit PolicyCreated( _policyId, msg.sender, _policyOwner == address(0) ? msg.sender : _policyOwner, _feeRate, policy.startTimestamp, policy.endTimestamp, _nodesLength ); } /** * @notice Increase fee rate for specified node * @param _currentPeriod Current period * @param _endPeriod End period of policy * @param _node Node that will handle policy * @param _feeRate Fee rate for one policy * @param _overallFeeRate Fee rate for all policies */ function addFeeToNode( uint16 _currentPeriod, uint16 _endPeriod, address _node, uint128 _feeRate, int256 _overallFeeRate ) internal { require(_node != RESERVED_NODE); NodeInfo storage nodeInfo = nodes[_node]; require(nodeInfo.previousFeePeriod != 0 && nodeInfo.previousFeePeriod < _currentPeriod && _feeRate >= getMinFeeRate(nodeInfo)); // Check default value for feeDelta if (nodeInfo.feeDelta[_currentPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[_currentPeriod] = _overallFeeRate; } else { // Overflow protection removed, because ETH total supply less than uint255/int256 nodeInfo.feeDelta[_currentPeriod] += _overallFeeRate; } if (nodeInfo.feeDelta[_endPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[_endPeriod] = -_overallFeeRate; } else { nodeInfo.feeDelta[_endPeriod] -= _overallFeeRate; } // Reset to default value if needed if (nodeInfo.feeDelta[_currentPeriod] == 0) { nodeInfo.feeDelta[_currentPeriod] = DEFAULT_FEE_DELTA; } if (nodeInfo.feeDelta[_endPeriod] == 0) { nodeInfo.feeDelta[_endPeriod] = DEFAULT_FEE_DELTA; } } /** * @notice Get policy owner */ function getPolicyOwner(bytes16 _policyId) public view returns (address) { Policy storage policy = policies[_policyId]; return policy.owner == address(0) ? policy.sponsor : policy.owner; } /** * @notice Call from StakingEscrow to update node info once per period. * Set default `feeDelta` value for specified period and update node fee * @param _node Node address * @param _processedPeriod1 Processed period * @param _processedPeriod2 Processed period * @param _periodToSetDefault Period to set */ function ping( address _node, uint16 _processedPeriod1, uint16 _processedPeriod2, uint16 _periodToSetDefault ) external onlyEscrowContract { NodeInfo storage node = nodes[_node]; // protection from calling not migrated node, see migrate() require(node.previousFeePeriod <= getCurrentPeriod()); if (_processedPeriod1 != 0) { updateFee(node, _processedPeriod1); } if (_processedPeriod2 != 0) { updateFee(node, _processedPeriod2); } // This code increases gas cost for node in trade of decreasing cost for policy sponsor if (_periodToSetDefault != 0 && node.feeDelta[_periodToSetDefault] == 0) { node.feeDelta[_periodToSetDefault] = DEFAULT_FEE_DELTA; } } /** * @notice Update node fee * @param _info Node info structure * @param _period Processed period */ function updateFee(NodeInfo storage _info, uint16 _period) internal { if (_info.previousFeePeriod == 0 || _period <= _info.previousFeePeriod) { return; } for (uint16 i = _info.previousFeePeriod + 1; i <= _period; i++) { int256 delta = _info.feeDelta[i]; if (delta == DEFAULT_FEE_DELTA) { // gas refund _info.feeDelta[i] = 0; continue; } _info.feeRate = _info.feeRate.addSigned(delta); // gas refund _info.feeDelta[i] = 0; } _info.previousFeePeriod = _period; _info.fee += uint128(_info.feeRate); } /** * @notice Withdraw fee by node */ function withdraw() external returns (uint256) { return withdraw(msg.sender); } /** * @notice Withdraw fee by node * @param _recipient Recipient of the fee */ function withdraw(address payable _recipient) public returns (uint256) { NodeInfo storage node = nodes[msg.sender]; uint256 fee = node.fee; require(fee != 0); node.fee = 0; _recipient.sendValue(fee); emit Withdrawn(msg.sender, _recipient, fee); return fee; } /** * @notice Calculate amount of refund * @param _policy Policy * @param _arrangement Arrangement */ function calculateRefundValue(Policy storage _policy, ArrangementInfo storage _arrangement) internal view returns (uint256 refundValue, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod) { uint16 policyStartPeriod = uint16(_policy.startTimestamp / secondsPerPeriod); uint16 maxPeriod = AdditionalMath.min16(getCurrentPeriod(), uint16(_policy.endTimestamp / secondsPerPeriod)); uint16 minPeriod = AdditionalMath.max16(policyStartPeriod, _arrangement.lastRefundedPeriod); uint16 downtimePeriods = 0; uint256 length = escrow.getPastDowntimeLength(_arrangement.node); uint256 initialIndexOfDowntimePeriods; if (_arrangement.lastRefundedPeriod == 0) { initialIndexOfDowntimePeriods = escrow.findIndexOfPastDowntime(_arrangement.node, policyStartPeriod); } else { initialIndexOfDowntimePeriods = _arrangement.indexOfDowntimePeriods; } for (indexOfDowntimePeriods = initialIndexOfDowntimePeriods; indexOfDowntimePeriods < length; indexOfDowntimePeriods++) { (uint16 startPeriod, uint16 endPeriod) = escrow.getPastDowntime(_arrangement.node, indexOfDowntimePeriods); if (startPeriod > maxPeriod) { break; } else if (endPeriod < minPeriod) { continue; } downtimePeriods += AdditionalMath.min16(maxPeriod, endPeriod) .sub16(AdditionalMath.max16(minPeriod, startPeriod)) + 1; if (maxPeriod <= endPeriod) { break; } } uint16 lastCommittedPeriod = escrow.getLastCommittedPeriod(_arrangement.node); if (indexOfDowntimePeriods == length && lastCommittedPeriod < maxPeriod) { // Overflow protection removed: // lastCommittedPeriod < maxPeriod and minPeriod <= maxPeriod + 1 downtimePeriods += maxPeriod - AdditionalMath.max16(minPeriod - 1, lastCommittedPeriod); } refundValue = _policy.feeRate * downtimePeriods; lastRefundedPeriod = maxPeriod + 1; } /** * @notice Revoke/refund arrangement/policy by the sponsor * @param _policyId Policy id * @param _node Node that will be excluded or RESERVED_NODE if full policy should be used ( @param _forceRevoke Force revoke arrangement/policy */ function refundInternal(bytes16 _policyId, address _node, bool _forceRevoke) internal returns (uint256 refundValue) { refundValue = 0; Policy storage policy = policies[_policyId]; require(!policy.disabled && policy.startTimestamp >= resetTimestamp); uint16 endPeriod = uint16(policy.endTimestamp / secondsPerPeriod) + 1; uint256 numberOfActive = policy.arrangements.length; uint256 i = 0; for (; i < policy.arrangements.length; i++) { ArrangementInfo storage arrangement = policy.arrangements[i]; address node = arrangement.node; if (node == RESERVED_NODE || _node != RESERVED_NODE && _node != node) { numberOfActive--; continue; } uint256 nodeRefundValue; (nodeRefundValue, arrangement.indexOfDowntimePeriods, arrangement.lastRefundedPeriod) = calculateRefundValue(policy, arrangement); if (_forceRevoke) { NodeInfo storage nodeInfo = nodes[node]; // Check default value for feeDelta uint16 lastRefundedPeriod = arrangement.lastRefundedPeriod; if (nodeInfo.feeDelta[lastRefundedPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[lastRefundedPeriod] = -int256(policy.feeRate); } else { nodeInfo.feeDelta[lastRefundedPeriod] -= int256(policy.feeRate); } if (nodeInfo.feeDelta[endPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[endPeriod] = int256(policy.feeRate); } else { nodeInfo.feeDelta[endPeriod] += int256(policy.feeRate); } // Reset to default value if needed if (nodeInfo.feeDelta[lastRefundedPeriod] == 0) { nodeInfo.feeDelta[lastRefundedPeriod] = DEFAULT_FEE_DELTA; } if (nodeInfo.feeDelta[endPeriod] == 0) { nodeInfo.feeDelta[endPeriod] = DEFAULT_FEE_DELTA; } nodeRefundValue += uint256(endPeriod - lastRefundedPeriod) * policy.feeRate; } if (_forceRevoke || arrangement.lastRefundedPeriod >= endPeriod) { arrangement.node = RESERVED_NODE; arrangement.indexOfDowntimePeriods = 0; arrangement.lastRefundedPeriod = 0; numberOfActive--; emit ArrangementRevoked(_policyId, msg.sender, node, nodeRefundValue); } else { emit RefundForArrangement(_policyId, msg.sender, node, nodeRefundValue); } refundValue += nodeRefundValue; if (_node != RESERVED_NODE) { break; } } address payable policySponsor = policy.sponsor; if (_node == RESERVED_NODE) { if (numberOfActive == 0) { policy.disabled = true; // gas refund policy.sponsor = address(0); policy.owner = address(0); policy.feeRate = 0; policy.startTimestamp = 0; policy.endTimestamp = 0; emit PolicyRevoked(_policyId, msg.sender, refundValue); } else { emit RefundForPolicy(_policyId, msg.sender, refundValue); } } else { // arrangement not found require(i < policy.arrangements.length); } if (refundValue > 0) { policySponsor.sendValue(refundValue); } } /** * @notice Calculate amount of refund * @param _policyId Policy id * @param _node Node or RESERVED_NODE if all nodes should be used */ function calculateRefundValueInternal(bytes16 _policyId, address _node) internal view returns (uint256 refundValue) { refundValue = 0; Policy storage policy = policies[_policyId]; require((policy.owner == msg.sender || policy.sponsor == msg.sender) && !policy.disabled); uint256 i = 0; for (; i < policy.arrangements.length; i++) { ArrangementInfo storage arrangement = policy.arrangements[i]; if (arrangement.node == RESERVED_NODE || _node != RESERVED_NODE && _node != arrangement.node) { continue; } (uint256 nodeRefundValue,,) = calculateRefundValue(policy, arrangement); refundValue += nodeRefundValue; if (_node != RESERVED_NODE) { break; } } if (_node != RESERVED_NODE) { // arrangement not found require(i < policy.arrangements.length); } } /** * @notice Revoke policy by the sponsor * @param _policyId Policy id */ function revokePolicy(bytes16 _policyId) external returns (uint256 refundValue) { require(getPolicyOwner(_policyId) == msg.sender); return refundInternal(_policyId, RESERVED_NODE, true); } /** * @notice Revoke arrangement by the sponsor * @param _policyId Policy id * @param _node Node that will be excluded */ function revokeArrangement(bytes16 _policyId, address _node) external returns (uint256 refundValue) { require(_node != RESERVED_NODE); require(getPolicyOwner(_policyId) == msg.sender); return refundInternal(_policyId, _node, true); } /** * @notice Get unsigned hash for revocation * @param _policyId Policy id * @param _node Node that will be excluded * @return Revocation hash, EIP191 version 0x45 ('E') */ function getRevocationHash(bytes16 _policyId, address _node) public view returns (bytes32) { return SignatureVerifier.hashEIP191(abi.encodePacked(_policyId, _node), byte(0x45)); } /** * @notice Check correctness of signature * @param _policyId Policy id * @param _node Node that will be excluded, zero address if whole policy will be revoked * @param _signature Signature of owner */ function checkOwnerSignature(bytes16 _policyId, address _node, bytes memory _signature) internal view { bytes32 hash = getRevocationHash(_policyId, _node); address recovered = SignatureVerifier.recover(hash, _signature); require(getPolicyOwner(_policyId) == recovered); } /** * @notice Revoke policy or arrangement using owner's signature * @param _policyId Policy id * @param _node Node that will be excluded, zero address if whole policy will be revoked * @param _signature Signature of owner, EIP191 version 0x45 ('E') */ function revoke(bytes16 _policyId, address _node, bytes calldata _signature) external returns (uint256 refundValue) { checkOwnerSignature(_policyId, _node, _signature); return refundInternal(_policyId, _node, true); } /** * @notice Refund part of fee by the sponsor * @param _policyId Policy id */ function refund(bytes16 _policyId) external { Policy storage policy = policies[_policyId]; require(policy.owner == msg.sender || policy.sponsor == msg.sender); refundInternal(_policyId, RESERVED_NODE, false); } /** * @notice Refund part of one node's fee by the sponsor * @param _policyId Policy id * @param _node Node address */ function refund(bytes16 _policyId, address _node) external returns (uint256 refundValue) { require(_node != RESERVED_NODE); Policy storage policy = policies[_policyId]; require(policy.owner == msg.sender || policy.sponsor == msg.sender); return refundInternal(_policyId, _node, false); } /** * @notice Calculate amount of refund * @param _policyId Policy id */ function calculateRefundValue(bytes16 _policyId) external view returns (uint256 refundValue) { return calculateRefundValueInternal(_policyId, RESERVED_NODE); } /** * @notice Calculate amount of refund * @param _policyId Policy id * @param _node Node */ function calculateRefundValue(bytes16 _policyId, address _node) external view returns (uint256 refundValue) { require(_node != RESERVED_NODE); return calculateRefundValueInternal(_policyId, _node); } /** * @notice Get number of arrangements in the policy * @param _policyId Policy id */ function getArrangementsLength(bytes16 _policyId) external view returns (uint256) { return policies[_policyId].arrangements.length; } /** * @notice Get information about staker's fee rate * @param _node Address of staker * @param _period Period to get fee delta */ function getNodeFeeDelta(address _node, uint16 _period) // TODO "virtual" only for tests, probably will be removed after #1512 public view virtual returns (int256) { // TODO remove after upgrade #2579 if (_node == RESERVED_NODE && _period == 11) { return 55; } return nodes[_node].feeDelta[_period]; } /** * @notice Return the information about arrangement */ function getArrangementInfo(bytes16 _policyId, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (ArrangementInfo) external view returns (address node, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod) { ArrangementInfo storage info = policies[_policyId].arrangements[_index]; node = info.node; indexOfDowntimePeriods = info.indexOfDowntimePeriods; lastRefundedPeriod = info.lastRefundedPeriod; } /** * @dev Get Policy structure by delegatecall */ function delegateGetPolicy(address _target, bytes16 _policyId) internal returns (Policy memory result) { bytes32 memoryAddress = delegateGetData(_target, this.policies.selector, 1, bytes32(_policyId), 0); assembly { result := memoryAddress } } /** * @dev Get ArrangementInfo structure by delegatecall */ function delegateGetArrangementInfo(address _target, bytes16 _policyId, uint256 _index) internal returns (ArrangementInfo memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getArrangementInfo.selector, 2, bytes32(_policyId), bytes32(_index)); assembly { result := memoryAddress } } /** * @dev Get NodeInfo structure by delegatecall */ function delegateGetNodeInfo(address _target, address _node) internal returns (MemoryNodeInfo memory result) { bytes32 memoryAddress = delegateGetData(_target, this.nodes.selector, 1, bytes32(uint256(_node)), 0); assembly { result := memoryAddress } } /** * @dev Get feeRateRange structure by delegatecall */ function delegateGetFeeRateRange(address _target) internal returns (Range memory result) { bytes32 memoryAddress = delegateGetData(_target, this.feeRateRange.selector, 0, 0, 0); assembly { result := memoryAddress } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(uint64(delegateGet(_testTarget, this.resetTimestamp.selector)) == resetTimestamp); Range memory rangeToCheck = delegateGetFeeRateRange(_testTarget); require(feeRateRange.min == rangeToCheck.min && feeRateRange.defaultValue == rangeToCheck.defaultValue && feeRateRange.max == rangeToCheck.max); Policy storage policy = policies[RESERVED_POLICY_ID]; Policy memory policyToCheck = delegateGetPolicy(_testTarget, RESERVED_POLICY_ID); require(policyToCheck.sponsor == policy.sponsor && policyToCheck.owner == policy.owner && policyToCheck.feeRate == policy.feeRate && policyToCheck.startTimestamp == policy.startTimestamp && policyToCheck.endTimestamp == policy.endTimestamp && policyToCheck.disabled == policy.disabled); require(delegateGet(_testTarget, this.getArrangementsLength.selector, RESERVED_POLICY_ID) == policy.arrangements.length); if (policy.arrangements.length > 0) { ArrangementInfo storage arrangement = policy.arrangements[0]; ArrangementInfo memory arrangementToCheck = delegateGetArrangementInfo( _testTarget, RESERVED_POLICY_ID, 0); require(arrangementToCheck.node == arrangement.node && arrangementToCheck.indexOfDowntimePeriods == arrangement.indexOfDowntimePeriods && arrangementToCheck.lastRefundedPeriod == arrangement.lastRefundedPeriod); } NodeInfo storage nodeInfo = nodes[RESERVED_NODE]; MemoryNodeInfo memory nodeInfoToCheck = delegateGetNodeInfo(_testTarget, RESERVED_NODE); require(nodeInfoToCheck.fee == nodeInfo.fee && nodeInfoToCheck.feeRate == nodeInfo.feeRate && nodeInfoToCheck.previousFeePeriod == nodeInfo.previousFeePeriod && nodeInfoToCheck.minFeeRate == nodeInfo.minFeeRate); require(int256(delegateGet(_testTarget, this.getNodeFeeDelta.selector, bytes32(bytes20(RESERVED_NODE)), bytes32(uint256(11)))) == getNodeFeeDelta(RESERVED_NODE, 11)); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); if (resetTimestamp == 0) { resetTimestamp = uint64(block.timestamp); } // Create fake Policy and NodeInfo to use them in verifyState(address) Policy storage policy = policies[RESERVED_POLICY_ID]; policy.sponsor = msg.sender; policy.owner = address(this); policy.startTimestamp = 1; policy.endTimestamp = 2; policy.feeRate = 3; policy.disabled = true; policy.arrangements.push(ArrangementInfo(RESERVED_NODE, 11, 22)); NodeInfo storage nodeInfo = nodes[RESERVED_NODE]; nodeInfo.fee = 100; nodeInfo.feeRate = 33; nodeInfo.previousFeePeriod = 44; nodeInfo.feeDelta[11] = 55; nodeInfo.minFeeRate = 777; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./Upgradeable.sol"; import "../../zeppelin/utils/Address.sol"; /** * @notice ERC897 - ERC DelegateProxy */ interface ERCProxy { function proxyType() external pure returns (uint256); function implementation() external view returns (address); } /** * @notice Proxying requests to other contracts. * Client should use ABI of real contract and address of this contract */ contract Dispatcher is Upgradeable, ERCProxy { using Address for address; event Upgraded(address indexed from, address indexed to, address owner); event RolledBack(address indexed from, address indexed to, address owner); /** * @dev Set upgrading status before and after operations */ modifier upgrading() { isUpgrade = UPGRADE_TRUE; _; isUpgrade = UPGRADE_FALSE; } /** * @param _target Target contract address */ constructor(address _target) upgrading { require(_target.isContract()); // Checks that target contract inherits Dispatcher state verifyState(_target); // `verifyState` must work with its contract verifyUpgradeableState(_target, _target); target = _target; finishUpgrade(); emit Upgraded(address(0), _target, msg.sender); } //------------------------ERC897------------------------ /** * @notice ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() external pure override returns (uint256) { return 2; } /** * @notice ERC897, gets the address of the implementation where every call will be delegated */ function implementation() external view override returns (address) { return target; } //------------------------------------------------------------ /** * @notice Verify new contract storage and upgrade target * @param _target New target contract address */ function upgrade(address _target) public onlyOwner upgrading { require(_target.isContract()); // Checks that target contract has "correct" (as much as possible) state layout verifyState(_target); //`verifyState` must work with its contract verifyUpgradeableState(_target, _target); if (target.isContract()) { verifyUpgradeableState(target, _target); } previousTarget = target; target = _target; finishUpgrade(); emit Upgraded(previousTarget, _target, msg.sender); } /** * @notice Rollback to previous target * @dev Test storage carefully before upgrade again after rollback */ function rollback() public onlyOwner upgrading { require(previousTarget.isContract()); emit RolledBack(target, previousTarget, msg.sender); // should be always true because layout previousTarget -> target was already checked // but `verifyState` is not 100% accurate so check again verifyState(previousTarget); if (target.isContract()) { verifyUpgradeableState(previousTarget, target); } target = previousTarget; previousTarget = address(0); finishUpgrade(); } /** * @dev Call verifyState method for Upgradeable contract */ function verifyUpgradeableState(address _from, address _to) private { (bool callSuccess,) = _from.delegatecall(abi.encodeWithSelector(this.verifyState.selector, _to)); require(callSuccess); } /** * @dev Call finishUpgrade method from the Upgradeable contract */ function finishUpgrade() private { (bool callSuccess,) = target.delegatecall(abi.encodeWithSelector(this.finishUpgrade.selector, target)); require(callSuccess); } function verifyState(address _testTarget) public override onlyWhileUpgrading { //checks equivalence accessing state through new contract and current storage require(address(uint160(delegateGet(_testTarget, this.owner.selector))) == owner()); require(address(uint160(delegateGet(_testTarget, this.target.selector))) == target); require(address(uint160(delegateGet(_testTarget, this.previousTarget.selector))) == previousTarget); require(uint8(delegateGet(_testTarget, this.isUpgrade.selector)) == isUpgrade); } /** * @dev Override function using empty code because no reason to call this function in Dispatcher */ function finishUpgrade(address) public override {} /** * @dev Receive function sends empty request to the target contract */ receive() external payable { assert(target.isContract()); // execute receive function from target contract using storage of the dispatcher (bool callSuccess,) = target.delegatecall(""); if (!callSuccess) { revert(); } } /** * @dev Fallback function sends all requests to the target contract */ fallback() external payable { assert(target.isContract()); // execute requested function from target contract using storage of the dispatcher (bool callSuccess,) = target.delegatecall(msg.data); if (callSuccess) { // copy result of the request to the return data // we can use the second return value from `delegatecall` (bytes memory) // but it will consume a little more gas assembly { returndatacopy(0x0, 0x0, returndatasize()) return(0x0, returndatasize()) } } else { revert(); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/utils/Address.sol"; import "../../zeppelin/token/ERC20/SafeERC20.sol"; import "./StakingInterface.sol"; import "../../zeppelin/proxy/Initializable.sol"; /** * @notice Router for accessing interface contract */ contract StakingInterfaceRouter is Ownable { BaseStakingInterface public target; /** * @param _target Address of the interface contract */ constructor(BaseStakingInterface _target) { require(address(_target.token()) != address(0)); target = _target; } /** * @notice Upgrade interface * @param _target New contract address */ function upgrade(BaseStakingInterface _target) external onlyOwner { require(address(_target.token()) != address(0)); target = _target; } } /** * @notice Internal base class for AbstractStakingContract and InitializableStakingContract */ abstract contract RawStakingContract { using Address for address; /** * @dev Returns address of StakingInterfaceRouter */ function router() public view virtual returns (StakingInterfaceRouter); /** * @dev Checks permission for calling fallback function */ function isFallbackAllowed() public virtual returns (bool); /** * @dev Withdraw tokens from staking contract */ function withdrawTokens(uint256 _value) public virtual; /** * @dev Withdraw ETH from staking contract */ function withdrawETH() public virtual; receive() external payable {} /** * @dev Function sends all requests to the target contract */ fallback() external payable { require(isFallbackAllowed()); address target = address(router().target()); require(target.isContract()); // execute requested function from target contract (bool callSuccess, ) = target.delegatecall(msg.data); if (callSuccess) { // copy result of the request to the return data // we can use the second return value from `delegatecall` (bytes memory) // but it will consume a little more gas assembly { returndatacopy(0x0, 0x0, returndatasize()) return(0x0, returndatasize()) } } else { revert(); } } } /** * @notice Base class for any staking contract (not usable with openzeppelin proxy) * @dev Implement `isFallbackAllowed()` or override fallback function * Implement `withdrawTokens(uint256)` and `withdrawETH()` functions */ abstract contract AbstractStakingContract is RawStakingContract { StakingInterfaceRouter immutable router_; NuCypherToken public immutable token; /** * @param _router Interface router contract address */ constructor(StakingInterfaceRouter _router) { router_ = _router; NuCypherToken localToken = _router.target().token(); require(address(localToken) != address(0)); token = localToken; } /** * @dev Returns address of StakingInterfaceRouter */ function router() public view override returns (StakingInterfaceRouter) { return router_; } } /** * @notice Base class for any staking contract usable with openzeppelin proxy * @dev Implement `isFallbackAllowed()` or override fallback function * Implement `withdrawTokens(uint256)` and `withdrawETH()` functions */ abstract contract InitializableStakingContract is Initializable, RawStakingContract { StakingInterfaceRouter router_; NuCypherToken public token; /** * @param _router Interface router contract address */ function initialize(StakingInterfaceRouter _router) public initializer { router_ = _router; NuCypherToken localToken = _router.target().token(); require(address(localToken) != address(0)); token = localToken; } /** * @dev Returns address of StakingInterfaceRouter */ function router() public view override returns (StakingInterfaceRouter) { return router_; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./AbstractStakingContract.sol"; import "../NuCypherToken.sol"; import "../StakingEscrow.sol"; import "../PolicyManager.sol"; import "../WorkLock.sol"; /** * @notice Base StakingInterface */ contract BaseStakingInterface { address public immutable stakingInterfaceAddress; NuCypherToken public immutable token; StakingEscrow public immutable escrow; PolicyManager public immutable policyManager; WorkLock public immutable workLock; /** * @notice Constructor sets addresses of the contracts * @param _token Token contract * @param _escrow Escrow contract * @param _policyManager PolicyManager contract * @param _workLock WorkLock contract */ constructor( NuCypherToken _token, StakingEscrow _escrow, PolicyManager _policyManager, WorkLock _workLock ) { require(_token.totalSupply() > 0 && _escrow.secondsPerPeriod() > 0 && _policyManager.secondsPerPeriod() > 0 && // in case there is no worklock contract (address(_workLock) == address(0) || _workLock.boostingRefund() > 0)); token = _token; escrow = _escrow; policyManager = _policyManager; workLock = _workLock; stakingInterfaceAddress = address(this); } /** * @dev Checks executing through delegate call */ modifier onlyDelegateCall() { require(stakingInterfaceAddress != address(this)); _; } /** * @dev Checks the existence of the worklock contract */ modifier workLockSet() { require(address(workLock) != address(0)); _; } } /** * @notice Interface for accessing main contracts from a staking contract * @dev All methods must be stateless because this code will be executed by delegatecall call, use immutable fields. * @dev |v1.7.1| */ contract StakingInterface is BaseStakingInterface { event DepositedAsStaker(address indexed sender, uint256 value, uint16 periods); event WithdrawnAsStaker(address indexed sender, uint256 value); event DepositedAndIncreased(address indexed sender, uint256 index, uint256 value); event LockedAndCreated(address indexed sender, uint256 value, uint16 periods); event LockedAndIncreased(address indexed sender, uint256 index, uint256 value); event Divided(address indexed sender, uint256 index, uint256 newValue, uint16 periods); event Merged(address indexed sender, uint256 index1, uint256 index2); event Minted(address indexed sender); event PolicyFeeWithdrawn(address indexed sender, uint256 value); event MinFeeRateSet(address indexed sender, uint256 value); event ReStakeSet(address indexed sender, bool reStake); event WorkerBonded(address indexed sender, address worker); event Prolonged(address indexed sender, uint256 index, uint16 periods); event WindDownSet(address indexed sender, bool windDown); event SnapshotSet(address indexed sender, bool snapshotsEnabled); event Bid(address indexed sender, uint256 depositedETH); event Claimed(address indexed sender, uint256 claimedTokens); event Refund(address indexed sender, uint256 refundETH); event BidCanceled(address indexed sender); event CompensationWithdrawn(address indexed sender); /** * @notice Constructor sets addresses of the contracts * @param _token Token contract * @param _escrow Escrow contract * @param _policyManager PolicyManager contract * @param _workLock WorkLock contract */ constructor( NuCypherToken _token, StakingEscrow _escrow, PolicyManager _policyManager, WorkLock _workLock ) BaseStakingInterface(_token, _escrow, _policyManager, _workLock) { } /** * @notice Bond worker in the staking escrow * @param _worker Worker address */ function bondWorker(address _worker) public onlyDelegateCall { escrow.bondWorker(_worker); emit WorkerBonded(msg.sender, _worker); } /** * @notice Set `reStake` parameter in the staking escrow * @param _reStake Value for parameter */ function setReStake(bool _reStake) public onlyDelegateCall { escrow.setReStake(_reStake); emit ReStakeSet(msg.sender, _reStake); } /** * @notice Deposit tokens to the staking escrow * @param _value Amount of token to deposit * @param _periods Amount of periods during which tokens will be locked */ function depositAsStaker(uint256 _value, uint16 _periods) public onlyDelegateCall { require(token.balanceOf(address(this)) >= _value); token.approve(address(escrow), _value); escrow.deposit(address(this), _value, _periods); emit DepositedAsStaker(msg.sender, _value, _periods); } /** * @notice Deposit tokens to the staking escrow * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function depositAndIncrease(uint256 _index, uint256 _value) public onlyDelegateCall { require(token.balanceOf(address(this)) >= _value); token.approve(address(escrow), _value); escrow.depositAndIncrease(_index, _value); emit DepositedAndIncreased(msg.sender, _index, _value); } /** * @notice Withdraw available amount of tokens from the staking escrow to the staking contract * @param _value Amount of token to withdraw */ function withdrawAsStaker(uint256 _value) public onlyDelegateCall { escrow.withdraw(_value); emit WithdrawnAsStaker(msg.sender, _value); } /** * @notice Lock some tokens in the staking escrow * @param _value Amount of tokens which should lock * @param _periods Amount of periods during which tokens will be locked */ function lockAndCreate(uint256 _value, uint16 _periods) public onlyDelegateCall { escrow.lockAndCreate(_value, _periods); emit LockedAndCreated(msg.sender, _value, _periods); } /** * @notice Lock some tokens in the staking escrow * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease(uint256 _index, uint256 _value) public onlyDelegateCall { escrow.lockAndIncrease(_index, _value); emit LockedAndIncreased(msg.sender, _index, _value); } /** * @notice Divide stake into two parts * @param _index Index of stake * @param _newValue New stake value * @param _periods Amount of periods for extending stake */ function divideStake(uint256 _index, uint256 _newValue, uint16 _periods) public onlyDelegateCall { escrow.divideStake(_index, _newValue, _periods); emit Divided(msg.sender, _index, _newValue, _periods); } /** * @notice Merge two sub-stakes into one * @param _index1 Index of the first sub-stake * @param _index2 Index of the second sub-stake */ function mergeStake(uint256 _index1, uint256 _index2) public onlyDelegateCall { escrow.mergeStake(_index1, _index2); emit Merged(msg.sender, _index1, _index2); } /** * @notice Mint tokens in the staking escrow */ function mint() public onlyDelegateCall { escrow.mint(); emit Minted(msg.sender); } /** * @notice Withdraw available policy fees from the policy manager to the staking contract */ function withdrawPolicyFee() public onlyDelegateCall { uint256 value = policyManager.withdraw(); emit PolicyFeeWithdrawn(msg.sender, value); } /** * @notice Set the minimum fee that the staker will accept in the policy manager contract */ function setMinFeeRate(uint256 _minFeeRate) public onlyDelegateCall { policyManager.setMinFeeRate(_minFeeRate); emit MinFeeRateSet(msg.sender, _minFeeRate); } /** * @notice Prolong active sub stake * @param _index Index of the sub stake * @param _periods Amount of periods for extending sub stake */ function prolongStake(uint256 _index, uint16 _periods) public onlyDelegateCall { escrow.prolongStake(_index, _periods); emit Prolonged(msg.sender, _index, _periods); } /** * @notice Set `windDown` parameter in the staking escrow * @param _windDown Value for parameter */ function setWindDown(bool _windDown) public onlyDelegateCall { escrow.setWindDown(_windDown); emit WindDownSet(msg.sender, _windDown); } /** * @notice Set `snapshots` parameter in the staking escrow * @param _enableSnapshots Value for parameter */ function setSnapshots(bool _enableSnapshots) public onlyDelegateCall { escrow.setSnapshots(_enableSnapshots); emit SnapshotSet(msg.sender, _enableSnapshots); } /** * @notice Bid for tokens by transferring ETH */ function bid(uint256 _value) public payable onlyDelegateCall workLockSet { workLock.bid{value: _value}(); emit Bid(msg.sender, _value); } /** * @notice Cancel bid and refund deposited ETH */ function cancelBid() public onlyDelegateCall workLockSet { workLock.cancelBid(); emit BidCanceled(msg.sender); } /** * @notice Withdraw compensation after force refund */ function withdrawCompensation() public onlyDelegateCall workLockSet { workLock.withdrawCompensation(); emit CompensationWithdrawn(msg.sender); } /** * @notice Claimed tokens will be deposited and locked as stake in the StakingEscrow contract */ function claim() public onlyDelegateCall workLockSet { uint256 claimedTokens = workLock.claim(); emit Claimed(msg.sender, claimedTokens); } /** * @notice Refund ETH for the completed work */ function refund() public onlyDelegateCall workLockSet { uint256 refundETH = workLock.refund(); emit Refund(msg.sender, refundETH); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/token/ERC20/SafeERC20.sol"; import "../zeppelin/utils/Address.sol"; import "../zeppelin/ownership/Ownable.sol"; import "./NuCypherToken.sol"; import "./StakingEscrow.sol"; import "./lib/AdditionalMath.sol"; /** * @notice The WorkLock distribution contract */ contract WorkLock is Ownable { using SafeERC20 for NuCypherToken; using SafeMath for uint256; using AdditionalMath for uint256; using Address for address payable; using Address for address; event Deposited(address indexed sender, uint256 value); event Bid(address indexed sender, uint256 depositedETH); event Claimed(address indexed sender, uint256 claimedTokens); event Refund(address indexed sender, uint256 refundETH, uint256 completedWork); event Canceled(address indexed sender, uint256 value); event BiddersChecked(address indexed sender, uint256 startIndex, uint256 endIndex); event ForceRefund(address indexed sender, address indexed bidder, uint256 refundETH); event CompensationWithdrawn(address indexed sender, uint256 value); event Shutdown(address indexed sender); struct WorkInfo { uint256 depositedETH; uint256 completedWork; bool claimed; uint128 index; } uint16 public constant SLOWING_REFUND = 100; uint256 private constant MAX_ETH_SUPPLY = 2e10 ether; NuCypherToken public immutable token; StakingEscrow public immutable escrow; /* * @dev WorkLock calculations: * bid = minBid + bonusETHPart * bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens * bonusDepositRate = bonusTokenSupply / bonusETHSupply * claimedTokens = minAllowableLockedTokens + bonusETHPart * bonusDepositRate * bonusRefundRate = bonusDepositRate * SLOWING_REFUND / boostingRefund * refundETH = completedWork / refundRate */ uint256 public immutable boostingRefund; uint256 public immutable minAllowedBid; uint16 public immutable stakingPeriods; // copy from the escrow contract uint256 public immutable maxAllowableLockedTokens; uint256 public immutable minAllowableLockedTokens; uint256 public tokenSupply; uint256 public startBidDate; uint256 public endBidDate; uint256 public endCancellationDate; uint256 public bonusETHSupply; mapping(address => WorkInfo) public workInfo; mapping(address => uint256) public compensation; address[] public bidders; // if value == bidders.length then WorkLock is fully checked uint256 public nextBidderToCheck; /** * @dev Checks timestamp regarding cancellation window */ modifier afterCancellationWindow() { require(block.timestamp >= endCancellationDate, "Operation is allowed when cancellation phase is over"); _; } /** * @param _token Token contract * @param _escrow Escrow contract * @param _startBidDate Timestamp when bidding starts * @param _endBidDate Timestamp when bidding will end * @param _endCancellationDate Timestamp when cancellation will ends * @param _boostingRefund Coefficient to boost refund ETH * @param _stakingPeriods Amount of periods during which tokens will be locked after claiming * @param _minAllowedBid Minimum allowed ETH amount for bidding */ constructor( NuCypherToken _token, StakingEscrow _escrow, uint256 _startBidDate, uint256 _endBidDate, uint256 _endCancellationDate, uint256 _boostingRefund, uint16 _stakingPeriods, uint256 _minAllowedBid ) { uint256 totalSupply = _token.totalSupply(); require(totalSupply > 0 && // token contract is deployed and accessible _escrow.secondsPerPeriod() > 0 && // escrow contract is deployed and accessible _escrow.token() == _token && // same token address for worklock and escrow _endBidDate > _startBidDate && // bidding period lasts some time _endBidDate > block.timestamp && // there is time to make a bid _endCancellationDate >= _endBidDate && // cancellation window includes bidding _minAllowedBid > 0 && // min allowed bid was set _boostingRefund > 0 && // boosting coefficient was set _stakingPeriods >= _escrow.minLockedPeriods()); // staking duration is consistent with escrow contract // worst case for `ethToWork()` and `workToETH()`, // when ethSupply == MAX_ETH_SUPPLY and tokenSupply == totalSupply require(MAX_ETH_SUPPLY * totalSupply * SLOWING_REFUND / MAX_ETH_SUPPLY / totalSupply == SLOWING_REFUND && MAX_ETH_SUPPLY * totalSupply * _boostingRefund / MAX_ETH_SUPPLY / totalSupply == _boostingRefund); token = _token; escrow = _escrow; startBidDate = _startBidDate; endBidDate = _endBidDate; endCancellationDate = _endCancellationDate; boostingRefund = _boostingRefund; stakingPeriods = _stakingPeriods; minAllowedBid = _minAllowedBid; maxAllowableLockedTokens = _escrow.maxAllowableLockedTokens(); minAllowableLockedTokens = _escrow.minAllowableLockedTokens(); } /** * @notice Deposit tokens to contract * @param _value Amount of tokens to transfer */ function tokenDeposit(uint256 _value) external { require(block.timestamp < endBidDate, "Can't deposit more tokens after end of bidding"); token.safeTransferFrom(msg.sender, address(this), _value); tokenSupply += _value; emit Deposited(msg.sender, _value); } /** * @notice Calculate amount of tokens that will be get for specified amount of ETH * @dev This value will be fixed only after end of bidding */ function ethToTokens(uint256 _ethAmount) public view returns (uint256) { if (_ethAmount < minAllowedBid) { return 0; } // when all participants bid with the same minimum amount of eth if (bonusETHSupply == 0) { return tokenSupply / bidders.length; } uint256 bonusETH = _ethAmount - minAllowedBid; uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens; return minAllowableLockedTokens + bonusETH.mul(bonusTokenSupply).div(bonusETHSupply); } /** * @notice Calculate amount of work that need to be done to refund specified amount of ETH */ function ethToWork(uint256 _ethAmount, uint256 _tokenSupply, uint256 _ethSupply) internal view returns (uint256) { return _ethAmount.mul(_tokenSupply).mul(SLOWING_REFUND).divCeil(_ethSupply.mul(boostingRefund)); } /** * @notice Calculate amount of work that need to be done to refund specified amount of ETH * @dev This value will be fixed only after end of bidding * @param _ethToReclaim Specified sum of ETH staker wishes to reclaim following completion of work * @param _restOfDepositedETH Remaining ETH in staker's deposit once ethToReclaim sum has been subtracted * @dev _ethToReclaim + _restOfDepositedETH = depositedETH */ function ethToWork(uint256 _ethToReclaim, uint256 _restOfDepositedETH) internal view returns (uint256) { uint256 baseETHSupply = bidders.length * minAllowedBid; // when all participants bid with the same minimum amount of eth if (bonusETHSupply == 0) { return ethToWork(_ethToReclaim, tokenSupply, baseETHSupply); } uint256 baseETH = 0; uint256 bonusETH = 0; // If the staker's total remaining deposit (including the specified sum of ETH to reclaim) // is lower than the minimum bid size, // then only the base part is used to calculate the work required to reclaim ETH if (_ethToReclaim + _restOfDepositedETH <= minAllowedBid) { baseETH = _ethToReclaim; // If the staker's remaining deposit (not including the specified sum of ETH to reclaim) // is still greater than the minimum bid size, // then only the bonus part is used to calculate the work required to reclaim ETH } else if (_restOfDepositedETH >= minAllowedBid) { bonusETH = _ethToReclaim; // If the staker's remaining deposit (not including the specified sum of ETH to reclaim) // is lower than the minimum bid size, // then both the base and bonus parts must be used to calculate the work required to reclaim ETH } else { bonusETH = _ethToReclaim + _restOfDepositedETH - minAllowedBid; baseETH = _ethToReclaim - bonusETH; } uint256 baseTokenSupply = bidders.length * minAllowableLockedTokens; uint256 work = 0; if (baseETH > 0) { work = ethToWork(baseETH, baseTokenSupply, baseETHSupply); } if (bonusETH > 0) { uint256 bonusTokenSupply = tokenSupply - baseTokenSupply; work += ethToWork(bonusETH, bonusTokenSupply, bonusETHSupply); } return work; } /** * @notice Calculate amount of work that need to be done to refund specified amount of ETH * @dev This value will be fixed only after end of bidding */ function ethToWork(uint256 _ethAmount) public view returns (uint256) { return ethToWork(_ethAmount, 0); } /** * @notice Calculate amount of ETH that will be refund for completing specified amount of work */ function workToETH(uint256 _completedWork, uint256 _ethSupply, uint256 _tokenSupply) internal view returns (uint256) { return _completedWork.mul(_ethSupply).mul(boostingRefund).div(_tokenSupply.mul(SLOWING_REFUND)); } /** * @notice Calculate amount of ETH that will be refund for completing specified amount of work * @dev This value will be fixed only after end of bidding */ function workToETH(uint256 _completedWork, uint256 _depositedETH) public view returns (uint256) { uint256 baseETHSupply = bidders.length * minAllowedBid; // when all participants bid with the same minimum amount of eth if (bonusETHSupply == 0) { return workToETH(_completedWork, baseETHSupply, tokenSupply); } uint256 bonusWork = 0; uint256 bonusETH = 0; uint256 baseTokenSupply = bidders.length * minAllowableLockedTokens; if (_depositedETH > minAllowedBid) { bonusETH = _depositedETH - minAllowedBid; uint256 bonusTokenSupply = tokenSupply - baseTokenSupply; bonusWork = ethToWork(bonusETH, bonusTokenSupply, bonusETHSupply); if (_completedWork <= bonusWork) { return workToETH(_completedWork, bonusETHSupply, bonusTokenSupply); } } _completedWork -= bonusWork; return bonusETH + workToETH(_completedWork, baseETHSupply, baseTokenSupply); } /** * @notice Get remaining work to full refund */ function getRemainingWork(address _bidder) external view returns (uint256) { WorkInfo storage info = workInfo[_bidder]; uint256 completedWork = escrow.getCompletedWork(_bidder).sub(info.completedWork); uint256 remainingWork = ethToWork(info.depositedETH); if (remainingWork <= completedWork) { return 0; } return remainingWork - completedWork; } /** * @notice Get length of bidders array */ function getBiddersLength() external view returns (uint256) { return bidders.length; } /** * @notice Bid for tokens by transferring ETH */ function bid() external payable { require(block.timestamp >= startBidDate, "Bidding is not open yet"); require(block.timestamp < endBidDate, "Bidding is already finished"); WorkInfo storage info = workInfo[msg.sender]; // first bid if (info.depositedETH == 0) { require(msg.value >= minAllowedBid, "Bid must be at least minimum"); require(bidders.length < tokenSupply / minAllowableLockedTokens, "Not enough tokens for more bidders"); info.index = uint128(bidders.length); bidders.push(msg.sender); bonusETHSupply = bonusETHSupply.add(msg.value - minAllowedBid); } else { bonusETHSupply = bonusETHSupply.add(msg.value); } info.depositedETH = info.depositedETH.add(msg.value); emit Bid(msg.sender, msg.value); } /** * @notice Cancel bid and refund deposited ETH */ function cancelBid() external { require(block.timestamp < endCancellationDate, "Cancellation allowed only during cancellation window"); WorkInfo storage info = workInfo[msg.sender]; require(info.depositedETH > 0, "No bid to cancel"); require(!info.claimed, "Tokens are already claimed"); uint256 refundETH = info.depositedETH; info.depositedETH = 0; // remove from bidders array, move last bidder to the empty place uint256 lastIndex = bidders.length - 1; if (info.index != lastIndex) { address lastBidder = bidders[lastIndex]; bidders[info.index] = lastBidder; workInfo[lastBidder].index = info.index; } bidders.pop(); if (refundETH > minAllowedBid) { bonusETHSupply = bonusETHSupply.sub(refundETH - minAllowedBid); } msg.sender.sendValue(refundETH); emit Canceled(msg.sender, refundETH); } /** * @notice Cancels distribution, makes possible to retrieve all bids and owner gets all tokens */ function shutdown() external onlyOwner { require(!isClaimingAvailable(), "Claiming has already been enabled"); internalShutdown(); } /** * @notice Cancels distribution, makes possible to retrieve all bids and owner gets all tokens */ function internalShutdown() internal { startBidDate = 0; endBidDate = 0; endCancellationDate = uint256(0) - 1; // "infinite" cancellation window token.safeTransfer(owner(), tokenSupply); emit Shutdown(msg.sender); } /** * @notice Make force refund to bidders who can get tokens more than maximum allowed * @param _biddersForRefund Sorted list of unique bidders. Only bidders who must receive a refund */ function forceRefund(address payable[] calldata _biddersForRefund) external afterCancellationWindow { require(nextBidderToCheck != bidders.length, "Bidders have already been checked"); uint256 length = _biddersForRefund.length; require(length > 0, "Must be at least one bidder for a refund"); uint256 minNumberOfBidders = tokenSupply.divCeil(maxAllowableLockedTokens); if (bidders.length < minNumberOfBidders) { internalShutdown(); return; } address previousBidder = _biddersForRefund[0]; uint256 minBid = workInfo[previousBidder].depositedETH; uint256 maxBid = minBid; // get minimum and maximum bids for (uint256 i = 1; i < length; i++) { address bidder = _biddersForRefund[i]; uint256 depositedETH = workInfo[bidder].depositedETH; require(bidder > previousBidder && depositedETH > 0, "Addresses must be an array of unique bidders"); if (minBid > depositedETH) { minBid = depositedETH; } else if (maxBid < depositedETH) { maxBid = depositedETH; } previousBidder = bidder; } uint256[] memory refunds = new uint256[](length); // first step - align at a minimum bid if (minBid != maxBid) { for (uint256 i = 0; i < length; i++) { address bidder = _biddersForRefund[i]; WorkInfo storage info = workInfo[bidder]; if (info.depositedETH > minBid) { refunds[i] = info.depositedETH - minBid; info.depositedETH = minBid; bonusETHSupply -= refunds[i]; } } } require(ethToTokens(minBid) > maxAllowableLockedTokens, "At least one of bidders has allowable bid"); // final bids adjustment (only for bonus part) // (min_whale_bid * token_supply - max_stake * eth_supply) / (token_supply - max_stake * n_whales) uint256 maxBonusTokens = maxAllowableLockedTokens - minAllowableLockedTokens; uint256 minBonusETH = minBid - minAllowedBid; uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens; uint256 refundETH = minBonusETH.mul(bonusTokenSupply) .sub(maxBonusTokens.mul(bonusETHSupply)) .divCeil(bonusTokenSupply - maxBonusTokens.mul(length)); uint256 resultBid = minBid.sub(refundETH); bonusETHSupply -= length * refundETH; for (uint256 i = 0; i < length; i++) { address bidder = _biddersForRefund[i]; WorkInfo storage info = workInfo[bidder]; refunds[i] += refundETH; info.depositedETH = resultBid; } // reset verification nextBidderToCheck = 0; // save a refund for (uint256 i = 0; i < length; i++) { address bidder = _biddersForRefund[i]; compensation[bidder] += refunds[i]; emit ForceRefund(msg.sender, bidder, refunds[i]); } } /** * @notice Withdraw compensation after force refund */ function withdrawCompensation() external { uint256 refund = compensation[msg.sender]; require(refund > 0, "There is no compensation"); compensation[msg.sender] = 0; msg.sender.sendValue(refund); emit CompensationWithdrawn(msg.sender, refund); } /** * @notice Check that the claimed tokens are within `maxAllowableLockedTokens` for all participants, * starting from the last point `nextBidderToCheck` * @dev Method stops working when the remaining gas is less than `_gasToSaveState` * and saves the state in `nextBidderToCheck`. * If all bidders have been checked then `nextBidderToCheck` will be equal to the length of the bidders array */ function verifyBiddingCorrectness(uint256 _gasToSaveState) external afterCancellationWindow returns (uint256) { require(nextBidderToCheck != bidders.length, "Bidders have already been checked"); // all participants bid with the same minimum amount of eth uint256 index = nextBidderToCheck; if (bonusETHSupply == 0) { require(tokenSupply / bidders.length <= maxAllowableLockedTokens, "Not enough bidders"); index = bidders.length; } uint256 maxBonusTokens = maxAllowableLockedTokens - minAllowableLockedTokens; uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens; uint256 maxBidFromMaxStake = minAllowedBid + maxBonusTokens.mul(bonusETHSupply).div(bonusTokenSupply); while (index < bidders.length && gasleft() > _gasToSaveState) { address bidder = bidders[index]; require(workInfo[bidder].depositedETH <= maxBidFromMaxStake, "Bid is greater than max allowable bid"); index++; } if (index != nextBidderToCheck) { emit BiddersChecked(msg.sender, nextBidderToCheck, index); nextBidderToCheck = index; } return nextBidderToCheck; } /** * @notice Checks if claiming available */ function isClaimingAvailable() public view returns (bool) { return block.timestamp >= endCancellationDate && nextBidderToCheck == bidders.length; } /** * @notice Claimed tokens will be deposited and locked as stake in the StakingEscrow contract. */ function claim() external returns (uint256 claimedTokens) { require(isClaimingAvailable(), "Claiming has not been enabled yet"); WorkInfo storage info = workInfo[msg.sender]; require(!info.claimed, "Tokens are already claimed"); claimedTokens = ethToTokens(info.depositedETH); require(claimedTokens > 0, "Nothing to claim"); info.claimed = true; token.approve(address(escrow), claimedTokens); escrow.depositFromWorkLock(msg.sender, claimedTokens, stakingPeriods); info.completedWork = escrow.setWorkMeasurement(msg.sender, true); emit Claimed(msg.sender, claimedTokens); } /** * @notice Get available refund for bidder */ function getAvailableRefund(address _bidder) public view returns (uint256) { WorkInfo storage info = workInfo[_bidder]; // nothing to refund if (info.depositedETH == 0) { return 0; } uint256 currentWork = escrow.getCompletedWork(_bidder); uint256 completedWork = currentWork.sub(info.completedWork); // no work that has been completed since last refund if (completedWork == 0) { return 0; } uint256 refundETH = workToETH(completedWork, info.depositedETH); if (refundETH > info.depositedETH) { refundETH = info.depositedETH; } return refundETH; } /** * @notice Refund ETH for the completed work */ function refund() external returns (uint256 refundETH) { WorkInfo storage info = workInfo[msg.sender]; require(info.claimed, "Tokens must be claimed before refund"); refundETH = getAvailableRefund(msg.sender); require(refundETH > 0, "Nothing to refund: there is no ETH to refund or no completed work"); if (refundETH == info.depositedETH) { escrow.setWorkMeasurement(msg.sender, false); } info.depositedETH = info.depositedETH.sub(refundETH); // convert refund back to work to eliminate potential rounding errors uint256 completedWork = ethToWork(refundETH, info.depositedETH); info.completedWork = info.completedWork.add(completedWork); emit Refund(msg.sender, refundETH, completedWork); msg.sender.sendValue(refundETH); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract acts as delegate for sub-stakers and owner **/ contract PoolingStakingContract is AbstractStakingContract, Ownable { using SafeMath for uint256; using Address for address payable; using SafeERC20 for NuCypherToken; event TokensDeposited(address indexed sender, uint256 value, uint256 depositedTokens); event TokensWithdrawn(address indexed sender, uint256 value, uint256 depositedTokens); event ETHWithdrawn(address indexed sender, uint256 value); event DepositSet(address indexed sender, bool value); struct Delegator { uint256 depositedTokens; uint256 withdrawnReward; uint256 withdrawnETH; } StakingEscrow public immutable escrow; uint256 public totalDepositedTokens; uint256 public totalWithdrawnReward; uint256 public totalWithdrawnETH; uint256 public ownerFraction; uint256 public ownerWithdrawnReward; uint256 public ownerWithdrawnETH; mapping (address => Delegator) public delegators; bool depositIsEnabled = true; /** * @param _router Address of the StakingInterfaceRouter contract * @param _ownerFraction Base owner's portion of reward */ constructor( StakingInterfaceRouter _router, uint256 _ownerFraction ) AbstractStakingContract(_router) { escrow = _router.target().escrow(); ownerFraction = _ownerFraction; } /** * @notice Enabled deposit */ function enableDeposit() external onlyOwner { depositIsEnabled = true; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Disable deposit */ function disableDeposit() external onlyOwner { depositIsEnabled = false; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Transfer tokens as delegator * @param _value Amount of tokens to transfer */ function depositTokens(uint256 _value) external { require(depositIsEnabled, "Deposit must be enabled"); require(_value > 0, "Value must be not empty"); totalDepositedTokens = totalDepositedTokens.add(_value); Delegator storage delegator = delegators[msg.sender]; delegator.depositedTokens += _value; token.safeTransferFrom(msg.sender, address(this), _value); emit TokensDeposited(msg.sender, _value, delegator.depositedTokens); } /** * @notice Get available reward for all delegators and owner */ function getAvailableReward() public view returns (uint256) { uint256 stakedTokens = escrow.getAllTokens(address(this)); uint256 freeTokens = token.balanceOf(address(this)); uint256 reward = stakedTokens + freeTokens - totalDepositedTokens; if (reward > freeTokens) { return freeTokens; } return reward; } /** * @notice Get cumulative reward */ function getCumulativeReward() public view returns (uint256) { return getAvailableReward().add(totalWithdrawnReward); } /** * @notice Get available reward in tokens for pool owner */ function getAvailableOwnerReward() public view returns (uint256) { uint256 reward = getCumulativeReward(); uint256 maxAllowableReward; if (totalDepositedTokens != 0) { maxAllowableReward = reward.mul(ownerFraction).div(totalDepositedTokens.add(ownerFraction)); } else { maxAllowableReward = reward; } return maxAllowableReward.sub(ownerWithdrawnReward); } /** * @notice Get available reward in tokens for delegator */ function getAvailableReward(address _delegator) public view returns (uint256) { if (totalDepositedTokens == 0) { return 0; } uint256 reward = getCumulativeReward(); Delegator storage delegator = delegators[_delegator]; uint256 maxAllowableReward = reward.mul(delegator.depositedTokens) .div(totalDepositedTokens.add(ownerFraction)); return maxAllowableReward > delegator.withdrawnReward ? maxAllowableReward - delegator.withdrawnReward : 0; } /** * @notice Withdraw reward in tokens to owner */ function withdrawOwnerReward() public onlyOwner { uint256 balance = token.balanceOf(address(this)); uint256 availableReward = getAvailableOwnerReward(); if (availableReward > balance) { availableReward = balance; } require(availableReward > 0, "There is no available reward to withdraw"); ownerWithdrawnReward = ownerWithdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); token.safeTransfer(msg.sender, availableReward); emit TokensWithdrawn(msg.sender, availableReward, 0); } /** * @notice Withdraw amount of tokens to delegator * @param _value Amount of tokens to withdraw */ function withdrawTokens(uint256 _value) public override { uint256 balance = token.balanceOf(address(this)); require(_value <= balance, "Not enough tokens in the contract"); uint256 availableReward = getAvailableReward(msg.sender); Delegator storage delegator = delegators[msg.sender]; require(_value <= availableReward + delegator.depositedTokens, "Requested amount of tokens exceeded allowed portion"); if (_value <= availableReward) { delegator.withdrawnReward += _value; totalWithdrawnReward += _value; } else { delegator.withdrawnReward = delegator.withdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); uint256 depositToWithdraw = _value - availableReward; uint256 newDepositedTokens = delegator.depositedTokens - depositToWithdraw; uint256 newWithdrawnReward = delegator.withdrawnReward.mul(newDepositedTokens).div(delegator.depositedTokens); uint256 newWithdrawnETH = delegator.withdrawnETH.mul(newDepositedTokens).div(delegator.depositedTokens); totalDepositedTokens -= depositToWithdraw; totalWithdrawnReward -= (delegator.withdrawnReward - newWithdrawnReward); totalWithdrawnETH -= (delegator.withdrawnETH - newWithdrawnETH); delegator.depositedTokens = newDepositedTokens; delegator.withdrawnReward = newWithdrawnReward; delegator.withdrawnETH = newWithdrawnETH; } token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens); } /** * @notice Get available ether for owner */ function getAvailableOwnerETH() public view returns (uint256) { // TODO boilerplate code uint256 balance = address(this).balance; balance = balance.add(totalWithdrawnETH); uint256 maxAllowableETH = balance.mul(ownerFraction).div(totalDepositedTokens.add(ownerFraction)); uint256 availableETH = maxAllowableETH.sub(ownerWithdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Get available ether for delegator */ function getAvailableETH(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; // TODO boilerplate code uint256 balance = address(this).balance; balance = balance.add(totalWithdrawnETH); uint256 maxAllowableETH = balance.mul(delegator.depositedTokens) .div(totalDepositedTokens.add(ownerFraction)); uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Withdraw available amount of ETH to pool owner */ function withdrawOwnerETH() public onlyOwner { uint256 availableETH = getAvailableOwnerETH(); require(availableETH > 0, "There is no available ETH to withdraw"); ownerWithdrawnETH = ownerWithdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } /** * @notice Withdraw available amount of ETH to delegator */ function withdrawETH() public override { uint256 availableETH = getAvailableETH(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); Delegator storage delegator = delegators[msg.sender]; delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } /** * @notice Calling fallback function is allowed only for the owner **/ function isFallbackAllowed() public view override returns (bool) { return msg.sender == owner(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract acts as delegate for sub-stakers **/ contract PoolingStakingContractV2 is InitializableStakingContract, Ownable { using SafeMath for uint256; using Address for address payable; using SafeERC20 for NuCypherToken; event TokensDeposited( address indexed sender, uint256 value, uint256 depositedTokens ); event TokensWithdrawn( address indexed sender, uint256 value, uint256 depositedTokens ); event ETHWithdrawn(address indexed sender, uint256 value); event WorkerOwnerSet(address indexed sender, address indexed workerOwner); struct Delegator { uint256 depositedTokens; uint256 withdrawnReward; uint256 withdrawnETH; } /** * Defines base fraction and precision of worker fraction. * E.g., for a value of 10000, a worker fraction of 100 represents 1% of reward (100/10000) */ uint256 public constant BASIS_FRACTION = 10000; StakingEscrow public escrow; address public workerOwner; uint256 public totalDepositedTokens; uint256 public totalWithdrawnReward; uint256 public totalWithdrawnETH; uint256 workerFraction; uint256 public workerWithdrawnReward; mapping(address => Delegator) public delegators; /** * @notice Initialize function for using with OpenZeppelin proxy * @param _workerFraction Share of token reward that worker node owner will get. * Use value up to BASIS_FRACTION (10000), if _workerFraction = BASIS_FRACTION -> means 100% reward as commission. * For example, 100 worker fraction is 1% of reward * @param _router StakingInterfaceRouter address * @param _workerOwner Owner of worker node, only this address can withdraw worker commission */ function initialize( uint256 _workerFraction, StakingInterfaceRouter _router, address _workerOwner ) external initializer { require(_workerOwner != address(0) && _workerFraction <= BASIS_FRACTION); InitializableStakingContract.initialize(_router); _transferOwnership(msg.sender); escrow = _router.target().escrow(); workerFraction = _workerFraction; workerOwner = _workerOwner; emit WorkerOwnerSet(msg.sender, _workerOwner); } /** * @notice withdrawAll() is allowed */ function isWithdrawAllAllowed() public view returns (bool) { // no tokens in StakingEscrow contract which belong to pool return escrow.getAllTokens(address(this)) == 0; } /** * @notice deposit() is allowed */ function isDepositAllowed() public view returns (bool) { // tokens which directly belong to pool uint256 freeTokens = token.balanceOf(address(this)); // no sub-stakes and no earned reward return isWithdrawAllAllowed() && freeTokens == totalDepositedTokens; } /** * @notice Set worker owner address */ function setWorkerOwner(address _workerOwner) external onlyOwner { workerOwner = _workerOwner; emit WorkerOwnerSet(msg.sender, _workerOwner); } /** * @notice Calculate worker's fraction depending on deposited tokens * Override to implement dynamic worker fraction. */ function getWorkerFraction() public view virtual returns (uint256) { return workerFraction; } /** * @notice Transfer tokens as delegator * @param _value Amount of tokens to transfer */ function depositTokens(uint256 _value) external { require(isDepositAllowed(), "Deposit must be enabled"); require(_value > 0, "Value must be not empty"); totalDepositedTokens = totalDepositedTokens.add(_value); Delegator storage delegator = delegators[msg.sender]; delegator.depositedTokens = delegator.depositedTokens.add(_value); token.safeTransferFrom(msg.sender, address(this), _value); emit TokensDeposited(msg.sender, _value, delegator.depositedTokens); } /** * @notice Get available reward for all delegators and owner */ function getAvailableReward() public view returns (uint256) { // locked + unlocked tokens in StakingEscrow contract which belong to pool uint256 stakedTokens = escrow.getAllTokens(address(this)); // tokens which directly belong to pool uint256 freeTokens = token.balanceOf(address(this)); // tokens in excess of the initially deposited uint256 reward = stakedTokens.add(freeTokens).sub(totalDepositedTokens); // check how many of reward tokens belong directly to pool if (reward > freeTokens) { return freeTokens; } return reward; } /** * @notice Get cumulative reward. * Available and withdrawn reward together to use in delegator/owner reward calculations */ function getCumulativeReward() public view returns (uint256) { return getAvailableReward().add(totalWithdrawnReward); } /** * @notice Get available reward in tokens for worker node owner */ function getAvailableWorkerReward() public view returns (uint256) { // total current and historical reward uint256 reward = getCumulativeReward(); // calculate total reward for worker including historical reward uint256 maxAllowableReward; // usual case if (totalDepositedTokens != 0) { uint256 fraction = getWorkerFraction(); maxAllowableReward = reward.mul(fraction).div(BASIS_FRACTION); // special case when there are no delegators } else { maxAllowableReward = reward; } // check that worker has any new reward if (maxAllowableReward > workerWithdrawnReward) { return maxAllowableReward - workerWithdrawnReward; } return 0; } /** * @notice Get available reward in tokens for delegator */ function getAvailableDelegatorReward(address _delegator) public view returns (uint256) { // special case when there are no delegators if (totalDepositedTokens == 0) { return 0; } // total current and historical reward uint256 reward = getCumulativeReward(); Delegator storage delegator = delegators[_delegator]; uint256 fraction = getWorkerFraction(); // calculate total reward for delegator including historical reward // excluding worker share uint256 maxAllowableReward = reward.mul(delegator.depositedTokens).mul(BASIS_FRACTION - fraction).div( totalDepositedTokens.mul(BASIS_FRACTION) ); // check that worker has any new reward if (maxAllowableReward > delegator.withdrawnReward) { return maxAllowableReward - delegator.withdrawnReward; } return 0; } /** * @notice Withdraw reward in tokens to worker node owner */ function withdrawWorkerReward() external { require(msg.sender == workerOwner); uint256 balance = token.balanceOf(address(this)); uint256 availableReward = getAvailableWorkerReward(); if (availableReward > balance) { availableReward = balance; } require( availableReward > 0, "There is no available reward to withdraw" ); workerWithdrawnReward = workerWithdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); token.safeTransfer(msg.sender, availableReward); emit TokensWithdrawn(msg.sender, availableReward, 0); } /** * @notice Withdraw reward to delegator * @param _value Amount of tokens to withdraw */ function withdrawTokens(uint256 _value) public override { uint256 balance = token.balanceOf(address(this)); require(_value <= balance, "Not enough tokens in the contract"); Delegator storage delegator = delegators[msg.sender]; uint256 availableReward = getAvailableDelegatorReward(msg.sender); require( _value <= availableReward, "Requested amount of tokens exceeded allowed portion"); delegator.withdrawnReward = delegator.withdrawnReward.add(_value); totalWithdrawnReward = totalWithdrawnReward.add(_value); token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens); } /** * @notice Withdraw reward, deposit and fee to delegator */ function withdrawAll() public { require(isWithdrawAllAllowed(), "Withdraw deposit and reward must be enabled"); uint256 balance = token.balanceOf(address(this)); Delegator storage delegator = delegators[msg.sender]; uint256 availableReward = getAvailableDelegatorReward(msg.sender); uint256 value = availableReward.add(delegator.depositedTokens); require(value <= balance, "Not enough tokens in the contract"); // TODO remove double reading: availableReward and availableWorkerReward use same calls to external contracts uint256 availableWorkerReward = getAvailableWorkerReward(); // potentially could be less then due reward uint256 availableETH = getAvailableDelegatorETH(msg.sender); // prevent losing reward for worker after calculations uint256 workerReward = availableWorkerReward.mul(delegator.depositedTokens).div(totalDepositedTokens); if (workerReward > 0) { require(value.add(workerReward) <= balance, "Not enough tokens in the contract"); token.safeTransfer(workerOwner, workerReward); emit TokensWithdrawn(workerOwner, workerReward, 0); } uint256 withdrawnToDecrease = workerWithdrawnReward.mul(delegator.depositedTokens).div(totalDepositedTokens); workerWithdrawnReward = workerWithdrawnReward.sub(withdrawnToDecrease); totalWithdrawnReward = totalWithdrawnReward.sub(withdrawnToDecrease).sub(delegator.withdrawnReward); totalDepositedTokens = totalDepositedTokens.sub(delegator.depositedTokens); delegator.withdrawnReward = 0; delegator.depositedTokens = 0; token.safeTransfer(msg.sender, value); emit TokensWithdrawn(msg.sender, value, 0); totalWithdrawnETH = totalWithdrawnETH.sub(delegator.withdrawnETH); delegator.withdrawnETH = 0; if (availableETH > 0) { emit ETHWithdrawn(msg.sender, availableETH); msg.sender.sendValue(availableETH); } } /** * @notice Get available ether for delegator */ function getAvailableDelegatorETH(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; uint256 balance = address(this).balance; // ETH balance + already withdrawn balance = balance.add(totalWithdrawnETH); uint256 maxAllowableETH = balance.mul(delegator.depositedTokens).div(totalDepositedTokens); uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Withdraw available amount of ETH to delegator */ function withdrawETH() public override { Delegator storage delegator = delegators[msg.sender]; uint256 availableETH = getAvailableDelegatorETH(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); emit ETHWithdrawn(msg.sender, availableETH); msg.sender.sendValue(availableETH); } /** * @notice Calling fallback function is allowed only for the owner */ function isFallbackAllowed() public override view returns (bool) { return msg.sender == owner(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract holds tokens for vesting. * Also tokens can be used as a stake in the staking escrow contract */ contract PreallocationEscrow is AbstractStakingContract, Ownable { using SafeMath for uint256; using SafeERC20 for NuCypherToken; using Address for address payable; event TokensDeposited(address indexed sender, uint256 value, uint256 duration); event TokensWithdrawn(address indexed owner, uint256 value); event ETHWithdrawn(address indexed owner, uint256 value); StakingEscrow public immutable stakingEscrow; uint256 public lockedValue; uint256 public endLockTimestamp; /** * @param _router Address of the StakingInterfaceRouter contract */ constructor(StakingInterfaceRouter _router) AbstractStakingContract(_router) { stakingEscrow = _router.target().escrow(); } /** * @notice Initial tokens deposit * @param _sender Token sender * @param _value Amount of token to deposit * @param _duration Duration of tokens locking */ function initialDeposit(address _sender, uint256 _value, uint256 _duration) internal { require(lockedValue == 0 && _value > 0); endLockTimestamp = block.timestamp.add(_duration); lockedValue = _value; token.safeTransferFrom(_sender, address(this), _value); emit TokensDeposited(_sender, _value, _duration); } /** * @notice Initial tokens deposit * @param _value Amount of token to deposit * @param _duration Duration of tokens locking */ function initialDeposit(uint256 _value, uint256 _duration) external { initialDeposit(msg.sender, _value, _duration); } /** * @notice Implementation of the receiveApproval(address,uint256,address,bytes) method * (see NuCypherToken contract). Initial tokens deposit * @param _from Sender * @param _value Amount of tokens to deposit * @param _tokenContract Token contract address * @notice (param _extraData) Amount of seconds during which tokens will be locked */ function receiveApproval( address _from, uint256 _value, address _tokenContract, bytes calldata /* _extraData */ ) external { require(_tokenContract == address(token) && msg.sender == address(token)); // Copy first 32 bytes from _extraData, according to calldata memory layout: // // 0x00: method signature 4 bytes // 0x04: _from 32 bytes after encoding // 0x24: _value 32 bytes after encoding // 0x44: _tokenContract 32 bytes after encoding // 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter) // 0x84: _extraData length 32 bytes // 0xA4: _extraData data Length determined by previous variable // // See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples uint256 payloadSize; uint256 payload; assembly { payloadSize := calldataload(0x84) payload := calldataload(0xA4) } payload = payload >> 8*(32 - payloadSize); initialDeposit(_from, _value, payload); } /** * @notice Get locked tokens value */ function getLockedTokens() public view returns (uint256) { if (endLockTimestamp <= block.timestamp) { return 0; } return lockedValue; } /** * @notice Withdraw available amount of tokens to owner * @param _value Amount of token to withdraw */ function withdrawTokens(uint256 _value) public override onlyOwner { uint256 balance = token.balanceOf(address(this)); require(balance >= _value); // Withdrawal invariant for PreallocationEscrow: // After withdrawing, the sum of all escrowed tokens (either here or in StakingEscrow) must exceed the locked amount require(balance - _value + stakingEscrow.getAllTokens(address(this)) >= getLockedTokens()); token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value); } /** * @notice Withdraw available ETH to the owner */ function withdrawETH() public override onlyOwner { uint256 balance = address(this).balance; require(balance != 0); msg.sender.sendValue(balance); emit ETHWithdrawn(msg.sender, balance); } /** * @notice Calling fallback function is allowed only for the owner */ function isFallbackAllowed() public view override returns (bool) { return msg.sender == owner(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract acts as delegate for sub-stakers and owner * @author @vzotova and @roma_k **/ contract WorkLockPoolingContract is InitializableStakingContract, Ownable { using SafeMath for uint256; using Address for address payable; using SafeERC20 for NuCypherToken; event TokensDeposited( address indexed sender, uint256 value, uint256 depositedTokens ); event TokensWithdrawn( address indexed sender, uint256 value, uint256 depositedTokens ); event ETHWithdrawn(address indexed sender, uint256 value); event DepositSet(address indexed sender, bool value); event Bid(address indexed sender, uint256 depositedETH); event Claimed(address indexed sender, uint256 claimedTokens); event Refund(address indexed sender, uint256 refundETH); struct Delegator { uint256 depositedTokens; uint256 withdrawnReward; uint256 withdrawnETH; uint256 depositedETHWorkLock; uint256 refundedETHWorkLock; bool claimedWorkLockTokens; } uint256 public constant BASIS_FRACTION = 100; StakingEscrow public escrow; WorkLock public workLock; address public workerOwner; uint256 public totalDepositedTokens; uint256 public workLockClaimedTokens; uint256 public totalWithdrawnReward; uint256 public totalWithdrawnETH; uint256 public totalWorkLockETHReceived; uint256 public totalWorkLockETHRefunded; uint256 public totalWorkLockETHWithdrawn; uint256 workerFraction; uint256 public workerWithdrawnReward; mapping(address => Delegator) public delegators; bool depositIsEnabled = true; /** * @notice Initialize function for using with OpenZeppelin proxy * @param _workerFraction Share of token reward that worker node owner will get. * Use value up to BASIS_FRACTION, if _workerFraction = BASIS_FRACTION -> means 100% reward as commission * @param _router StakingInterfaceRouter address * @param _workerOwner Owner of worker node, only this address can withdraw worker commission */ function initialize( uint256 _workerFraction, StakingInterfaceRouter _router, address _workerOwner ) public initializer { require(_workerOwner != address(0) && _workerFraction <= BASIS_FRACTION); InitializableStakingContract.initialize(_router); _transferOwnership(msg.sender); escrow = _router.target().escrow(); workLock = _router.target().workLock(); workerFraction = _workerFraction; workerOwner = _workerOwner; } /** * @notice Enabled deposit */ function enableDeposit() external onlyOwner { depositIsEnabled = true; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Disable deposit */ function disableDeposit() external onlyOwner { depositIsEnabled = false; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Calculate worker's fraction depending on deposited tokens */ function getWorkerFraction() public view returns (uint256) { return workerFraction; } /** * @notice Transfer tokens as delegator * @param _value Amount of tokens to transfer */ function depositTokens(uint256 _value) external { require(depositIsEnabled, "Deposit must be enabled"); require(_value > 0, "Value must be not empty"); totalDepositedTokens = totalDepositedTokens.add(_value); Delegator storage delegator = delegators[msg.sender]; delegator.depositedTokens = delegator.depositedTokens.add(_value); token.safeTransferFrom(msg.sender, address(this), _value); emit TokensDeposited(msg.sender, _value, delegator.depositedTokens); } /** * @notice Delegator can transfer ETH directly to workLock */ function escrowETH() external payable { Delegator storage delegator = delegators[msg.sender]; delegator.depositedETHWorkLock = delegator.depositedETHWorkLock.add(msg.value); totalWorkLockETHReceived = totalWorkLockETHReceived.add(msg.value); workLock.bid{value: msg.value}(); emit Bid(msg.sender, msg.value); } /** * @dev Hide method from StakingInterface */ function bid(uint256) public payable { revert(); } /** * @dev Hide method from StakingInterface */ function withdrawCompensation() public pure { revert(); } /** * @dev Hide method from StakingInterface */ function cancelBid() public pure { revert(); } /** * @dev Hide method from StakingInterface */ function claim() public pure { revert(); } /** * @notice Claim tokens in WorkLock and save number of claimed tokens */ function claimTokensFromWorkLock() public { workLockClaimedTokens = workLock.claim(); totalDepositedTokens = totalDepositedTokens.add(workLockClaimedTokens); emit Claimed(address(this), workLockClaimedTokens); } /** * @notice Calculate and save number of claimed tokens for specified delegator */ function calculateAndSaveTokensAmount() external { Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); } /** * @notice Calculate and save number of claimed tokens for specified delegator */ function calculateAndSaveTokensAmount(Delegator storage _delegator) internal { if (workLockClaimedTokens == 0 || _delegator.depositedETHWorkLock == 0 || _delegator.claimedWorkLockTokens) { return; } uint256 delegatorTokensShare = _delegator.depositedETHWorkLock.mul(workLockClaimedTokens) .div(totalWorkLockETHReceived); _delegator.depositedTokens = _delegator.depositedTokens.add(delegatorTokensShare); _delegator.claimedWorkLockTokens = true; emit Claimed(msg.sender, delegatorTokensShare); } /** * @notice Get available reward for all delegators and owner */ function getAvailableReward() public view returns (uint256) { uint256 stakedTokens = escrow.getAllTokens(address(this)); uint256 freeTokens = token.balanceOf(address(this)); uint256 reward = stakedTokens.add(freeTokens).sub(totalDepositedTokens); if (reward > freeTokens) { return freeTokens; } return reward; } /** * @notice Get cumulative reward */ function getCumulativeReward() public view returns (uint256) { return getAvailableReward().add(totalWithdrawnReward); } /** * @notice Get available reward in tokens for worker node owner */ function getAvailableWorkerReward() public view returns (uint256) { uint256 reward = getCumulativeReward(); uint256 maxAllowableReward; if (totalDepositedTokens != 0) { uint256 fraction = getWorkerFraction(); maxAllowableReward = reward.mul(fraction).div(BASIS_FRACTION); } else { maxAllowableReward = reward; } if (maxAllowableReward > workerWithdrawnReward) { return maxAllowableReward - workerWithdrawnReward; } return 0; } /** * @notice Get available reward in tokens for delegator */ function getAvailableReward(address _delegator) public view returns (uint256) { if (totalDepositedTokens == 0) { return 0; } uint256 reward = getCumulativeReward(); Delegator storage delegator = delegators[_delegator]; uint256 fraction = getWorkerFraction(); uint256 maxAllowableReward = reward.mul(delegator.depositedTokens).mul(BASIS_FRACTION - fraction).div( totalDepositedTokens.mul(BASIS_FRACTION) ); return maxAllowableReward > delegator.withdrawnReward ? maxAllowableReward - delegator.withdrawnReward : 0; } /** * @notice Withdraw reward in tokens to worker node owner */ function withdrawWorkerReward() external { require(msg.sender == workerOwner); uint256 balance = token.balanceOf(address(this)); uint256 availableReward = getAvailableWorkerReward(); if (availableReward > balance) { availableReward = balance; } require( availableReward > 0, "There is no available reward to withdraw" ); workerWithdrawnReward = workerWithdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); token.safeTransfer(msg.sender, availableReward); emit TokensWithdrawn(msg.sender, availableReward, 0); } /** * @notice Withdraw reward to delegator * @param _value Amount of tokens to withdraw */ function withdrawTokens(uint256 _value) public override { uint256 balance = token.balanceOf(address(this)); require(_value <= balance, "Not enough tokens in the contract"); Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); uint256 availableReward = getAvailableReward(msg.sender); require( _value <= availableReward, "Requested amount of tokens exceeded allowed portion"); delegator.withdrawnReward = delegator.withdrawnReward.add(_value); totalWithdrawnReward = totalWithdrawnReward.add(_value); token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens); } /** * @notice Withdraw reward, deposit and fee to delegator */ function withdrawAll() public { uint256 balance = token.balanceOf(address(this)); Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); uint256 availableReward = getAvailableReward(msg.sender); uint256 value = availableReward.add(delegator.depositedTokens); require(value <= balance, "Not enough tokens in the contract"); // TODO remove double reading uint256 availableWorkerReward = getAvailableWorkerReward(); // potentially could be less then due reward uint256 availableETH = getAvailableETH(msg.sender); // prevent losing reward for worker after calculations uint256 workerReward = availableWorkerReward.mul(delegator.depositedTokens).div(totalDepositedTokens); if (workerReward > 0) { require(value.add(workerReward) <= balance, "Not enough tokens in the contract"); token.safeTransfer(workerOwner, workerReward); emit TokensWithdrawn(workerOwner, workerReward, 0); } uint256 withdrawnToDecrease = workerWithdrawnReward.mul(delegator.depositedTokens).div(totalDepositedTokens); workerWithdrawnReward = workerWithdrawnReward.sub(withdrawnToDecrease); totalWithdrawnReward = totalWithdrawnReward.sub(withdrawnToDecrease).sub(delegator.withdrawnReward); totalDepositedTokens = totalDepositedTokens.sub(delegator.depositedTokens); delegator.withdrawnReward = 0; delegator.depositedTokens = 0; token.safeTransfer(msg.sender, value); emit TokensWithdrawn(msg.sender, value, 0); totalWithdrawnETH = totalWithdrawnETH.sub(delegator.withdrawnETH); delegator.withdrawnETH = 0; if (availableETH > 0) { msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } } /** * @notice Get available ether for delegator */ function getAvailableETH(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; uint256 balance = address(this).balance; // ETH balance + already withdrawn - (refunded - refundWithdrawn) balance = balance.add(totalWithdrawnETH).add(totalWorkLockETHWithdrawn).sub(totalWorkLockETHRefunded); uint256 maxAllowableETH = balance.mul(delegator.depositedTokens).div(totalDepositedTokens); uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Withdraw available amount of ETH to delegator */ function withdrawETH() public override { Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); uint256 availableETH = getAvailableETH(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } /** * @notice Withdraw compensation and refund from WorkLock and save these numbers */ function refund() public { uint256 balance = address(this).balance; if (workLock.compensation(address(this)) > 0) { workLock.withdrawCompensation(); } workLock.refund(); uint256 refundETH = address(this).balance - balance; totalWorkLockETHRefunded = totalWorkLockETHRefunded.add(refundETH); emit Refund(address(this), refundETH); } /** * @notice Get available refund for delegator */ function getAvailableRefund(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; uint256 maxAllowableETH = totalWorkLockETHRefunded.mul(delegator.depositedETHWorkLock) .div(totalWorkLockETHReceived); uint256 availableETH = maxAllowableETH.sub(delegator.refundedETHWorkLock); uint256 balance = totalWorkLockETHRefunded.sub(totalWorkLockETHWithdrawn); if (availableETH > balance) { availableETH = balance; } return availableETH; } /* * @notice Withdraw available amount of ETH to delegator */ function withdrawRefund() external { uint256 availableETH = getAvailableRefund(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); Delegator storage delegator = delegators[msg.sender]; delegator.refundedETHWorkLock = delegator.refundedETHWorkLock.add(availableETH); totalWorkLockETHWithdrawn = totalWorkLockETHWithdrawn.add(availableETH); msg.sender.sendValue(availableETH); emit Refund(msg.sender, availableETH); } /** * @notice Calling fallback function is allowed only for the owner */ function isFallbackAllowed() public override view returns (bool) { return msg.sender == owner(); } }
Withdraw available amount of ETH to delegator/
function withdrawRefund() external { uint256 availableETH = getAvailableRefund(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); Delegator storage delegator = delegators[msg.sender]; delegator.refundedETHWorkLock = delegator.refundedETHWorkLock.add(availableETH); totalWorkLockETHWithdrawn = totalWorkLockETHWithdrawn.add(availableETH); msg.sender.sendValue(availableETH); emit Refund(msg.sender, availableETH); }
1,393,668
./full_match/1/0xE83B94ECA0e76D9cE0119Fe6D37a539623C097D4/sources/contracts/staking/StakingPools.sol
Extends the end block of a pool The function will update the endBlock of a pool and emit a PoolEndBlockExtended event poolId The ID of the pool newEndBlock The new end block for the pool/
function extendEndBlock(uint256 poolId, uint256 newEndBlock) external override onlyOwnerOrFactory onlyPoolExists(poolId) onlyPoolNotEnded(poolId) { uint256 currentEndBlock = poolInfos[poolId].endBlock; require(newEndBlock > currentEndBlock, "StakingPools: end block not extended"); poolInfos[poolId].endBlock = newEndBlock; emit PoolEndBlockExtended(poolId, currentEndBlock, newEndBlock); }
8,402,150
pragma solidity >= 0.5.0 <0.7.0; import "@aztec/protocol/contracts/interfaces/IAZTEC.sol"; import "@aztec/protocol/contracts/libs/NoteUtils.sol"; import "@aztec/protocol/contracts/ERC1724/ZkAsset.sol"; import "./ZKERC20/ZKERC20.sol"; import "./Loan.sol"; contract LoanDapp is IAZTEC { using NoteUtils for bytes; event SettlementCurrencyAdded( uint id, address settlementAddress ); event LoanApprovedForSettlement( address loanId ); event LoanCreated( address id, address borrower, bytes32 notional, string borrowerPublicKey, uint256[] loanVariables, uint createdAt ); event ViewRequestCreated( address loanId, address lender, string lenderPublicKey ); event ViewRequestApproved( uint accessId, address loanId, address user, string sharedSecret ); event NoteAccessApproved( uint accessId, bytes32 note, address user, string sharedSecret ); address owner = msg.sender; address aceAddress; address[] public loans; mapping(uint => address) public settlementCurrencies; uint24 MINT_PRO0F = 66049; uint24 BILATERAL_SWAP_PROOF = 65794; modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyBorrower(address _loanAddress) { Loan loanContract = Loan(_loanAddress); require(msg.sender == loanContract.borrower()); _; } constructor(address _aceAddress) public { aceAddress = _aceAddress; } function _getCurrencyContract(uint _settlementCurrencyId) internal view returns (address) { require(settlementCurrencies[_settlementCurrencyId] != address(0), 'Settlement Currency is not defined'); return settlementCurrencies[_settlementCurrencyId]; } function _generateAccessId(bytes32 _note, address _user) internal pure returns (uint) { return uint(keccak256(abi.encodePacked(_note, _user))); } function _approveNoteAccess( bytes32 _note, address _userAddress, string memory _sharedSecret ) internal { uint accessId = _generateAccessId(_note, _userAddress); emit NoteAccessApproved( accessId, _note, _userAddress, _sharedSecret ); } function _createLoan( bytes32 _notional, uint256[] memory _loanVariables, bytes memory _proofData ) private returns (address) { address loanCurrency = _getCurrencyContract(_loanVariables[3]); Loan newLoan = new Loan( _notional, _loanVariables, msg.sender, aceAddress, loanCurrency ); loans.push(address(newLoan)); Loan loanContract = Loan(address(newLoan)); loanContract.setProofs(1, uint256(-1)); loanContract.confidentialMint(MINT_PROOF, bytes(_proofData)); return address(newLoan); } function addSettlementCurrency(uint _id, address _address) external onlyOwner { settlementCurrencies[_id] = _address; emit SettlementCurrencyAdded(_id, _address); } function createLoan( bytes32 _notional, string calldata _viewingKey, string calldata _borrowerPublicKey, uint256[] calldata _loanVariables, // [0] interestRate // [1] interestPeriod // [2] loanDuration // [3] settlementCurrencyId bytes calldata _proofData ) external { address loanId = _createLoan( _notional, _loanVariables, _proofData ); emit LoanCreated( loanId, msg.sender, _notional, _borrowerPublicKey, _loanVariables, block.timestamp ); _approveNoteAccess( _notional, msg.sender, _viewingKey ); } function approveLoanNotional( bytes32 _noteHash, bytes memory _signature, address _loanId ) public { Loan loanContract = Loan(_loanId); loanContract.confidentialApprove(_noteHash, _loanId, true, _signature); emit LoanApprovedForSettlement(_loanId); } function submitViewRequest(address _loanId, string calldata _lenderPublicKey) external { emit ViewRequestCreated( _loanId, msg.sender, _lenderPublicKey ); } function approveViewRequest( address _loanId, address _lender, bytes32 _notionalNote, string calldata _sharedSecret ) external onlyBorrower(_loanId) { uint accessId = _generateAccessId(_notionalNote, _lender); emit ViewRequestApproved( accessId, _loanId, _lender, _sharedSecret ); } event SettlementSuccesfull( address indexed from, address indexed to, address loanId, uint256 timestamp ); struct LoanPayment { address from; address to; bytes notional; } mapping(uint => mapping(uint => LoanPayment)) public loanPayments; function settleInitialBalance( address _loanId, bytes calldata _proofData, bytes32 _currentInterestBalance ) external { Loan loanContract = Loan(_loanId); loanContract.settleLoan(_proofData, _currentInterestBalance, msg.sender); emit SettlementSuccesfull( msg.sender, loanContract.borrower(), _loanId, block.timestamp ); } function approveNoteAccess( bytes32 _note, string calldata _viewingKey, string calldata _sharedSecret, address _sharedWith ) external { if (bytes(_viewingKey).length != 0) { _approveNoteAccess( _note, msg.sender, _viewingKey ); } if (bytes(_sharedSecret).length != 0) { _approveNoteAccess( _note, _sharedWith, _sharedSecret ); } } }
[0] interestRate [1] interestPeriod [2] loanDuration [3] settlementCurrencyId
function createLoan( bytes32 _notional, string calldata _viewingKey, string calldata _borrowerPublicKey, uint256[] calldata _loanVariables, bytes calldata _proofData ) external { address loanId = _createLoan( _notional, _loanVariables, _proofData ); emit LoanCreated( loanId, msg.sender, _notional, _borrowerPublicKey, _loanVariables, block.timestamp ); _approveNoteAccess( _notional, msg.sender, _viewingKey ); }
923,390
./full_match/4/0x0Cd4aB3C76E1F452d951118c8a3861Ca533cef09/sources/Cryptogotchi.sol
play to earn tokens, increase generationchanging this first stops reentrancy
function play(uint256 tokenId) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "!o"); require(alive(tokenId), "!x"); Device storage device = unit[tokenId]; uint256 timeBetweenPlays = ONE_HOUR.add(device.prestige.mul(ONE_HOUR)); uint256 elapsed = block.timestamp.sub(device.lastPlayTime); uint256 fullCycles = uint256(block.timestamp.sub(device.createdAt)).div(ONE_DAY); require(device.feedLevel != fullCycles, "!f"); require(device.generation <= 10 && device.generation > 0, "!g"); require(elapsed > timeBetweenPlays, "!t"); device.lastPlayTime = block.timestamp; device.generationTicker = device.generationTicker.add(1); generationUp(tokenId); }
816,959
// SPDX-License-Identifier: MIT pragma solidity ^0.8.11; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./NFPeace.sol"; contract NFPeaceV2 is ERC165, IERC721Receiver, IERC1155Receiver, ReentrancyGuard { /// @notice The previous NFPeace (V1) contract. NFPeaceV2 fixes a potential exploit. /// @dev The V1 NFPeace contract NFPeace public constant NFPEACE_V1 = NFPeace(0x0000000011E48D382b4F627437A2bBAc3b10F90e); /// @notice Unchain (https://unchain.fund) is a charity project created by blockchain activists. Its goal is to break the chain of war which the Russian Federation started against Ukraine. /// @dev The wallet address of the humanitarian relief fund unchain.fund address payable public constant CHARITY_ADDRESS = payable(0x10E1439455BD2624878b243819E31CfEE9eb721C); /// @notice Minimum auction duration after a bid in seconds (15 minutes). /// @dev Minimum auction runtime in seconds after new bids uint32 public constant BIDDING_GRACE_PERIOD = 15 minutes; /// @notice Each bid has to increase by at least 10% /// @dev The minimum percentage increase per bid uint32 public constant BID_PERCENTAGE_INCREASE = 10; /// @dev The minimum value of an auction uint64 public constant DEFAULT_STARTING_PRICE = 0.05 ether; /// @dev The initial auction ID of the V2 NFPeace contract uint64 public initialAuctionId = 0; /// @dev The next auction ID uint64 public nextAuctionId = 0; struct Auction { address tokenContract; uint256 tokenId; address latestBidder; uint128 latestBid; uint64 startingPrice; // max ~18.44 Ether uint32 endTimestamp; // latest date is Sun Feb 07 2106 06:28:15 GMT (in 84 years) uint16 tokenERCStandard; uint8 tokenAmount; bool settled; } /// @dev Each auction is identified by an ID mapping(uint256 => Auction) private _auctions; /// @dev When the automatic refunds of previous bids fail, they are stored in here mapping(address => uint256) private _balances; /// @dev Emitted when an NFT is sent to the contract. event AuctionInitialised(uint64 indexed auctionId); /// @dev Emitted when a new bid is entered. event Bid(uint64 indexed auctionId, uint256 indexed bid, address indexed from); /// @dev Emitted when a new bid is entered within the BIDDING_GRACE_PERIOD. event AuctionExtended(uint64 indexed auctionId, uint256 indexed endTimestamp); /// @dev Emitted when an auction is settled, the NFT is sent to the winner and the funds sent to the charity. event AuctionSettled(uint64 indexed auctionId); /// @dev Set the initial tokenID. constructor () { initialAuctionId = NFPEACE_V1.nextAuctionId(); nextAuctionId = initialAuctionId; } /// @dev Get an Auction by its ID function getAuction (uint64 auctionId) public view returns ( address tokenContract, uint256 tokenId, address latestBidder, uint128 latestBid, uint64 startingPrice, uint32 endTimestamp, uint16 tokenERCStandard, uint8 tokenAmount, bool settled ) { // Proxy V1 auctions through to the V1 contract. if (auctionId < initialAuctionId) { return NFPEACE_V1.getAuction(auctionId); } Auction memory auction = _auctions[auctionId]; return ( auction.tokenContract, auction.tokenId, auction.latestBidder, auction.latestBid, auction.startingPrice, auction.endTimestamp, auction.tokenERCStandard, auction.tokenAmount, auction.settled ); } /// @dev The minimum value of the next bid for an auction. function currentBidPrice (uint64 auctionId) external view returns (uint128) { return _currentBidPrice(_auctions[auctionId]); } /// @dev Enter a new bid /// @param auctionId The Auction ID to bid on function bid (uint64 auctionId) external payable nonReentrant { Auction storage auction = _auctions[auctionId]; uint256 bidValue = msg.value; address bidder = msg.sender; require(bidValue >= _currentBidPrice(auction), "Minimum bid value not met."); require(block.timestamp <= auction.endTimestamp, "Auction is not active."); // Pay back previous bidder if (_hasBid(auction)) { if (!payable(auction.latestBidder).send(auction.latestBid)) { _balances[auction.latestBidder] += auction.latestBid; } } _maybeExtendTime(auctionId, auction); // Store the bid auction.latestBid = uint128(bidValue); auction.latestBidder = bidder; emit Bid(auctionId, bidValue, bidder); } /// @dev Settles an auction /// @param auctionId The Auction ID to claim. function settle (uint64 auctionId) external { Auction storage auction = _auctions[auctionId]; require(!auction.settled, "Auction already settled."); require(auction.endTimestamp > 0, "Auction does not exist."); require(block.timestamp > auction.endTimestamp, "Auction not complete."); if (_hasBid(auction)) { (bool success,) = CHARITY_ADDRESS.call{ value: auction.latestBid }(""); require(success, "Failed to forward funds"); } if (auction.tokenERCStandard == 721) { IERC721(auction.tokenContract).safeTransferFrom(address(this), auction.latestBidder, auction.tokenId, ""); } else if (auction.tokenERCStandard == 1155) { IERC1155(auction.tokenContract).safeTransferFrom(address(this), auction.latestBidder, auction.tokenId, auction.tokenAmount, ""); } // End the auction auction.settled = true; emit AuctionSettled(auctionId); } /// @dev Get the balance for an address. function getBalance (address _address) external view returns (uint256) { return _balances[_address]; } /// @dev Withdraw user balance in case automatic refund in bid failed. function withdraw () external { uint256 amount = _balances[msg.sender]; require(amount > 0, "No balance to withdraw."); // Set balance to zero because it could be called again in receive before send returns _balances[msg.sender] = 0; if (!payable(msg.sender).send(amount)) { _balances[msg.sender] = amount; } } /// @dev Hook for `saveTransferFrom` of ERC721 tokens to this contract /// @param from The address which previously owned the token /// @param tokenId The ID of the token being transferred /// @param data The custom starting price (set by a user) function onERC721Received( address, address from, uint256 tokenId, bytes calldata data ) public override returns (bytes4) { _initializeAuction(tokenId, 721, from, _getStartingPrice(data), 1); return IERC721Receiver.onERC721Received.selector; } /// @dev Hook for `saveTransferFrom` of ERC1155 tokens to this contract /// @param from The address which previously owned the token /// @param id The ID of the token being transferred /// @param value The amount of tokens being transferred /// @param data The custom starting price (set by a user) function onERC1155Received( address, address from, uint256 id, uint256 value, bytes calldata data ) public override returns (bytes4) { require(value < 256, "Too many tokens"); _initializeAuction(id, 1155, from, _getStartingPrice(data), uint8(value)); return IERC1155Receiver.onERC1155Received.selector; } /// @dev Hook for `safeBatchTransferFrom` of ERC1155 tokens to this contract /// @param operator The address which initiated the transfer /// @param from The address which previously owned the token /// @param ids An array containing ids of each token being transferred (order and length must match values array) /// @param values An array containing amounts of each token being transferred (order and length must match ids array) /// @param data The custom starting price (set by a user) function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override returns (bytes4) { for (uint256 index = 0; index < ids.length; index++) { onERC1155Received(operator, from, ids[index], values[index], data); } return IERC1155Receiver.onERC1155BatchReceived.selector; } /// @dev Get the starting price based on default or user input. Warns users about out of range price. function _getStartingPrice (bytes calldata data) internal pure returns (uint64) { uint64 price = toUint64(data); return price > DEFAULT_STARTING_PRICE ? price : DEFAULT_STARTING_PRICE; } /// @dev Initializes an auction function _initializeAuction ( uint256 tokenId, uint16 tokenERCStandard, address tokenOwner, uint64 startingPrice, uint8 tokenAmount ) internal { _auctions[nextAuctionId] = Auction( msg.sender, // the NFT token contract tokenId, // the NFT token ID tokenOwner, // the token owner can claim for free if no one bids 0, // no bid has been placed (latestBid = 0) startingPrice, // minimum bid (can be customised per auction) uint32(block.timestamp + 24 hours), // auction ends 24 hours from now tokenERCStandard, // ERC721 or ERC1155 tokenAmount, // the number of tokens with that ID (for ERC1155) false // the auction is not settled ); emit AuctionInitialised(nextAuctionId); nextAuctionId++; } /// @dev Extends the end time of an auction if we are within the grace period. function _maybeExtendTime (uint64 auctionId, Auction storage auction) internal { uint64 gracePeriodStart = auction.endTimestamp - BIDDING_GRACE_PERIOD; uint64 _now = uint64(block.timestamp); if (_now > gracePeriodStart) { auction.endTimestamp = uint32(_now + BIDDING_GRACE_PERIOD); emit AuctionExtended(auctionId, auction.endTimestamp); } } /// @dev Whether an auction has an existing bid function _hasBid (Auction memory auction) internal pure returns (bool) { return auction.latestBid > 0; } /// @dev Calculates the minimum price for the next bid function _currentBidPrice (Auction memory auction) internal pure returns (uint128) { if (! _hasBid(auction)) { return auction.startingPrice; } uint128 percentageIncreasePrice = auction.latestBid * (100 + BID_PERCENTAGE_INCREASE) / 100; return percentageIncreasePrice - auction.latestBid < auction.startingPrice ? auction.latestBid + auction.startingPrice : percentageIncreasePrice; } /// @dev Transform a bytes string into a uint64. If no string provided, return 0 function toUint64(bytes memory _bytes) internal pure returns (uint64) { if (_bytes.length == 0) return 0; require(_bytes.length <= 8, "toUint64_outOfBounds"); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), 0)) } return tempUint; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.11; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; contract NFPeace is ERC165, IERC721Receiver, IERC1155Receiver, ReentrancyGuard { /// @notice Unchain (https://unchain.fund) is a charity project created by blockchain activists. Its goal is to break the chain of war which the Russian Federation started against Ukraine. /// @dev The wallet address of the humanitarian relief fund unchain.fund address payable public constant CHARITY_ADDRESS = payable(0x10E1439455BD2624878b243819E31CfEE9eb721C); /// @notice Minimum auction duration after a bid in seconds (15 minutes). /// @dev Minimum auction runtime in seconds after new bids uint32 public constant BIDDING_GRACE_PERIOD = 15 minutes; /// @notice Each bid has to increase by at least 10% /// @dev The minimum percentage increase per bid uint32 public constant BID_PERCENTAGE_INCREASE = 10; /// @dev The minimum value of an auction uint64 public constant DEFAULT_STARTING_PRICE = 0.05 ether; /// @dev The next auction ID uint64 public nextAuctionId = 0; struct Auction { address tokenContract; uint256 tokenId; address latestBidder; uint128 latestBid; uint64 startingPrice; // max ~18.44 Ether uint32 endTimestamp; // latest date is Sun Feb 07 2106 06:28:15 GMT (in 84 years) uint16 tokenERCStandard; uint8 tokenAmount; bool settled; } /// @dev Each auction is identified by an ID mapping(uint256 => Auction) private _auctions; /// @dev Emitted when an NFT is sent to the contract. event AuctionInitialised(uint64 indexed auctionId); /// @dev Emitted when a new bid is entered. event Bid(uint64 indexed auctionId, uint256 indexed bid, address indexed from); /// @dev Emitted when a new bid is entered within the BIDDING_GRACE_PERIOD. event AuctionExtended(uint64 indexed auctionId, uint256 indexed endTimestamp); /// @dev Emitted when an auction is settled, the NFT is sent to the winner and the funds sent to the charity. event AuctionSettled(uint64 indexed auctionId); /// @dev Get an Auction by its ID function getAuction (uint64 auctionId) public view returns ( address tokenContract, uint256 tokenId, address latestBidder, uint128 latestBid, uint64 startingPrice, uint32 endTimestamp, uint16 tokenERCStandard, uint8 tokenAmount, bool settled ) { Auction memory auction = _auctions[auctionId]; return ( auction.tokenContract, auction.tokenId, auction.latestBidder, auction.latestBid, auction.startingPrice, auction.endTimestamp, auction.tokenERCStandard, auction.tokenAmount, auction.settled ); } /// @dev The minimum value of the next bid for an auction. function currentBidPrice (uint64 auctionId) external view returns (uint128) { return _currentBidPrice(_auctions[auctionId]); } /// @dev Enter a new bid /// @param auctionId The Auction ID to bid on function bid (uint64 auctionId) external payable nonReentrant { Auction storage auction = _auctions[auctionId]; uint256 bidValue = msg.value; address bidder = msg.sender; require(bidValue >= _currentBidPrice(auction), "Minimum bid value not met."); require(block.timestamp <= auction.endTimestamp, "Auction is not active."); // Pay back previous bidder if (_hasBid(auction)) { payable(auction.latestBidder).transfer(auction.latestBid); } _maybeExtendTime(auctionId, auction); // Store the bid auction.latestBid = uint128(bidValue); auction.latestBidder = bidder; emit Bid(auctionId, bidValue, bidder); } /// @dev Settles an auction /// @param auctionId The Auction ID to claim. function settle (uint64 auctionId) external { Auction storage auction = _auctions[auctionId]; require(!auction.settled, "Auction already settled."); require(auction.endTimestamp > 0, "Auction does not exist."); require(block.timestamp > auction.endTimestamp, "Auction not complete."); if (_hasBid(auction)) { (bool success,) = CHARITY_ADDRESS.call{ value: auction.latestBid }(""); require(success, "Failed to forward funds"); } if (auction.tokenERCStandard == 721) { IERC721(auction.tokenContract).safeTransferFrom(address(this), auction.latestBidder, auction.tokenId, ""); } else if (auction.tokenERCStandard == 1155) { IERC1155(auction.tokenContract).safeTransferFrom(address(this), auction.latestBidder, auction.tokenId, auction.tokenAmount, ""); } // End the auction auction.settled = true; emit AuctionSettled(auctionId); } /// @dev Hook for `saveTransferFrom` of ERC721 tokens to this contract /// @param from The address which previously owned the token /// @param tokenId The ID of the token being transferred /// @param data The custom starting price (set by a user) function onERC721Received( address, address from, uint256 tokenId, bytes calldata data ) public override returns (bytes4) { _initializeAuction(tokenId, 721, from, _getStartingPrice(data), 1); return IERC721Receiver.onERC721Received.selector; } /// @dev Hook for `saveTransferFrom` of ERC1155 tokens to this contract /// @param from The address which previously owned the token /// @param id The ID of the token being transferred /// @param value The amount of tokens being transferred /// @param data The custom starting price (set by a user) function onERC1155Received( address, address from, uint256 id, uint256 value, bytes calldata data ) public override returns (bytes4) { require(value < 256, "Too many tokens"); _initializeAuction(id, 1155, from, _getStartingPrice(data), uint8(value)); return IERC1155Receiver.onERC1155Received.selector; } /// @dev Hook for `safeBatchTransferFrom` of ERC1155 tokens to this contract /// @param operator The address which initiated the transfer /// @param from The address which previously owned the token /// @param ids An array containing ids of each token being transferred (order and length must match values array) /// @param values An array containing amounts of each token being transferred (order and length must match ids array) /// @param data The custom starting price (set by a user) function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override returns (bytes4) { for (uint256 index = 0; index < ids.length; index++) { onERC1155Received(operator, from, ids[index], values[index], data); } return IERC1155Receiver.onERC1155BatchReceived.selector; } /// @dev Get the starting price based on default or user input. Warns users about out of range price. function _getStartingPrice (bytes calldata data) internal pure returns (uint64) { uint64 price = toUint64(data); return price > DEFAULT_STARTING_PRICE ? price : DEFAULT_STARTING_PRICE; } /// @dev Initializes an auction function _initializeAuction ( uint256 tokenId, uint16 tokenERCStandard, address tokenOwner, uint64 startingPrice, uint8 tokenAmount ) internal { _auctions[nextAuctionId] = Auction( msg.sender, // the NFT token contract tokenId, // the NFT token ID tokenOwner, // the token owner can claim for free if no one bids 0, // no bid has been placed (latestBid = 0) startingPrice, // minimum bid (can be customised per auction) uint32(block.timestamp + 24 hours), // auction ends 24 hours from now tokenERCStandard, // ERC721 or ERC1155 tokenAmount, // the number of tokens with that ID (for ERC1155) false // the auction is not settled ); emit AuctionInitialised(nextAuctionId); nextAuctionId++; } /// @dev Extends the end time of an auction if we are within the grace period. function _maybeExtendTime (uint64 auctionId, Auction storage auction) internal { uint64 gracePeriodStart = auction.endTimestamp - BIDDING_GRACE_PERIOD; uint64 _now = uint64(block.timestamp); if (_now > gracePeriodStart) { auction.endTimestamp = uint32(_now + BIDDING_GRACE_PERIOD); emit AuctionExtended(auctionId, auction.endTimestamp); } } /// @dev Whether an auction has an existing bid function _hasBid (Auction memory auction) internal pure returns (bool) { return auction.latestBid > 0; } /// @dev Calculates the minimum price for the next bid function _currentBidPrice (Auction memory auction) internal pure returns (uint128) { if (! _hasBid(auction)) { return auction.startingPrice; } uint128 percentageIncreasePrice = auction.latestBid * (100 + BID_PERCENTAGE_INCREASE) / 100; return percentageIncreasePrice - auction.latestBid < auction.startingPrice ? auction.latestBid + auction.startingPrice : percentageIncreasePrice; } /// @dev Transform a bytes string into a uint64. If no string provided, return 0 function toUint64(bytes memory _bytes) internal pure returns (uint64) { if (_bytes.length == 0) return 0; require(_bytes.length <= 8, "toUint64_outOfBounds"); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), 0)) } return tempUint; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Get the starting price based on default or user input. Warns users about out of range price.
function _getStartingPrice (bytes calldata data) internal pure returns (uint64) { uint64 price = toUint64(data); return price > DEFAULT_STARTING_PRICE ? price : DEFAULT_STARTING_PRICE; }
1,280,154
pragma solidity ^0.5.0; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./FlightSuretyData.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) FlightSuretyData flightSuretyData; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; uint8 private constant MINIMUM_AIRLINES_TO_VOTE = 4; uint public constant FUND_AIRLINE_PRICE = 10000000000000000000; address payable contractOwner; // Account used to deploy contract struct Flight { address airline; bool isRegistered; bytes32 flightKey; string flightNumber; uint8 statusCode; uint256 timestamp; } mapping(bytes32 => Flight) private flights; bytes32[] private regIndexFlight; bool public operational; /********************************************************************************************/ /* EVENTS */ /********************************************************************************************/ event OperationalStatusChanged(bool mode); event airlinePaid(address airline, uint256 value); event registeredFlight(address airline, bool isRegistered, bytes32 flightKey, string flightNumber, uint8 statusCode, uint256 timestamp); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { // Modify to call data contract's status require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } modifier differentModeRequest(bool status) { require(status != operational, "Contract already in the state requested"); _; } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireNotSubmittedAirline(address _airline) { require(!flightSuretyData.isSubmitted(_airline), "Airline is already submitted"); _; } modifier requireIsSubmittedAirline(address _airline) { require(flightSuretyData.isSubmitted(_airline), "Airline is not submitted"); _; } modifier requireIsRegisteredAirline() { require(flightSuretyData.isRegistered(msg.sender), "Airline is not Registered"); _; } modifier requireAirlineIsFunded() { require(flightSuretyData.isFunded(msg.sender), "Airline is not funded"); _; } modifier requireNotVoted(address _airline) { require(!flightSuretyData.isVotedBy(_airline), "Already voted"); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor(address payable _dataContract) public { flightSuretyData = FlightSuretyData(_dataContract); contractOwner = msg.sender; operational = true; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** @dev Get operating status of contract *** @return A bool that is the current operating status*/ function isOperational() public view returns(bool){ return operational; } /** @dev Sets contract operations on/off *** When operational mode is disabled, all write transactions except for this one will fail*/ function setOperatingStatus(bool mode) external requireContractOwner differentModeRequest(mode) returns(bool){ operational = mode; emit OperationalStatusChanged(mode); return mode; } /** @dev getting balance of funds held in this contract address**/ function getBalance() public view requireIsOperational returns (uint256) { return address(this).balance; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** @dev Add an airline*/ function submitAirline(address _airline) external requireIsOperational requireNotSubmittedAirline(_airline) returns(address) { require(msg.sender == _airline, "It is not your address"); flightSuretyData.submitAirline(_airline); return (_airline); } /** @dev Vote an airline*/ function voteAirline(address _airline) external requireIsOperational requireAirlineIsFunded requireNotVoted(_airline) returns(address, address) { if (flightSuretyData.numAirlinesFunded() < MINIMUM_AIRLINES_TO_VOTE) { require(flightSuretyData.getFirstAirline() == msg.sender, "You are not the first airline"); } else { require(_airline != msg.sender, "You can't vote for yourself"); } flightSuretyData.voteAirline(_airline); return (_airline, msg.sender); } /** @dev Add an airline to the registration queue*/ function registerAirline(address _airline) external requireIsOperational requireAirlineIsFunded requireIsSubmittedAirline(_airline) returns(address, address) { if (flightSuretyData.numAirlinesFunded() < MINIMUM_AIRLINES_TO_VOTE) { require(flightSuretyData.getFirstAirline() == msg.sender, "You are not the first airline"); } if (flightSuretyData.numAirlinesFunded() >= MINIMUM_AIRLINES_TO_VOTE) { uint airlinesFunded = flightSuretyData.numAirlinesFunded(); uint8 votes = flightSuretyData.getVotesAirline(_airline); require(airlinesFunded.div(2) <= votes, "Has not passed the consensus"); } flightSuretyData.registerAirline(_airline); return (_airline, msg.sender); } /** @dev pay for registering Airline**/ function fundAirline() external payable requireIsOperational requireIsRegisteredAirline { address payable payableAccount = address(uint160(address(flightSuretyData))); require(msg.value == FUND_AIRLINE_PRICE, "Insufficient founds, 10 eth"); payableAccount.transfer(msg.value); flightSuretyData.fundAirline(msg.sender); } /** @dev Get airline status**/ function getAirlineStatus(address _airline) external view returns(address, bool, bool, bool, uint256, uint256) { return flightSuretyData.getAirline(_airline); } /** @dev Register a future flight for insuring.**/ function getAirlines() external view returns(address[] memory) { return flightSuretyData.getAirlines(); } /*** @dev Register a future flight for insuring.**/ function registerFlight(address _airline, string calldata _flight, uint256 _timestamp) external payable { bytes32 flightKey = getFlightKey(_airline, _flight, _timestamp); flights[flightKey] = Flight ({ airline: _airline, isRegistered: true, flightKey: flightKey, flightNumber: _flight, statusCode: STATUS_CODE_UNKNOWN, timestamp: _timestamp }); regIndexFlight.push(flightKey); emit registeredFlight(_airline, true, flightKey, _flight, STATUS_CODE_UNKNOWN, _timestamp); } /*** @dev Get All Flights**/ function getFlights() external view returns (bytes32[] memory ) { bytes32[] memory arrFlights = new bytes32[](regIndexFlight.length); for (uint i = 0; i < regIndexFlight.length; i++){ arrFlights[i] = flights[regIndexFlight[i]].flightKey; } return (arrFlights); } /*** @dev Get Flight data**/ function getFlightData(bytes32 flightKey) external view requireIsOperational returns(address, bool, bytes32, string memory, uint8, uint256) { return ( flights[flightKey].airline, flights[flightKey].isRegistered, flights[flightKey].flightKey, flights[flightKey].flightNumber, flights[flightKey].statusCode, flights[flightKey].timestamp ); } /*** @dev Called after oracle has updated flight status**/ function processFlightStatus(bytes32 flightKey, uint8 statusCode) internal { flights[flightKey].statusCode = statusCode; } // Generate a request for oracles to fetch flight information function fetchFlightStatus(bytes32 _flightKey) external requireIsOperational { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, flights[_flightKey].airline, flights[_flightKey].flightNumber, flights[_flightKey].timestamp)); oracleResponses[key] = ResponseInfo({requester: msg.sender, isOpen: true}); emit OracleRequest(index, flights[_flightKey].airline, flights[_flightKey].flightNumber, flights[_flightKey].timestamp); } function buyInsurance (bytes32 _flight) external payable requireIsOperational { address payable payableAccount = address(uint160(address(flightSuretyData))); payableAccount.transfer(msg.value); uint payout = msg.value + msg.value.div(2); flightSuretyData.buyInsurance(msg.sender, _flight, msg.value, payout); } function payout () external payable requireIsOperational { bytes32 flight = flightSuretyData.getPassengerFlight(msg.sender); require(flights[flight].statusCode == 20, 'You cannot withdraw the funds for a justified cause'); flightSuretyData.payout(msg.sender); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status, bytes32 flightKye); event OracleReport(address airline, string flight, uint256 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp); // Register an oracle with the contract function registerOracle ( ) external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); address payable dataContract = address(uint160(address(flightSuretyData))); dataContract.transfer(msg.value); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); } function getMyIndexes ( ) view external returns(uint8[3] memory) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, address airline, string calldata flight, uint256 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { bytes32 flightKey = getFlightKey(airline, flight, timestamp); emit FlightStatusInfo(airline, flight, timestamp, statusCode, flightKey); // Handle flight status as appropriate processFlightStatus(flightKey, statusCode); } } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes ( address account ) internal returns(uint8[3] memory) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion }
Add an airline to the registration queue/
function registerAirline(address _airline) external requireIsOperational requireAirlineIsFunded requireIsSubmittedAirline(_airline) returns(address, address) { if (flightSuretyData.numAirlinesFunded() < MINIMUM_AIRLINES_TO_VOTE) { require(flightSuretyData.getFirstAirline() == msg.sender, "You are not the first airline"); } if (flightSuretyData.numAirlinesFunded() >= MINIMUM_AIRLINES_TO_VOTE) { uint airlinesFunded = flightSuretyData.numAirlinesFunded(); uint8 votes = flightSuretyData.getVotesAirline(_airline); require(airlinesFunded.div(2) <= votes, "Has not passed the consensus"); } flightSuretyData.registerAirline(_airline); return (_airline, msg.sender); }
15,866,084
//Address: 0xe495bcacaf29a0eb00fb67b86e9cd2a994dd55d8 //Contract name: EtherToken //Balance: 0 Ether //Verification Date: 12/13/2017 //Transacion Count: 13 // CODE STARTS HERE /* Copyright 2017 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.4.18; contract Token { /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint _value) public returns (bool) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint _value) public returns (bool) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint _value) public returns (bool) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint) {} event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } contract ERC20Token is Token { function transfer(address _to, uint _value) public returns (bool) { require(balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) public returns (bool) { require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value >= balances[_to]); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function balanceOf(address _owner) public view returns (uint) { return balances[_owner]; } function allowance(address _owner, address _spender) public view returns (uint) { return allowed[_owner][_spender]; } mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; uint public totalSupply; } contract UnlimitedAllowanceToken is ERC20Token { uint constant MAX_UINT = 2**256 - 1; /// @dev ERC20 transferFrom, modified such that an allowance of MAX_UINT represents an unlimited allowance. See https://github.com/ethereum/EIPs/issues/717 /// @param _from Address to transfer from. /// @param _to Address to transfer to. /// @param _value Amount to transfer. /// @return Success of transfer. function transferFrom(address _from, address _to, uint _value) public returns (bool) { uint allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value && balances[_to] + _value >= balances[_to]); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT) { allowed[_from][msg.sender] -= _value; } Transfer(_from, _to, _value); return true; } } contract SafeMath { function safeMul(uint a, uint b) internal pure returns (uint256) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal pure returns (uint256) { uint c = a / b; return c; } function safeSub(uint a, uint b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint256) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint256) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint256) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract EtherToken is UnlimitedAllowanceToken, SafeMath { string constant public name = "Ether Token"; string constant public symbol = "WETH"; string constant public version = "2.0.0"; // version 1.0.0 deployed on mainnet at 0x2956356cd2a2bf3202f771f50d3d14a367b48070 uint8 constant public decimals = 18; /// @dev Fallback to calling deposit when ether is sent directly to contract. function() public payable { deposit(); } /// @dev Buys tokens with Ether, exchanging them 1:1. function deposit() public payable { balances[msg.sender] = safeAdd(balances[msg.sender], msg.value); totalSupply = safeAdd(totalSupply, msg.value); Transfer(address(0), msg.sender, msg.value); } /// @dev Sells tokens in exchange for Ether, exchanging them 1:1. /// @param _value Number of tokens to sell. function withdraw(uint _value) public { balances[msg.sender] = safeSub(balances[msg.sender], _value); totalSupply = safeSub(totalSupply, _value); require(msg.sender.send(_value)); Transfer(msg.sender, address(0), _value); } }
send `_value` token to `_to` from `msg.sender` _to The address of the recipient _value The amount of token to be transferred return Whether the transfer was successful or not
function transfer(address _to, uint _value) public returns (bool) {}
1,823,067
/** *Submitted for verification at Etherscan.io on 2021-02-07 */ // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } /** * @dev Implementation of an {ERC20} token that is pausable, burnable * and has an owner to mint, revoke and pause. */ contract gHOPtoken is ERC20("HOPR Genesis DAO Token", "gHOP"), ERC20Pausable, ERC20Burnable, Ownable { /** * @dev Initializes the contract in paused state. */ constructor() { _pause(); } // since this contract inherits _beforeTokenTransfer both from ERC20Pausable and also from ERC20 via ERC20Burnable // the compiler needs to know which parent function to call function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20, ERC20Pausable) { if (_msgSender() != owner()) { // pause does not apply to owner super._beforeTokenTransfer(from, to, amount); } } /** * @dev Allows the owner to mint tokens for one recipient. * @param account the beneficiary getting tokens * @param amount the amount of tokens that the beneficiary gets */ function mint(address account, uint256 amount) external onlyOwner { _mint(account, amount); } /** * @dev Allows the owner to mint tokens for several recipients in one transaction. * @param accounts an array of beneficiaries getting tokens * @param amount the amount of tokens that each beneficiary gets */ function batchMint(address[] calldata accounts, uint256 amount) external onlyOwner { uint256 len = accounts.length; for (uint256 c = 0; c < len; c++) { _mint(accounts[c], amount); } } /** * @dev Allows the owner to revoke tokens from one recipient. * @param account from which to revoke the tokens * @param amount the amount of tokens to be revoked from account */ function revoke(address account, uint256 amount) external onlyOwner { _burn(account, amount); } /** * @dev Allows the owner to revoke tokens from several accounts in one trasnaction. * @param accounts array of accounts from which to revoke the tokens * @param amount the amount of tokens to be revoked from each account */ function batchRevoke(address[] calldata accounts, uint256 amount) external onlyOwner { uint256 len = accounts.length; for (uint256 c = 0; c < len; c++) { _burn(accounts[c], amount); } } /** * @dev Allows the owner to pause all interactions with the smart contract, except for owner. */ function pause() external onlyOwner { _pause(); } /** * @dev Allows the owner to unpause all interactions with the smart contract. */ function unpause() external onlyOwner { _unpause(); } }
Allows the owner to pause all interactions with the smart contract, except for owner./
function pause() external onlyOwner { _pause(); }
2,075,205
./full_match/11111/0x1f41dBA8Ac45eB8226410A38f519667eeE5BBD08/sources/contracts/WelcomeNFTv1.sol
ERC721._safeTransfer(from, to, tokenId, data);
function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public override { require(false , "UptnWelcomeNFTv1: Transfer is prohibited by internal policy."); }
16,361,843
//Address: 0xd73be539d6b2076bab83ca6ba62dfe189abc6bbe //Contract name: BlockchainCutiesCore //Balance: 20.223731891324013681 Ether //Verification Date: 4/25/2018 //Transacion Count: 8014 // CODE STARTS HERE pragma solidity ^0.4.20; /// BlockchainCuties: Collectible and breedable cuties on the Ethereum blockchain. /// https://blockchaincuties.co/ /// @title defined the interface that will be referenced in main Cutie contract contract GeneMixerInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isGeneMixer() external pure returns (bool); /// @dev given genes of cutie 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of dad /// @return the genes that are supposed to be passed down the child function mixGenes(uint256 genes1, uint256 genes2) public view returns (uint256); function canBreed(uint40 momId, uint256 genes1, uint40 dadId, uint256 genes2) public view returns (bool); } /// @author https://BlockChainArchitect.iocontract Bank is CutiePluginBase contract PluginInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isPluginInterface() public pure returns (bool); function onRemove() public; /// @dev Begins new feature. /// @param _cutieId - ID of token to auction, sender must be owner. /// @param _parameter - arbitrary parameter /// @param _seller - Old owner, if not the message sender function run( uint40 _cutieId, uint256 _parameter, address _seller ) public payable; /// @dev Begins new feature, approved and signed by COO. /// @param _cutieId - ID of token to auction, sender must be owner. /// @param _parameter - arbitrary parameter function runSigned( uint40 _cutieId, uint256 _parameter, address _owner ) external payable; function withdraw() public; } /// @title Auction Market for Blockchain Cuties. /// @author https://BlockChainArchitect.io contract MarketInterface { function withdrawEthFromBalance() external; function createAuction(uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller) public payable; function bid(uint40 _cutieId) public payable; function cancelActiveAuctionWhenPaused(uint40 _cutieId) public; function getAuctionInfo(uint40 _cutieId) public view returns ( address seller, uint128 startPrice, uint128 endPrice, uint40 duration, uint40 startedAt, uint128 featuringFee ); } /// @title BlockchainCuties: Collectible and breedable cuties on the Ethereum blockchain. /// @author https://BlockChainArchitect.io /// @dev This is the BlockchainCuties configuration. It can be changed redeploying another version. contract ConfigInterface { function isConfig() public pure returns (bool); function getCooldownIndexFromGeneration(uint16 _generation) public view returns (uint16); function getCooldownEndTimeFromIndex(uint16 _cooldownIndex) public view returns (uint40); function getCooldownIndexCount() public view returns (uint256); function getBabyGen(uint16 _momGen, uint16 _dadGen) public pure returns (uint16); function getTutorialBabyGen(uint16 _dadGen) public pure returns (uint16); function getBreedingFee(uint40 _momId, uint40 _dadId) public pure returns (uint256); } /// @dev Note: the ERC-165 identifier for this interface is 0xf0b9e5ba interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. This function MUST use 50,000 gas or less. Return of other /// than the magic value MUST result in the transaction being reverted. /// Note: the contract address is always the message sender. /// @param _from The sending address /// @param _tokenId The NFT identifier which is being transfered /// @param data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4); } /// @title BlockchainCuties: Collectible and breedable cuties on the Ethereum blockchain. /// @author https://BlockChainArchitect.io /// @dev This is the main BlockchainCuties contract. For separated logical sections the code is divided in // several separately-instantiated sibling contracts that handle auctions and the genetic combination algorithm. // By keeping auctions separate it is possible to upgrade them without disrupting the main contract that tracks // the ownership of the cutie. The genetic combination algorithm is kept separate so that all of the rest of the // code can be open-sourced. // The contracts: // // - BlockchainCuties: The fundamental code, including main data storage, constants and data types, as well as // internal functions for managing these items ans ERC-721 implementation. // Various addresses and constraints for operations can be executed only by specific roles - // Owner, Operator and Parties. // Methods for interacting with additional features (Plugins). // The methods for breeding and keeping track of breeding offers, relies on external genetic combination // contract. // Public methods for auctioning or bidding or breeding. // // - SaleMarket and BreedingMarket: The actual auction functionality is handled in two sibling contracts - one // for sales and one for breeding. Auction creation and bidding is mostly mediated through this side of // the core contract. // // - Effects: Contracts allow to use item effects on cuties, implemented as plugins. Items are not stored in // blockchain to not overload Ethereum network. Operator generates signatures, and Plugins check it // and perform effect. // // - ItemMarket: Plugin contract used to transfer money from buyer to seller. // // - Bank: Plugin contract used to receive payments for payed features. contract BlockchainCutiesCore /*is ERC721, CutieCoreInterface*/ { /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string _name) { return "BlockchainCuties"; } /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string _symbol) { return "BC"; } /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external pure returns (bool) { return interfaceID == 0x6466353c || interfaceID == bytes4(keccak256('supportsInterface(bytes4)')); } event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @dev The Birth event is fired as soon as a new cutie is created. This /// is any time a cutie comes into existence through the giveBirth method, as well as /// when a new gen0 cutie is created. event Birth(address indexed owner, uint40 cutieId, uint40 momId, uint40 dadId, uint256 genes); /// @dev This struct represents a blockchain Cutie. It was ensured that struct fits well into /// exactly two 256-bit words. The order of the members in this structure /// matters because of the Ethereum byte-packing rules. /// Reference: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Cutie { // The Cutie's genetic code is in these 256-bits. Cutie's genes never change. uint256 genes; // The timestamp from the block when this cutie was created. uint40 birthTime; // The minimum timestamp after which the cutie can start breeding // again. uint40 cooldownEndTime; // The cutie's parents ID is set to 0 for gen0 cuties. // Because of using 32-bit unsigned integers the limit is 4 billion cuties. // Current Ethereum annual limit is about 500 million transactions. uint40 momId; uint40 dadId; // Set the index in the cooldown array (see below) that means // the current cooldown duration for this Cutie. Starts at 0 // for gen0 cats, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding, regardless // of being cutie mom or cutie dad. uint16 cooldownIndex; // The "generation number" of the cutie. Cutioes minted by the contract // for sale are called "gen0" with generation number of 0. All other cuties' // generation number is the larger of their parents' two generation // numbers, plus one (i.e. max(mom.generation, dad.generation) + 1) uint16 generation; // Some optional data used by external contracts // Cutie struct is 2x256 bits long. uint64 optional; } /// @dev An array containing the Cutie struct for all Cuties in existence. The ID /// of each cutie is actually an index into this array. ID 0 is the parent /// of all generation 0 cats, and both parents to itself. It is an invalid genetic code. Cutie[] public cuties; /// @dev A mapping from cutie IDs to the address that owns them. All cuties have /// some valid owner address, even gen0 cuties are created with a non-zero owner. mapping (uint40 => address) public cutieIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from CutieIDs to an address that has been approved to call /// transferFrom(). A Cutie can have one approved address for transfer /// at any time. A zero value means that there is no outstanding approval. mapping (uint40 => address) public cutieIndexToApproved; /// @dev A mapping from CutieIDs to an address that has been approved to use /// this Cutie for breeding via breedWith(). A Cutie can have one approved /// address for breeding at any time. A zero value means that there is no outstanding approval. mapping (uint40 => address) public sireAllowedToAddress; /// @dev The address of the Market contract used to sell cuties. This /// contract used both peer-to-peer sales and the gen0 sales that are /// initiated each 15 minutes. MarketInterface public saleMarket; /// @dev The address of a custom Market subclassed contract used for breeding /// auctions. Is to be separated from saleMarket as the actions taken on success /// after a sales and breeding auction are quite different. MarketInterface public breedingMarket; // Modifiers to check that inputs can be safely stored with a certain // number of bits. modifier canBeStoredIn40Bits(uint256 _value) { require(_value <= 0xFFFFFFFFFF); _; } /// @notice Returns the total number of Cuties in existence. /// @dev Required for ERC-721 compliance. function totalSupply() external view returns (uint256) { return cuties.length - 1; } /// @notice Returns the total number of Cuties in existence. /// @dev Required for ERC-721 compliance. function _totalSupply() internal view returns (uint256) { return cuties.length - 1; } // Internal utility functions assume that their input arguments // are valid. Public methods sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a certain Cutie. /// @param _claimant the address we are validating against. /// @param _cutieId cutie id, only valid when > 0 function _isOwner(address _claimant, uint40 _cutieId) internal view returns (bool) { return cutieIndexToOwner[_cutieId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a certain Cutie. /// @param _claimant the address we are confirming the cutie is approved for. /// @param _cutieId cutie id, only valid when > 0 function _approvedFor(address _claimant, uint40 _cutieId) internal view returns (bool) { return cutieIndexToApproved[_cutieId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is done on purpose: /// _approve() and transferFrom() are used together for putting Cuties on auction. /// There is no value in spamming the log with Approval events in that case. function _approve(uint40 _cutieId, address _approved) internal { cutieIndexToApproved[_cutieId] = _approved; } /// @notice Returns the number of Cuties owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) external view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Cutie to another address. When transferring to a smart /// contract, ensure that it is aware of ERC-721 (or /// BlockchainCuties specifically), otherwise the Cutie may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _cutieId The ID of the Cutie to transfer. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _cutieId) external whenNotPaused canBeStoredIn40Bits(_cutieId) { // You can only send your own cutie. require(_isOwner(msg.sender, uint40(_cutieId))); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, uint40(_cutieId)); } /// @notice Grant another address the right to transfer a perticular Cutie via transferFrom(). /// This flow is preferred for transferring NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to clear all approvals. /// @param _cutieId The ID of the Cutie that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _cutieId) external whenNotPaused canBeStoredIn40Bits(_cutieId) { // Only cutie's owner can grant transfer approval. require(_isOwner(msg.sender, uint40(_cutieId))); // Registering approval replaces any previous approval. _approve(uint40(_cutieId), _to); // Emit approval event. emit Approval(msg.sender, _to, _cutieId); } /// @notice Transfers the ownership of an NFT from one address to another address. /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external whenNotPaused canBeStoredIn40Bits(_tokenId) { require(_to != address(0)); require(_to != address(this)); require(_to != address(saleMarket)); require(_to != address(breedingMarket)); // Check for approval and valid ownership require(_approvedFor(msg.sender, uint40(_tokenId)) || _isApprovedForAll(_from, msg.sender)); require(_isOwner(_from, uint40(_tokenId))); // Reassign ownership, clearing pending approvals and emitting Transfer event. _transfer(_from, _to, uint40(_tokenId)); ERC721TokenReceiver (_to).onERC721Received(_from, _tokenId, data); } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "" /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused canBeStoredIn40Bits(_tokenId) { require(_to != address(0)); require(_to != address(this)); require(_to != address(saleMarket)); require(_to != address(breedingMarket)); // Check for approval and valid ownership require(_approvedFor(msg.sender, uint40(_tokenId)) || _isApprovedForAll(_from, msg.sender)); require(_isOwner(_from, uint40(_tokenId))); // Reassign ownership, clearing pending approvals and emitting Transfer event. _transfer(_from, _to, uint40(_tokenId)); } /// @notice Transfer a Cutie owned by another address, for which the calling address /// has been granted transfer approval by the owner. /// @param _from The address that owns the Cutie to be transfered. /// @param _to Any address, including the caller address, can take ownership of the Cutie. /// @param _tokenId The ID of the Cutie to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused canBeStoredIn40Bits(_tokenId) { // Check for approval and valid ownership require(_approvedFor(msg.sender, uint40(_tokenId)) || _isApprovedForAll(_from, msg.sender)); require(_isOwner(_from, uint40(_tokenId))); // Reassign ownership, clearing pending approvals and emitting Transfer event. _transfer(_from, _to, uint40(_tokenId)); } /// @notice Returns the address currently assigned ownership of a given Cutie. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _cutieId) external view canBeStoredIn40Bits(_cutieId) returns (address owner) { owner = cutieIndexToOwner[uint40(_cutieId)]; require(owner != address(0)); } /// @notice Returns the nth Cutie assigned to an address, with n specified by the /// _index argument. /// @param _owner The owner of the Cuties we are interested in. /// @param _index The zero-based index of the cutie within the owner's list of cuties. /// Must be less than balanceOf(_owner). /// @dev This method must not be called by smart contract code. It will almost /// certainly blow past the block gas limit once there are a large number of /// Cuties in existence. Exists only to allow off-chain queries of ownership. /// Optional method for ERC-721. function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 cutieId) { uint40 count = 0; for (uint40 i = 1; i <= _totalSupply(); ++i) { if (cutieIndexToOwner[i] == _owner) { if (count == _index) { return i; } else { count++; } } } revert(); } /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external pure returns (uint256) { return _index; } /// @dev A mapping from Cuties owner (account) to an address that has been approved to call /// transferFrom() for all cuties, owned by owner. /// Only one approved address is permitted for each account for transfer /// at any time. A zero value means there is no outstanding approval. mapping (address => address) public addressToApprovedAll; /// @notice Enable or disable approval for a third party ("operator") to manage /// all your asset. /// @dev Emits the ApprovalForAll event /// @param _operator Address to add to the set of authorized operators. /// @param _approved True if the operators is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external { if (_approved) { addressToApprovedAll[msg.sender] = _operator; } else { delete addressToApprovedAll[msg.sender]; } emit ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view canBeStoredIn40Bits(_tokenId) returns (address) { require(_tokenId <= _totalSupply()); if (cutieIndexToApproved[uint40(_tokenId)] != address(0)) { return cutieIndexToApproved[uint40(_tokenId)]; } address owner = cutieIndexToOwner[uint40(_tokenId)]; return addressToApprovedAll[owner]; } /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return addressToApprovedAll[_owner] == _operator; } function _isApprovedForAll(address _owner, address _operator) internal view returns (bool) { return addressToApprovedAll[_owner] == _operator; } ConfigInterface public config; /// @dev Update the address of the config contract. /// @param _address An address of a ConfigInterface contract instance to be used from this point forward. function setConfigAddress(address _address) public onlyOwner { ConfigInterface candidateContract = ConfigInterface(_address); require(candidateContract.isConfig()); // Set the new contract address config = candidateContract; } function getCooldownIndexFromGeneration(uint16 _generation) internal view returns (uint16) { return config.getCooldownIndexFromGeneration(_generation); } /// @dev An internal method that creates a new cutie and stores it. This /// method does not check anything and should only be called when the /// input data is valid for sure. Will generate both a Birth event /// and a Transfer event. /// @param _momId The cutie ID of the mom of this cutie (zero for gen0) /// @param _dadId The cutie ID of the dad of this cutie (zero for gen0) /// @param _generation The generation number of this cutie, must be computed by caller. /// @param _genes The cutie's genetic code. /// @param _owner The initial owner of this cutie, must be non-zero (except for the unCutie, ID 0) function _createCutie( uint40 _momId, uint40 _dadId, uint16 _generation, uint16 _cooldownIndex, uint256 _genes, address _owner, uint40 _birthTime ) internal returns (uint40) { Cutie memory _cutie = Cutie({ genes: _genes, birthTime: _birthTime, cooldownEndTime: 0, momId: _momId, dadId: _dadId, cooldownIndex: _cooldownIndex, generation: _generation, optional: 0 }); uint256 newCutieId256 = cuties.push(_cutie) - 1; // Check if id can fit into 40 bits require(newCutieId256 <= 0xFFFFFFFFFF); uint40 newCutieId = uint40(newCutieId256); // emit the birth event emit Birth(_owner, newCutieId, _cutie.momId, _cutie.dadId, _cutie.genes); // This will assign ownership, as well as emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newCutieId); return newCutieId; } /// @notice Returns all the relevant information about a certain cutie. /// @param _id The ID of the cutie of interest. function getCutie(uint40 _id) external view returns ( uint256 genes, uint40 birthTime, uint40 cooldownEndTime, uint40 momId, uint40 dadId, uint16 cooldownIndex, uint16 generation ) { Cutie storage cutie = cuties[_id]; genes = cutie.genes; birthTime = cutie.birthTime; cooldownEndTime = cutie.cooldownEndTime; momId = cutie.momId; dadId = cutie.dadId; cooldownIndex = cutie.cooldownIndex; generation = cutie.generation; } /// @dev Assigns ownership of a particular Cutie to an address. function _transfer(address _from, address _to, uint40 _cutieId) internal { // since the number of cuties is capped to 2^40 // there is no way to overflow this ownershipTokenCount[_to]++; // transfer ownership cutieIndexToOwner[_cutieId] = _to; // When creating new cuties _from is 0x0, but we cannot account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // once the cutie is transferred also clear breeding allowances delete sireAllowedToAddress[_cutieId]; // clear any previously approved ownership exchange delete cutieIndexToApproved[_cutieId]; } // Emit the transfer event. emit Transfer(_from, _to, _cutieId); } /// @dev For transferring a cutie owned by this contract to the specified address. /// Used to rescue lost cuties. (There is no "proper" flow where this contract /// should be the owner of any Cutie. This function exists for us to reassign /// the ownership of Cuties that users may have accidentally sent to our address.) /// @param _cutieId - ID of cutie /// @param _recipient - Address to send the cutie to function restoreCutieToAddress(uint40 _cutieId, address _recipient) public onlyOperator whenNotPaused { require(_isOwner(this, _cutieId)); _transfer(this, _recipient, _cutieId); } address ownerAddress; address operatorAddress; bool public paused = false; modifier onlyOwner() { require(msg.sender == ownerAddress); _; } function setOwner(address _newOwner) public onlyOwner { require(_newOwner != address(0)); ownerAddress = _newOwner; } modifier onlyOperator() { require(msg.sender == operatorAddress || msg.sender == ownerAddress); _; } function setOperator(address _newOperator) public onlyOwner { require(_newOperator != address(0)); operatorAddress = _newOperator; } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() public onlyOwner whenNotPaused { paused = true; } string public metadataUrlPrefix = "https://blockchaincuties.co/cutie/"; string public metadataUrlSuffix = ".svg"; /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string infoUrl) { return concat(toSlice(metadataUrlPrefix), toSlice(concat(toSlice(uintToString(_tokenId)), toSlice(metadataUrlSuffix)))); } function setMetadataUrl(string _metadataUrlPrefix, string _metadataUrlSuffix) public onlyOwner { metadataUrlPrefix = _metadataUrlPrefix; metadataUrlSuffix = _metadataUrlSuffix; } mapping(address => PluginInterface) public plugins; PluginInterface[] public pluginsArray; mapping(uint40 => address) public usedSignes; uint40 public minSignId; event GenesChanged(uint40 indexed cutieId, uint256 oldValue, uint256 newValue); event CooldownEndTimeChanged(uint40 indexed cutieId, uint40 oldValue, uint40 newValue); event CooldownIndexChanged(uint40 indexed cutieId, uint16 ololdValue, uint16 newValue); event GenerationChanged(uint40 indexed cutieId, uint16 oldValue, uint16 newValue); event OptionalChanged(uint40 indexed cutieId, uint64 oldValue, uint64 newValue); event SignUsed(uint40 signId, address sender); event MinSignSet(uint40 signId); /// @dev Sets the reference to the plugin contract. /// @param _address - Address of plugin contract. function addPlugin(address _address) public onlyOwner { PluginInterface candidateContract = PluginInterface(_address); // verify that a contract is what we expect require(candidateContract.isPluginInterface()); // Set the new contract address plugins[_address] = candidateContract; pluginsArray.push(candidateContract); } /// @dev Remove plugin and calls onRemove to cleanup function removePlugin(address _address) public onlyOwner { plugins[_address].onRemove(); delete plugins[_address]; uint256 kindex = 0; while (kindex < pluginsArray.length) { if (address(pluginsArray[kindex]) == _address) { pluginsArray[kindex] = pluginsArray[pluginsArray.length-1]; pluginsArray.length--; } else { kindex++; } } } /// @dev Put a cutie up for plugin feature. function runPlugin( address _pluginAddress, uint40 _cutieId, uint256 _parameter ) public whenNotPaused payable { // If cutie is already on any auction or in adventure, this will throw // because it will be owned by the other contract. // If _cutieId is 0, then cutie is not used on this feature. require(_cutieId == 0 || _isOwner(msg.sender, _cutieId)); require(address(plugins[_pluginAddress]) != address(0)); if (_cutieId > 0) { _approve(_cutieId, _pluginAddress); } // Plugin contract throws if inputs are invalid and clears // transfer after escrowing the cutie. plugins[_pluginAddress].run.value(msg.value)( _cutieId, _parameter, msg.sender ); } /// @dev Called from plugin contract when using items as effect function getGenes(uint40 _id) public view returns ( uint256 genes ) { Cutie storage cutie = cuties[_id]; genes = cutie.genes; } /// @dev Called from plugin contract when using items as effect function changeGenes( uint40 _cutieId, uint256 _genes) public whenNotPaused { // if caller is registered plugin contract require(address(plugins[msg.sender]) != address(0)); Cutie storage cutie = cuties[_cutieId]; if (cutie.genes != _genes) { emit GenesChanged(_cutieId, cutie.genes, _genes); cutie.genes = _genes; } } function getCooldownEndTime(uint40 _id) public view returns ( uint40 cooldownEndTime ) { Cutie storage cutie = cuties[_id]; cooldownEndTime = cutie.cooldownEndTime; } function changeCooldownEndTime( uint40 _cutieId, uint40 _cooldownEndTime) public whenNotPaused { require(address(plugins[msg.sender]) != address(0)); Cutie storage cutie = cuties[_cutieId]; if (cutie.cooldownEndTime != _cooldownEndTime) { emit CooldownEndTimeChanged(_cutieId, cutie.cooldownEndTime, _cooldownEndTime); cutie.cooldownEndTime = _cooldownEndTime; } } function getCooldownIndex(uint40 _id) public view returns ( uint16 cooldownIndex ) { Cutie storage cutie = cuties[_id]; cooldownIndex = cutie.cooldownIndex; } function changeCooldownIndex( uint40 _cutieId, uint16 _cooldownIndex) public whenNotPaused { require(address(plugins[msg.sender]) != address(0)); Cutie storage cutie = cuties[_cutieId]; if (cutie.cooldownIndex != _cooldownIndex) { emit CooldownIndexChanged(_cutieId, cutie.cooldownIndex, _cooldownIndex); cutie.cooldownIndex = _cooldownIndex; } } function changeGeneration( uint40 _cutieId, uint16 _generation) public whenNotPaused { require(address(plugins[msg.sender]) != address(0)); Cutie storage cutie = cuties[_cutieId]; if (cutie.generation != _generation) { emit GenerationChanged(_cutieId, cutie.generation, _generation); cutie.generation = _generation; } } function getGeneration(uint40 _id) public view returns (uint16 generation) { Cutie storage cutie = cuties[_id]; generation = cutie.generation; } function changeOptional( uint40 _cutieId, uint64 _optional) public whenNotPaused { require(address(plugins[msg.sender]) != address(0)); Cutie storage cutie = cuties[_cutieId]; if (cutie.optional != _optional) { emit OptionalChanged(_cutieId, cutie.optional, _optional); cutie.optional = _optional; } } function getOptional(uint40 _id) public view returns (uint64 optional) { Cutie storage cutie = cuties[_id]; optional = cutie.optional; } /// @dev Common function to be used also in backend function hashArguments( address _pluginAddress, uint40 _signId, uint40 _cutieId, uint128 _value, uint256 _parameter) public pure returns (bytes32 msgHash) { msgHash = keccak256(_pluginAddress, _signId, _cutieId, _value, _parameter); } /// @dev Common function to be used also in backend function getSigner( address _pluginAddress, uint40 _signId, uint40 _cutieId, uint128 _value, uint256 _parameter, uint8 _v, bytes32 _r, bytes32 _s ) public pure returns (address) { bytes32 msgHash = hashArguments(_pluginAddress, _signId, _cutieId, _value, _parameter); return ecrecover(msgHash, _v, _r, _s); } /// @dev Common function to be used also in backend function isValidSignature( address _pluginAddress, uint40 _signId, uint40 _cutieId, uint128 _value, uint256 _parameter, uint8 _v, bytes32 _r, bytes32 _s ) public view returns (bool) { return getSigner(_pluginAddress, _signId, _cutieId, _value, _parameter, _v, _r, _s) == operatorAddress; } /// @dev Put a cutie up for plugin feature with signature. /// Can be used for items equip, item sales and other features. /// Signatures are generated by Operator role. function runPluginSigned( address _pluginAddress, uint40 _signId, uint40 _cutieId, uint128 _value, uint256 _parameter, uint8 _v, bytes32 _r, bytes32 _s ) public whenNotPaused payable { // If cutie is already on any auction or in adventure, this will throw // as it will be owned by the other contract. // If _cutieId is 0, then cutie is not used on this feature. require(_cutieId == 0 || _isOwner(msg.sender, _cutieId)); require(address(plugins[_pluginAddress]) != address(0)); require (usedSignes[_signId] == address(0)); require (_signId >= minSignId); // value can also be zero for free calls require (_value <= msg.value); require (isValidSignature(_pluginAddress, _signId, _cutieId, _value, _parameter, _v, _r, _s)); usedSignes[_signId] = msg.sender; emit SignUsed(_signId, msg.sender); // Plugin contract throws if inputs are invalid and clears // transfer after escrowing the cutie. plugins[_pluginAddress].runSigned.value(_value)( _cutieId, _parameter, msg.sender ); } /// @dev Sets minimal signId, than can be used. /// All unused signatures less than signId will be cancelled on off-chain server /// and unused items will be transfered back to owner. function setMinSign(uint40 _newMinSignId) public onlyOperator { require (_newMinSignId > minSignId); minSignId = _newMinSignId; emit MinSignSet(minSignId); } event BreedingApproval(address indexed _owner, address indexed _approved, uint256 _tokenId); // Set in case the core contract is broken and an upgrade is required address public upgradedContractAddress; function isCutieCore() pure public returns (bool) { return true; } /// @notice Creates the main BlockchainCuties smart contract instance. function BlockchainCutiesCore() public { // Starts paused. paused = true; // the creator of the contract is the initial owner ownerAddress = msg.sender; // the creator of the contract is also the initial operator operatorAddress = msg.sender; // start with the mythical cutie 0 - so there are no generation-0 parent issues _createCutie(0, 0, 0, 0, uint256(-1), address(0), 0); } event ContractUpgrade(address newContract); /// @dev Aimed to mark the smart contract as upgraded if there is a crucial /// bug. This keeps track of the new contract and indicates that the new address is set. /// Updating to the new contract address is up to the clients. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _newAddress new address function setUpgradedAddress(address _newAddress) public onlyOwner whenPaused { require(_newAddress != address(0)); upgradedContractAddress = _newAddress; emit ContractUpgrade(upgradedContractAddress); } /// @dev Import cuties from previous version of Core contract. /// @param _oldAddress Old core contract address /// @param _fromIndex (inclusive) /// @param _toIndex (inclusive) function migrate(address _oldAddress, uint40 _fromIndex, uint40 _toIndex) public onlyOwner whenPaused { require(_totalSupply() + 1 == _fromIndex); BlockchainCutiesCore old = BlockchainCutiesCore(_oldAddress); for (uint40 i = _fromIndex; i <= _toIndex; i++) { uint256 genes; uint40 birthTime; uint40 cooldownEndTime; uint40 momId; uint40 dadId; uint16 cooldownIndex; uint16 generation; (genes, birthTime, cooldownEndTime, momId, dadId, cooldownIndex, generation) = old.getCutie(i); Cutie memory _cutie = Cutie({ genes: genes, birthTime: birthTime, cooldownEndTime: cooldownEndTime, momId: momId, dadId: dadId, cooldownIndex: cooldownIndex, generation: generation, optional: 0 }); cuties.push(_cutie); } } /// @dev Import cuties from previous version of Core contract (part 2). /// @param _oldAddress Old core contract address /// @param _fromIndex (inclusive) /// @param _toIndex (inclusive) function migrate2(address _oldAddress, uint40 _fromIndex, uint40 _toIndex, address saleAddress, address breedingAddress) public onlyOwner whenPaused { BlockchainCutiesCore old = BlockchainCutiesCore(_oldAddress); MarketInterface oldSaleMarket = MarketInterface(saleAddress); MarketInterface oldBreedingMarket = MarketInterface(breedingAddress); for (uint40 i = _fromIndex; i <= _toIndex; i++) { address owner = old.ownerOf(i); if (owner == saleAddress) { (owner,,,,,) = oldSaleMarket.getAuctionInfo(i); } if (owner == breedingAddress) { (owner,,,,,) = oldBreedingMarket.getAuctionInfo(i); } _transfer(0, owner, i); } } /// @dev Override unpause so it requires upgradedContractAddress not set, because then the contract was upgraded. function unpause() public onlyOwner whenPaused { require(upgradedContractAddress == address(0)); paused = false; } // Counts the number of cuties the contract owner has created. uint40 public promoCutieCreatedCount; uint40 public gen0CutieCreatedCount; uint40 public gen0Limit = 50000; uint40 public promoLimit = 5000; /// @dev Creates a new gen0 cutie with the given genes and /// creates an auction for it. function createGen0Auction(uint256 _genes, uint128 startPrice, uint128 endPrice, uint40 duration) public onlyOperator { require(gen0CutieCreatedCount < gen0Limit); uint40 cutieId = _createCutie(0, 0, 0, 0, _genes, address(this), uint40(now)); _approve(cutieId, saleMarket); saleMarket.createAuction( cutieId, startPrice, endPrice, duration, address(this) ); gen0CutieCreatedCount++; } function createPromoCutie(uint256 _genes, address _owner) public onlyOperator { require(promoCutieCreatedCount < promoLimit); if (_owner == address(0)) { _owner = operatorAddress; } promoCutieCreatedCount++; gen0CutieCreatedCount++; _createCutie(0, 0, 0, 0, _genes, _owner, uint40(now)); } /// @dev Put a cutie up for auction to be dad. /// Performs checks to ensure the cutie can be dad, then /// delegates to reverse auction. /// Optional money amount can be sent to contract to feature auction. /// Pricea are available on web. function createBreedingAuction( uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration ) public whenNotPaused payable { // Auction contract checks input sizes // If cutie is already on any auction, this will throw // because it will be owned by the auction contract. require(_isOwner(msg.sender, _cutieId)); require(canBreed(_cutieId)); _approve(_cutieId, breedingMarket); // breeding auction function is called if inputs are invalid and clears // transfer and sire approval after escrowing the cutie. breedingMarket.createAuction.value(msg.value)( _cutieId, _startPrice, _endPrice, _duration, msg.sender ); } /// @dev Sets the reference to the breeding auction. /// @param _breedingAddress - Address of breeding market contract. /// @param _saleAddress - Address of sale market contract. function setMarketAddress(address _breedingAddress, address _saleAddress) public onlyOwner { //require(address(breedingMarket) == address(0)); //require(address(saleMarket) == address(0)); breedingMarket = MarketInterface(_breedingAddress); saleMarket = MarketInterface(_saleAddress); } /// @dev Completes a breeding auction by bidding. /// Immediately breeds the winning mom with the dad on auction. /// @param _dadId - ID of the dad on auction. /// @param _momId - ID of the mom owned by the bidder. function bidOnBreedingAuction( uint40 _dadId, uint40 _momId ) public payable whenNotPaused returns (uint256) { // Auction contract checks input sizes require(_isOwner(msg.sender, _momId)); require(canBreed(_momId)); require(_canMateViaMarketplace(_momId, _dadId)); // Take breeding fee uint256 fee = getBreedingFee(_momId, _dadId); require(msg.value >= fee); // breeding auction will throw if the bid fails. breedingMarket.bid.value(msg.value - fee)(_dadId); return _breedWith(_momId, _dadId); } /// @dev Put a cutie up for auction. /// Does some ownership trickery for creating auctions in one transaction. /// Optional money amount can be sent to contract to feature auction. /// Pricea are available on web. function createSaleAuction( uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration ) public whenNotPaused payable { // Auction contract checks input sizes // If cutie is already on any auction, this will throw // because it will be owned by the auction contract. require(_isOwner(msg.sender, _cutieId)); _approve(_cutieId, saleMarket); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the cutie. saleMarket.createAuction.value(msg.value)( _cutieId, _startPrice, _endPrice, _duration, msg.sender ); } /// @dev The address of the sibling contract that is used to implement the genetic combination algorithm. GeneMixerInterface geneMixer; /// @dev Check if dad has authorized breeding with the mom. True if both dad /// and mom have the same owner, or if the dad has given breeding permission to /// the mom's owner (via approveBreeding()). function _isBreedingPermitted(uint40 _dadId, uint40 _momId) internal view returns (bool) { address momOwner = cutieIndexToOwner[_momId]; address dadOwner = cutieIndexToOwner[_dadId]; // Breeding is approved if they have same owner, or if the mom's owner was given // permission to breed with the dad. return (momOwner == dadOwner || sireAllowedToAddress[_dadId] == momOwner); } /// @dev Update the address of the genetic contract. /// @param _address An address of a GeneMixer contract instance to be used from this point forward. function setGeneMixerAddress(address _address) public onlyOwner { GeneMixerInterface candidateContract = GeneMixerInterface(_address); require(candidateContract.isGeneMixer()); // Set the new contract address geneMixer = candidateContract; } /// @dev Checks that a given cutie is able to breed. Requires that the /// current cooldown is finished (for dads) function _canBreed(Cutie _cutie) internal view returns (bool) { return _cutie.cooldownEndTime <= now; } /// @notice Grants approval to another user to sire with one of your Cuties. /// @param _addr The address that will be able to sire with your Cutie. Set to /// address(0) to clear all breeding approvals for this Cutie. /// @param _dadId A Cutie that you own that _addr will now be able to dad with. function approveBreeding(address _addr, uint40 _dadId) public whenNotPaused { require(_isOwner(msg.sender, _dadId)); sireAllowedToAddress[_dadId] = _addr; emit BreedingApproval(msg.sender, _addr, _dadId); } /// @dev Set the cooldownEndTime for the given Cutie, based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _cutie A reference to the Cutie in storage which needs its timer started. function _triggerCooldown(uint40 _cutieId, Cutie storage _cutie) internal { // Compute the end of the cooldown time, based on current cooldownIndex uint40 oldValue = _cutie.cooldownIndex; _cutie.cooldownEndTime = config.getCooldownEndTimeFromIndex(_cutie.cooldownIndex); emit CooldownEndTimeChanged(_cutieId, oldValue, _cutie.cooldownEndTime); // Increment the breeding count. if (_cutie.cooldownIndex + 1 < config.getCooldownIndexCount()) { uint16 oldValue2 = _cutie.cooldownIndex; _cutie.cooldownIndex++; emit CooldownIndexChanged(_cutieId, oldValue2, _cutie.cooldownIndex); } } /// @notice Checks that a certain cutie is not /// in the middle of a breeding cooldown and is able to breed. /// @param _cutieId reference the id of the cutie, any user can inquire about it function canBreed(uint40 _cutieId) public view returns (bool) { require(_cutieId > 0); Cutie storage cutie = cuties[_cutieId]; return _canBreed(cutie); } /// @dev Check if given mom and dad are a valid mating pair. function _canPairMate( Cutie storage _mom, uint40 _momId, Cutie storage _dad, uint40 _dadId ) private view returns(bool) { // A Cutie can't breed with itself. if (_dadId == _momId) { return false; } // Cuties can't breed with their parents. if (_mom.momId == _dadId) { return false; } if (_mom.dadId == _dadId) { return false; } if (_dad.momId == _momId) { return false; } if (_dad.dadId == _momId) { return false; } // We can short circuit the sibling check (below) if either cat is // gen zero (has a mom ID of zero). if (_dad.momId == 0) { return true; } if (_mom.momId == 0) { return true; } // Cuties can't breed with full or half siblings. if (_dad.momId == _mom.momId) { return false; } if (_dad.momId == _mom.dadId) { return false; } if (_dad.dadId == _mom.momId) { return false; } if (_dad.dadId == _mom.dadId) { return false; } if (geneMixer.canBreed(_momId, _mom.genes, _dadId, _dad.genes)) { return true; } return false; } /// @notice Checks to see if two cuties can breed together (checks both /// ownership and breeding approvals, but does not check if both cuties are ready for /// breeding). /// @param _momId The ID of the proposed mom. /// @param _dadId The ID of the proposed dad. function canBreedWith(uint40 _momId, uint40 _dadId) public view returns(bool) { require(_momId > 0); require(_dadId > 0); Cutie storage mom = cuties[_momId]; Cutie storage dad = cuties[_dadId]; return _canPairMate(mom, _momId, dad, _dadId) && _isBreedingPermitted(_dadId, _momId); } /// @dev Internal check to see if a given dad and mom are a valid mating pair for /// breeding via market (this method doesn't check ownership and if mating is allowed). function _canMateViaMarketplace(uint40 _momId, uint40 _dadId) internal view returns (bool) { Cutie storage mom = cuties[_momId]; Cutie storage dad = cuties[_dadId]; return _canPairMate(mom, _momId, dad, _dadId); } function getBreedingFee(uint40 _momId, uint40 _dadId) public view returns (uint256) { return config.getBreedingFee(_momId, _dadId); } /// @notice Breed cuties that you own, or for which you /// have previously been given Breeding approval. Will either make your cutie give birth, or will /// fail. /// @param _momId The ID of the Cutie acting as mom (will end up give birth if successful) /// @param _dadId The ID of the Cutie acting as dad (will begin its breeding cooldown if successful) function breedWith(uint40 _momId, uint40 _dadId) public whenNotPaused payable returns (uint40) { // Caller must own the mom. require(_isOwner(msg.sender, _momId)); // Neither dad nor mom can be on auction during // breeding. // For mom: The caller of this function can't be the owner of the mom // because the owner of a Cutie on auction is the auction house, and the // auction house will never call breedWith(). // For dad: Similarly, a dad on auction will be owned by the auction house // and the act of transferring ownership will have cleared any outstanding // breeding approval. // Thus we don't need check if either cutie // is on auction. // Check that mom and dad are both owned by caller, or that the dad // has given breeding permission to caller (i.e. mom's owner). // Will fail for _dadId = 0 require(_isBreedingPermitted(_dadId, _momId)); // Check breeding fee require(getBreedingFee(_momId, _dadId) <= msg.value); // Grab a reference to the potential mom Cutie storage mom = cuties[_momId]; // Make sure mom's cooldown isn't active, or in the middle of a breeding cooldown require(_canBreed(mom)); // Grab a reference to the potential dad Cutie storage dad = cuties[_dadId]; // Make sure dad cooldown isn't active, or in the middle of a breeding cooldown require(_canBreed(dad)); // Test that these cuties are a valid mating pair. require(_canPairMate( mom, _momId, dad, _dadId )); return _breedWith(_momId, _dadId); } /// @dev Internal utility function to start breeding, assumes that all breeding /// requirements have been checked. function _breedWith(uint40 _momId, uint40 _dadId) internal returns (uint40) { // Grab a reference to the Cuties from storage. Cutie storage dad = cuties[_dadId]; Cutie storage mom = cuties[_momId]; // Trigger the cooldown for both parents. _triggerCooldown(_dadId, dad); _triggerCooldown(_momId, mom); // Clear breeding permission for both parents. delete sireAllowedToAddress[_momId]; delete sireAllowedToAddress[_dadId]; // Check that the mom is a valid cutie. require(mom.birthTime != 0); // Determine the higher generation number of the two parents uint16 babyGen = config.getBabyGen(mom.generation, dad.generation); // Call the gene mixing operation. uint256 childGenes = geneMixer.mixGenes(mom.genes, dad.genes); // Make the new cutie address owner = cutieIndexToOwner[_momId]; uint40 cutieId = _createCutie(_momId, _dadId, babyGen, getCooldownIndexFromGeneration(babyGen), childGenes, owner, mom.cooldownEndTime); // return the new cutie's ID return cutieId; } mapping(address => uint40) isTutorialPetUsed; /// @dev Completes a breeding tutorial cutie (non existing in blockchain) /// with auction by bidding. Immediately breeds with dad on auction. /// @param _dadId - ID of the dad on auction. function bidOnBreedingAuctionTutorial( uint40 _dadId ) public payable whenNotPaused returns (uint) { require(isTutorialPetUsed[msg.sender] == 0); // Take breeding fee uint256 fee = getBreedingFee(0, _dadId); require(msg.value >= fee); // breeding auction will throw if the bid fails. breedingMarket.bid.value(msg.value - fee)(_dadId); // Grab a reference to the Cuties from storage. Cutie storage dad = cuties[_dadId]; // Trigger the cooldown for parent. _triggerCooldown(_dadId, dad); // Clear breeding permission for parent. delete sireAllowedToAddress[_dadId]; uint16 babyGen = config.getTutorialBabyGen(dad.generation); // tutorial pet genome is zero uint256 childGenes = geneMixer.mixGenes(0x0, dad.genes); // tutorial pet id is zero uint40 cutieId = _createCutie(0, _dadId, babyGen, getCooldownIndexFromGeneration(babyGen), childGenes, msg.sender, 12); isTutorialPetUsed[msg.sender] = cutieId; // return the new cutie's ID return cutieId; } address party1address; address party2address; address party3address; address party4address; address party5address; /// @dev Setup project owners function setParties(address _party1, address _party2, address _party3, address _party4, address _party5) public onlyOwner { require(_party1 != address(0)); require(_party2 != address(0)); require(_party3 != address(0)); require(_party4 != address(0)); require(_party5 != address(0)); party1address = _party1; party2address = _party2; party3address = _party3; party4address = _party4; party5address = _party5; } /// @dev Reject all Ether which is not from game contracts from being sent here. function() external payable { require( msg.sender == address(saleMarket) || msg.sender == address(breedingMarket) || address(plugins[msg.sender]) != address(0) ); } /// @dev The balance transfer from the market and plugins contract /// to the CutieCore contract. function withdrawBalances() external { require( msg.sender == ownerAddress || msg.sender == operatorAddress); saleMarket.withdrawEthFromBalance(); breedingMarket.withdrawEthFromBalance(); for (uint32 i = 0; i < pluginsArray.length; ++i) { pluginsArray[i].withdraw(); } } /// @dev The balance transfer from CutieCore contract to project owners function withdrawEthFromBalance() external { require( msg.sender == party1address || msg.sender == party2address || msg.sender == party3address || msg.sender == party4address || msg.sender == party5address || msg.sender == ownerAddress || msg.sender == operatorAddress); require(party1address != 0); require(party2address != 0); require(party3address != 0); require(party4address != 0); require(party5address != 0); uint256 total = address(this).balance; party1address.transfer(total*105/1000); party2address.transfer(total*105/1000); party3address.transfer(total*140/1000); party4address.transfer(total*140/1000); party5address.transfer(total*510/1000); } /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <arachnid@notdot.net> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ struct slice { uint _len; uint _ptr; } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal pure returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice self, slice other) internal pure returns (string) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } function uintToString(uint256 a) internal pure returns (string result) { string memory r = ""; do { uint b = a % 10; a /= 10; string memory c = ""; if (b == 0) c = "0"; else if (b == 1) c = "1"; else if (b == 2) c = "2"; else if (b == 3) c = "3"; else if (b == 4) c = "4"; else if (b == 5) c = "5"; else if (b == 6) c = "6"; else if (b == 7) c = "7"; else if (b == 8) c = "8"; else if (b == 9) c = "9"; r = concat(toSlice(c), toSlice(r)); } while (a > 0); result = r; } }
Put a cutie up for plugin feature. If cutie is already on any auction or in adventure, this will throw because it will be owned by the other contract. If _cutieId is 0, then cutie is not used on this feature.
function runPlugin( address _pluginAddress, uint40 _cutieId, uint256 _parameter ) public whenNotPaused payable { require(_cutieId == 0 || _isOwner(msg.sender, _cutieId)); require(address(plugins[_pluginAddress]) != address(0)); if (_cutieId > 0) { _approve(_cutieId, _pluginAddress); } _cutieId, _parameter, msg.sender ); }
12,941,796
pragma solidity ^0.5.0; import "./SafeERC20.sol"; import "./Ownable.sol"; import "./SafeMath.sol"; /** * @title PartnersVesting * @dev A token holder contract that can release its token balance gradually at different vesting points */ contract TokenVesting is Ownable { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMath for uint256; using SafeERC20 for IERC20; event TokensReleased(address token, uint256 amount); // The token being vested IERC20 public _token; // beneficiary of tokens after they are released address private _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private _start; uint256 private _released = 0; uint256 private _amount = 0; uint256[] private _schedule; uint256[] private _percent; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param token ERC20 token which is being vested * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param amount Amount of tokens being vested * @param schedule array of the timestamps (as Unix time) at which point vesting starts * @param percent array of the percents which can be released at which vesting points */ constructor (IERC20 token, address beneficiary, uint256 amount, uint256[] memory schedule, uint256[] memory percent) public { require(beneficiary != address(0), "TokenVesting: beneficiary is the zero address"); require(schedule.length == percent.length, "TokenVesting: Incorrect release schedule"); require(schedule.length <= 255); _token = token; _beneficiary = beneficiary; _amount = amount; _schedule = schedule; _percent = percent; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @dev Throws if called by any account other than the beneficiary. */ modifier onlyBeneficiary() { require(isBeneficiary(), "caller is not the beneficiary"); _; } /** * @dev Returns true if the caller is the current beneficiary. */ function isBeneficiary() private view returns (bool) { return _msgSender() == _beneficiary; } /** * @dev Change token contract address. * Can only be called by the current beneficiary. */ function changeTokenAddress(IERC20 newToken) public onlyBeneficiary { _token = newToken; } /** * @return the vesting token address. */ function tokenAddress() public view returns (IERC20) { return _token; } /** * @return the schedule and percent arrays. */ function getScheduleAndPercent() public view returns (uint256[] memory, uint256[] memory) { return (_schedule,_percent); } /** * @return the start time of the token vesting. */ function totalAmount() public view returns (uint256) { return _amount; } /** * @return the amount of the token released. */ function released() public view returns (uint256) { return _released; } /** * @return the vested amount of the token for a particular timestamp. */ function vestedAmount(uint256 ts) public view returns (uint256) { int8 unreleasedIdx = _releasableIdx(ts); if (unreleasedIdx >= 0) { return _amount.mul(_percent[uint(unreleasedIdx)]).div(10000); } else { return 0; } } /** * @notice Transfers vested tokens to beneficiary. */ function release() public { int8 unreleasedIdx = _releasableIdx(block.timestamp); require(unreleasedIdx >= 0, "TokenVesting: no tokens are due"); uint256 unreleasedAmount = _amount.mul(_percent[uint(unreleasedIdx)]).div(10000); _token.safeTransfer(_beneficiary, unreleasedAmount); _percent[uint(unreleasedIdx)] = 0; _released = _released.add(unreleasedAmount); emit TokensReleased(address(_token), unreleasedAmount); } /** * @dev Calculates the index that has already vested but hasn't been released yet. */ function _releasableIdx(uint256 ts) private view returns (int8) { for (uint8 i = 0; i < _schedule.length; i++) { if (ts > _schedule[i] && _percent[i] > 0) { return int8(i); } } return -1; } }
return the start time of the token vesting./
function totalAmount() public view returns (uint256) { return _amount; }
6,986,764
./full_match/1/0x688615BBEAb622c14DE67A762751d7E99875EeF7/sources/contracts/Xdog.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("XDOG", "XDOG") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMktFee = 2; uint256 _buyLiquidityFee = 2; uint256 _buyTeamFee = 0; uint256 _sellMktFee = 2; uint256 _sellLiquidityFee = 2; uint256 totalSupply = 1_000_000_000 * 1e18; buyMktFee = _buyMktFee; buyLiquidityFee = _buyLiquidityFee; buyTeamFee = _buyTeamFee; buyTotalFees = buyMktFee + buyLiquidityFee + buyTeamFee; sellMktFee = _sellMktFee; sellLiquidityFee = _sellLiquidityFee; sellTeamFee = _sellTeamFee; sellTotalFees = sellMktFee + sellLiquidityFee + sellTeamFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); preMigrationTransferrable[owner()] = true; _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
4,825,658
pragma solidity 0.4.26; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * Don't use this function. */ /* function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } */ /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract Stoppable is Ownable{ bool public stopped = false; modifier enabled { require (!stopped); _; } function stop() external onlyOwner { stopped = true; } function start() external onlyOwner { stopped = false; } } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != 0); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != 0); require(value <= _balances[account]); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ /* --Do not use function burnFrom(address from, uint256 value) public { _burnFrom(from, value); //Only the owner's address can be burned. @ejkang } */ } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string name, string symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } } contract BMPToken is ERC20Detailed, ERC20Burnable, Stoppable { constructor ( string memory name, string memory symbol, uint256 totalSupply, uint8 decimals ) ERC20Detailed(name, symbol, decimals) public { _mint(owner(), totalSupply * 10**uint(decimals)); } // Don't accept ETH function () payable external { revert(); } //------------------------ // Lock account transfer mapping (address => uint256) private _lockTimes; mapping (address => uint256) private _lockAmounts; event LockChanged(address indexed account, uint256 releaseTime, uint256 amount); /// Lock user amount. (run only owner) /// @param account account to lock /// @param releaseTime Time to release from lock state. /// @param amount amount to lock. /// @return Boolean function setLock(address account, uint256 releaseTime, uint256 amount) onlyOwner public { //require(now < releaseTime, "ERC20 : Current time is greater than release time"); require(block.timestamp < releaseTime, "ERC20 : Current time is greater than release time"); require(amount != 0, "ERC20: Amount error"); _lockTimes[account] = releaseTime; _lockAmounts[account] = amount; emit LockChanged( account, releaseTime, amount ); } /// Get Lock information (run anyone) /// @param account user acount /// @return lokced time and locked amount. function getLock(address account) public view returns (uint256 lockTime, uint256 lockAmount) { return (_lockTimes[account], _lockAmounts[account]); } /// Check lock state (run anyone) /// @param account user acount /// @param amount amount to check. /// @return Boolean : Don't use balance (true) function _isLocked(address account, uint256 amount) internal view returns (bool) { return _lockAmounts[account] != 0 && _lockTimes[account] > block.timestamp && ( balanceOf(account) <= _lockAmounts[account] || balanceOf(account).sub(_lockAmounts[account]) < amount ); } /// Transfer token (run anyone) /// @param recipient Token trasfer destination acount. /// @param amount Token transfer amount. /// @return Boolean function transfer(address recipient, uint256 amount) enabled public returns (bool) { require( !_isLocked( msg.sender, amount ) , "ERC20: Locked balance"); return super.transfer(recipient, amount); } /// Transfer token (run anyone) /// @param sender Token trasfer source acount. /// @param recipient Token transfer destination acount. /// @param amount Token transfer amount. /// @return Boolean function transferFrom(address sender, address recipient, uint256 amount) enabled public returns (bool) { require( !_isLocked( sender, amount ) , "ERC20: Locked balance"); return super.transferFrom(sender, recipient, amount); } /// Decrease token balance (run only owner) /// @param value Amount to decrease. function burn(uint256 value) onlyOwner public { require( !_isLocked( msg.sender, value ) , "ERC20: Locked balance"); super.burn(value); } }
Total number of tokens in existence/
function totalSupply() public view returns (uint256) { return _totalSupply; }
7,330,784
./full_match/1/0x26c2e43405cF79720a3A4117613425D037683a64/sources/src/arbi-fed/ArbiGovMessengerL1.sol
Send message to L2 address This function automatically handles gas estimation. Default gas limit may be too low to execute. _to L2 address to send message to _functionSelector Function selector of the function to call at the L2 address _data The calldata to the L2 address/
function sendMessage( address _to, bytes4 _functionSelector, bytes calldata _data ) external payable onlyAllowed() returns (uint256) { emit MessageSent(_to, _data); uint gasLimit = functionGasLimit[functionId]; if(gasLimit == 0) gasLimit = defaultGasLimit; _to, 0, maxSubmissionCost, refundAddress, gasLimit, gasPrice, _data ); }
3,019,999
./full_match/1/0x82a7b5842085f434c6584A8c44b6A1C15c25a512/sources/contracts/Pool.sol
@inheritdoc IPool/
function quote( uint256 principal, uint64 duration, address collateralToken, uint256[] calldata collateralTokenIds, uint256 collateralTokenCount, uint128[] calldata ticks, bytes calldata options ) external view returns (uint256) { (uint256 repayment, , ) = _quote( principal, duration, collateralToken, collateralTokenIds, collateralTokenCount, ticks, _getOptionsData(options, BorrowOptions.CollateralFilterContext), false ); return repayment;
9,659,207
./partial_match/42/0x9266D722f9F559D3a9588BB21579AED5f058b297/sources/AMMExchange.sol
Sell some amount of complete sets for a market _market The market to sell complete sets in _holder The holder of the complete sets _recipient The recipient of funds from the sale _amount The number of complete sets to sell _fingerprint Fingerprint of the filler used to naively restrict affiliate fee dispursement return (uint256 _creatorFee, uint256 _reportingFee) The fees taken for the market creator and reporting respectively/
function sellCompleteSets(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee) { require(_holder == msg.sender || isApprovedForAll(_holder, msg.sender) == true, "ERC1155: need operator approval to sell complete sets"); (uint256 _payout, uint256 _creatorFee, uint256 _reportingFee) = burnCompleteSets(_market, _holder, _amount, _holder, _fingerprint); require(cash.transfer(_recipient, _payout)); assertBalances(_market); return (_creatorFee, _reportingFee); }
3,418,352
pragma solidity 0.4.25; // File: contracts/sogur/interfaces/IMonetaryModelState.sol /** * @title Monetary Model State Interface. */ interface IMonetaryModelState { /** * @dev Set the total amount of SDR in the model. * @param _amount The total amount of SDR in the model. */ function setSdrTotal(uint256 _amount) external; /** * @dev Set the total amount of SGR in the model. * @param _amount The total amount of SGR in the model. */ function setSgrTotal(uint256 _amount) external; /** * @dev Get the total amount of SDR in the model. * @return The total amount of SDR in the model. */ function getSdrTotal() external view returns (uint256); /** * @dev Get the total amount of SGR in the model. * @return The total amount of SGR in the model. */ function getSgrTotal() external view returns (uint256); } // File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol /** * @title Contract Address Locator Interface. */ interface IContractAddressLocator { /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) external view returns (address); /** * @dev Determine whether or not a contract address relates to one of the identifiers. * @param _contractAddress The contract address to look for. * @param _identifiers The identifiers. * @return A boolean indicating if the contract address relates to one of the identifiers. */ function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool); } // File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol /** * @title Contract Address Locator Holder. * @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system. * @dev Any contract which inherits from this contract can retrieve the address of any contract in the system. * @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system. * @dev In addition to that, any function in any contract can be restricted to a specific caller. */ contract ContractAddressLocatorHolder { bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource"; bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ; bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ; bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ; bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ; bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ; bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ; bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ; bytes32 internal constant _IMintHandler_ = "IMintHandler" ; bytes32 internal constant _IMintListener_ = "IMintListener" ; bytes32 internal constant _IMintManager_ = "IMintManager" ; bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ; bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ; bytes32 internal constant _IRedButton_ = "IRedButton" ; bytes32 internal constant _IReserveManager_ = "IReserveManager" ; bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ; bytes32 internal constant _ISogurExchanger_ = "ISogurExchanger" ; bytes32 internal constant _SgnToSgrExchangeInitiator_ = "SgnToSgrExchangeInitiator" ; bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ; bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ; bytes32 internal constant _ISGRAuthorizationManager_ = "ISGRAuthorizationManager"; bytes32 internal constant _ISGRToken_ = "ISGRToken" ; bytes32 internal constant _ISGRTokenManager_ = "ISGRTokenManager" ; bytes32 internal constant _ISGRTokenInfo_ = "ISGRTokenInfo" ; bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager"; bytes32 internal constant _ISGNToken_ = "ISGNToken" ; bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ; bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ; bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ; bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ; bytes32 internal constant _BuyWalletsTradingDataSource_ = "BuyWalletsTradingDataSource" ; bytes32 internal constant _SellWalletsTradingDataSource_ = "SellWalletsTradingDataSource" ; bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ; bytes32 internal constant _BuyWalletsTradingLimiter_SGRTokenManager_ = "BuyWalletsTLSGRTokenManager" ; bytes32 internal constant _SellWalletsTradingLimiter_SGRTokenManager_ = "SellWalletsTLSGRTokenManager" ; bytes32 internal constant _IETHConverter_ = "IETHConverter" ; bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ; bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ; bytes32 internal constant _IRateApprover_ = "IRateApprover" ; bytes32 internal constant _SGAToSGRInitializer_ = "SGAToSGRInitializer" ; IContractAddressLocator private contractAddressLocator; /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) internal { require(_contractAddressLocator != address(0), "locator is illegal"); contractAddressLocator = _contractAddressLocator; } /** * @dev Get the contract address locator. * @return The contract address locator. */ function getContractAddressLocator() external view returns (IContractAddressLocator) { return contractAddressLocator; } /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) internal view returns (address) { return contractAddressLocator.getContractAddress(_identifier); } /** * @dev Determine whether or not the sender relates to one of the identifiers. * @param _identifiers The identifiers. * @return A boolean indicating if the sender relates to one of the identifiers. */ function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) { return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers); } /** * @dev Verify that the caller is mapped to a given identifier. * @param _identifier The identifier. */ modifier only(bytes32 _identifier) { require(msg.sender == getContractAddress(_identifier), "caller is illegal"); _; } } // File: contracts/sogur/MonetaryModelState.sol /** * Details of usage of licenced software see here: https://www.sogur.com/software/readme_v1 */ /** * @title Monetary Model State. */ contract MonetaryModelState is IMonetaryModelState, ContractAddressLocatorHolder { string public constant VERSION = "1.1.0"; bool public initialized; uint256 public sdrTotal; uint256 public sgrTotal; event MonetaryModelStateInitialized(address indexed _initializer, uint256 _sdrTotal, uint256 _sgrTotal); /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {} /** * @dev Reverts if called when the contract is already initialized. */ modifier onlyIfNotInitialized() { require(!initialized, "contract already initialized"); _; } /** * @dev Initialize the contract. * @param _sdrTotal The total amount of SDR in the model. * @param _sgrTotal The total amount of SGR in the model. */ function init(uint256 _sdrTotal, uint256 _sgrTotal) external onlyIfNotInitialized only(_SGAToSGRInitializer_) { initialized = true; sdrTotal = _sdrTotal; sgrTotal = _sgrTotal; emit MonetaryModelStateInitialized(msg.sender, _sdrTotal, _sgrTotal); } /** * @dev Set the total amount of SDR in the model. * @param _amount The total amount of SDR in the model. */ function setSdrTotal(uint256 _amount) external only(_IMonetaryModel_) { sdrTotal = _amount; } /** * @dev Set the total amount of SGR in the model. * @param _amount The total amount of SGR in the model. */ function setSgrTotal(uint256 _amount) external only(_IMonetaryModel_) { sgrTotal = _amount; } /** * @dev Get the total amount of SDR in the model. * @return The total amount of SDR in the model. */ function getSdrTotal() external view returns (uint256) { return sdrTotal; } /** * @dev Get the total amount of SGR in the model. * @return The total amount of SGR in the model. */ function getSgrTotal() external view returns (uint256) { return sgrTotal; } } // File: contracts/sogur/interfaces/IPaymentHandler.sol /** * @title Payment Handler Interface. */ interface IPaymentHandler { /** * @dev Get the amount of available ETH. * @return The amount of available ETH. */ function getEthBalance() external view returns (uint256); /** * @dev Transfer ETH to an SGR holder. * @param _to The address of the SGR holder. * @param _value The amount of ETH to transfer. */ function transferEthToSgrHolder(address _to, uint256 _value) external; } // File: contracts/sogur/interfaces/IMintListener.sol /** * @title Mint Listener Interface. */ interface IMintListener { /** * @dev Mint SGR for SGN holders. * @param _value The amount of SGR to mint. */ function mintSgrForSgnHolders(uint256 _value) external; } // File: contracts/sogur/interfaces/ISGRTokenManager.sol /** * @title SGR Token Manager Interface. */ interface ISGRTokenManager { /** * @dev Exchange ETH for SGR. * @param _sender The address of the sender. * @param _ethAmount The amount of ETH received. * @return The amount of SGR that the sender is entitled to. */ function exchangeEthForSgr(address _sender, uint256 _ethAmount) external returns (uint256); /** * @dev Handle after the ETH for SGR exchange operation. * @param _sender The address of the sender. * @param _ethAmount The amount of ETH received. * @param _sgrAmount The amount of SGR given. */ function afterExchangeEthForSgr(address _sender, uint256 _ethAmount, uint256 _sgrAmount) external; /** * @dev Exchange SGR for ETH. * @param _sender The address of the sender. * @param _sgrAmount The amount of SGR received. * @return The amount of ETH that the sender is entitled to. */ function exchangeSgrForEth(address _sender, uint256 _sgrAmount) external returns (uint256); /** * @dev Handle after the SGR for ETH exchange operation. * @param _sender The address of the sender. * @param _sgrAmount The amount of SGR received. * @param _ethAmount The amount of ETH given. * @return The is success result. */ function afterExchangeSgrForEth(address _sender, uint256 _sgrAmount, uint256 _ethAmount) external returns (bool); /** * @dev Handle direct SGR transfer. * @param _sender The address of the sender. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. */ function uponTransfer(address _sender, address _to, uint256 _value) external; /** * @dev Handle after direct SGR transfer operation. * @param _sender The address of the sender. * @param _to The address of the destination account. * @param _value The SGR transferred amount. * @param _transferResult The transfer result. * @return is success result. */ function afterTransfer(address _sender, address _to, uint256 _value, bool _transferResult) external returns (bool); /** * @dev Handle custodian SGR transfer. * @param _sender The address of the sender. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. */ function uponTransferFrom(address _sender, address _from, address _to, uint256 _value) external; /** * @dev Handle after custodian SGR transfer operation. * @param _sender The address of the sender. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The SGR transferred amount. * @param _transferFromResult The transferFrom result. * @return is success result. */ function afterTransferFrom(address _sender, address _from, address _to, uint256 _value, bool _transferFromResult) external returns (bool); /** * @dev Handle the operation of ETH deposit into the SGRToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGRToken contract. * @param _amount The deposited ETH amount. * @return The address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. */ function uponDeposit(address _sender, uint256 _balance, uint256 _amount) external returns (address, uint256); /** * @dev Handle the operation of ETH withdrawal from the SGRToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGRToken contract prior the withdrawal. * @return The address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. */ function uponWithdraw(address _sender, uint256 _balance) external returns (address, uint256); /** * @dev Handle after ETH withdrawal from the SGRToken contract operation. * @param _sender The address of the account which has issued the operation. * @param _wallet The address of the withdrawal wallet. * @param _amount The ETH withdraw amount. * @param _priorWithdrawEthBalance The amount of ETH in the SGRToken contract prior the withdrawal. * @param _afterWithdrawEthBalance The amount of ETH in the SGRToken contract after the withdrawal. */ function afterWithdraw(address _sender, address _wallet, uint256 _amount, uint256 _priorWithdrawEthBalance, uint256 _afterWithdrawEthBalance) external; /** * @dev Upon SGR mint for SGN holders. * @param _value The amount of SGR to mint. */ function uponMintSgrForSgnHolders(uint256 _value) external; /** * @dev Handle after SGR mint for SGN holders. * @param _value The minted amount of SGR. */ function afterMintSgrForSgnHolders(uint256 _value) external; /** * @dev Upon SGR transfer to an SGN holder. * @param _to The address of the SGN holder. * @param _value The amount of SGR to transfer. */ function uponTransferSgrToSgnHolder(address _to, uint256 _value) external; /** * @dev Handle after SGR transfer to an SGN holder. * @param _to The address of the SGN holder. * @param _value The transferred amount of SGR. */ function afterTransferSgrToSgnHolder(address _to, uint256 _value) external; /** * @dev Upon ETH transfer to an SGR holder. * @param _to The address of the SGR holder. * @param _value The amount of ETH to transfer. * @param _status The operation's completion-status. */ function postTransferEthToSgrHolder(address _to, uint256 _value, bool _status) external; /** * @dev Get the address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. * @return The address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. */ function getDepositParams() external view returns (address, uint256); /** * @dev Get the address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. * @return The address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. */ function getWithdrawParams() external view returns (address, uint256); } // File: contracts/saga-genesis/interfaces/ISogurExchanger.sol /** * @title Sogur Exchanger Interface. */ interface ISogurExchanger { /** * @dev Transfer SGR to an SGN holder. * @param _to The address of the SGN holder. * @param _value The amount of SGR to transfer. */ function transferSgrToSgnHolder(address _to, uint256 _value) external; } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from], "sdjfndskjfndskjfb"); require(to != address(0), "asfdsf"); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != 0); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != 0, "heerrrrrsss"); require(value <= _balances[account], "heerrrrr"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } // File: contracts/sogur/interfaces/ISGRTokenInfo.sol /** * @title SGR Token Info Interface. */ interface ISGRTokenInfo { /** * @return the name of the sgr token. */ function getName() external pure returns (string); /** * @return the symbol of the sgr token. */ function getSymbol() external pure returns (string); /** * @return the number of decimals of the sgr token. */ function getDecimals() external pure returns (uint8); } // File: contracts/sogur/SGRToken.sol /** * Details of usage of licenced software see here: https://www.sogur.com/software/readme_v1 */ /** * @title Sogur Token. * @dev ERC20 compatible. * @dev Exchange ETH for SGR. * @dev Exchange SGR for ETH. */ contract SGRToken is ERC20, ContractAddressLocatorHolder, IMintListener, ISogurExchanger, IPaymentHandler { string public constant VERSION = "2.0.0"; bool public initialized; event SgrTokenInitialized(address indexed _initializer, address _sgaToSGRTokenExchangeAddress, uint256 _sgaToSGRTokenExchangeSGRSupply); /** * @dev Public Address 0x6e9Cd21f2B9033ea0953943c81A041fe203D5E55. * @notice SGR will be minted at this public address for SGN holders. * @notice SGR will be transferred from this public address upon conversion by an SGN holder. * @notice It is generated in a manner which ensures that the corresponding private key is unknown. */ address public constant SGR_MINTED_FOR_SGN_HOLDERS = address(keccak256("SGR_MINTED_FOR_SGN_HOLDERS")); /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {} /** * @dev Return the contract which implements the ISGRTokenManager interface. */ function getSGRTokenManager() public view returns (ISGRTokenManager) { return ISGRTokenManager(getContractAddress(_ISGRTokenManager_)); } /** * @dev Return the contract which implements ISGRTokenInfo interface. */ function getSGRTokenInfo() public view returns (ISGRTokenInfo) { return ISGRTokenInfo(getContractAddress(_ISGRTokenInfo_)); } /** * @dev Return the sgr token name. */ function name() public view returns (string) { return getSGRTokenInfo().getName(); } /** * @dev Return the sgr token symbol. */ function symbol() public view returns (string){ return getSGRTokenInfo().getSymbol(); } /** * @dev Return the sgr token number of decimals. */ function decimals() public view returns (uint8){ return getSGRTokenInfo().getDecimals(); } /** * @dev Reverts if called when the contract is already initialized. */ modifier onlyIfNotInitialized() { require(!initialized, "contract already initialized"); _; } /** * @dev Exchange ETH for SGR. * @notice Can be executed from externally-owned accounts but not from other contracts. * @notice This is due to the insufficient gas-stipend provided to the fallback function. */ function() external payable { ISGRTokenManager sgrTokenManager = getSGRTokenManager(); uint256 amount = sgrTokenManager.exchangeEthForSgr(msg.sender, msg.value); _mint(msg.sender, amount); sgrTokenManager.afterExchangeEthForSgr(msg.sender, msg.value, amount); } /** * @dev Exchange ETH for SGR. * @notice Can be executed from externally-owned accounts as well as from other contracts. */ function exchange() external payable { ISGRTokenManager sgrTokenManager = getSGRTokenManager(); uint256 amount = sgrTokenManager.exchangeEthForSgr(msg.sender, msg.value); _mint(msg.sender, amount); sgrTokenManager.afterExchangeEthForSgr(msg.sender, msg.value, amount); } /** * @dev Initialize the contract. * @param _sgaToSGRTokenExchangeAddress the contract address. * @param _sgaToSGRTokenExchangeSGRSupply SGR supply for the SGAToSGRTokenExchange contract. */ function init(address _sgaToSGRTokenExchangeAddress, uint256 _sgaToSGRTokenExchangeSGRSupply) external onlyIfNotInitialized only(_SGAToSGRInitializer_) { require(_sgaToSGRTokenExchangeAddress != address(0), "SGA to SGR token exchange address is illegal"); initialized = true; _mint(_sgaToSGRTokenExchangeAddress, _sgaToSGRTokenExchangeSGRSupply); emit SgrTokenInitialized(msg.sender, _sgaToSGRTokenExchangeAddress, _sgaToSGRTokenExchangeSGRSupply); } /** * @dev Transfer SGR to another account. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. * @return Status (true if completed successfully, false otherwise). * @notice If the destination account is this contract, then exchange SGR for ETH. */ function transfer(address _to, uint256 _value) public returns (bool) { ISGRTokenManager sgrTokenManager = getSGRTokenManager(); if (_to == address(this)) { uint256 amount = sgrTokenManager.exchangeSgrForEth(msg.sender, _value); _burn(msg.sender, _value); msg.sender.transfer(amount); return sgrTokenManager.afterExchangeSgrForEth(msg.sender, _value, amount); } sgrTokenManager.uponTransfer(msg.sender, _to, _value); bool transferResult = super.transfer(_to, _value); return sgrTokenManager.afterTransfer(msg.sender, _to, _value, transferResult); } /** * @dev Transfer SGR from one account to another. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. * @return Status (true if completed successfully, false otherwise). * @notice If the destination account is this contract, then the operation is illegal. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { ISGRTokenManager sgrTokenManager = getSGRTokenManager(); require(_to != address(this), "custodian-transfer of SGR into this contract is illegal"); sgrTokenManager.uponTransferFrom(msg.sender, _from, _to, _value); bool transferFromResult = super.transferFrom(_from, _to, _value); return sgrTokenManager.afterTransferFrom(msg.sender, _from, _to, _value, transferFromResult); } /** * @dev Deposit ETH into this contract. */ function deposit() external payable { getSGRTokenManager().uponDeposit(msg.sender, address(this).balance, msg.value); } /** * @dev Withdraw ETH from this contract. */ function withdraw() external { ISGRTokenManager sgrTokenManager = getSGRTokenManager(); uint256 priorWithdrawEthBalance = address(this).balance; (address wallet, uint256 amount) = sgrTokenManager.uponWithdraw(msg.sender, priorWithdrawEthBalance); wallet.transfer(amount); sgrTokenManager.afterWithdraw(msg.sender, wallet, amount, priorWithdrawEthBalance, address(this).balance); } /** * @dev Mint SGR for SGN holders. * @param _value The amount of SGR to mint. */ function mintSgrForSgnHolders(uint256 _value) external only(_IMintManager_) { ISGRTokenManager sgrTokenManager = getSGRTokenManager(); sgrTokenManager.uponMintSgrForSgnHolders(_value); _mint(SGR_MINTED_FOR_SGN_HOLDERS, _value); sgrTokenManager.afterMintSgrForSgnHolders(_value); } /** * @dev Transfer SGR to an SGN holder. * @param _to The address of the SGN holder. * @param _value The amount of SGR to transfer. */ function transferSgrToSgnHolder(address _to, uint256 _value) external only(_SgnToSgrExchangeInitiator_) { ISGRTokenManager sgrTokenManager = getSGRTokenManager(); sgrTokenManager.uponTransferSgrToSgnHolder(_to, _value); _transfer(SGR_MINTED_FOR_SGN_HOLDERS, _to, _value); sgrTokenManager.afterTransferSgrToSgnHolder(_to, _value); } /** * @dev Transfer ETH to an SGR holder. * @param _to The address of the SGR holder. * @param _value The amount of ETH to transfer. */ function transferEthToSgrHolder(address _to, uint256 _value) external only(_IPaymentManager_) { bool status = _to.send(_value); getSGRTokenManager().postTransferEthToSgrHolder(_to, _value, status); } /** * @dev Get the amount of available ETH. * @return The amount of available ETH. */ function getEthBalance() external view returns (uint256) { return address(this).balance; } /** * @dev Get the address of the reserve-wallet and the deficient amount of ETH in this contract. * @return The address of the reserve-wallet and the deficient amount of ETH in this contract. */ function getDepositParams() external view returns (address, uint256) { return getSGRTokenManager().getDepositParams(); } /** * @dev Get the address of the reserve-wallet and the excessive amount of ETH in this contract. * @return The address of the reserve-wallet and the excessive amount of ETH in this contract. */ function getWithdrawParams() external view returns (address, uint256) { return getSGRTokenManager().getWithdrawParams(); } } // File: openzeppelin-solidity/contracts/math/Math.sol /** * @title Math * @dev Assorted math operations */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: openzeppelin-solidity-v1.12.0/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity-v1.12.0/contracts/ownership/Claimable.sol /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/sogur/interfaces/IRedButton.sol /** * @title Red Button Interface. */ interface IRedButton { /** * @dev Get the state of the red-button. * @return The state of the red-button. */ function isEnabled() external view returns (bool); } // File: contracts/migrations/SGAToSGRInitializer.sol /** * Details of usage of licenced software see here: https://www.sogur.com/software/readme_v1 */ /** * @title SGAToSGRInitializer SGA Monetary Model State Interface. */ interface ISGAToSGRInitializerSGAMonetaryModelState { /** * @dev Get the total amount of SGA in the model. * @return The total amount of SGA in the model. */ function getSgaTotal() external view returns (uint256); /** * @dev Get the total amount of SDR in the model. * @return The total amount of SDR in the model. */ function getSdrTotal() external view returns (uint256); } /** * @title SGA to SGR Initializer. */ contract SGAToSGRInitializer is Claimable { string public constant VERSION = "1.0.0"; IRedButton public redButton; IERC20 public sgaToken; SGRToken public sgrToken; ISGAToSGRInitializerSGAMonetaryModelState public sgaMonetaryModelState; MonetaryModelState public sgrMonetaryModelState; address public sgaToSGRTokenExchangeAddress; /** * @dev Create the contract. * @param _redButtonAddress The red button contract address. * @param _sgaTokenAddress The SGA token contract address. * @param _sgrTokenAddress The SGR token contract address. * @param _sgaMonetaryModelStateAddress The SGA MonetaryModelState contract address. * @param _sgrMonetaryModelStateAddress The SGR MonetaryModelState contract address. * @param _sgaToSGRTokenExchangeAddress The SGA to SGR token exchange contract address. */ constructor(address _redButtonAddress, address _sgaTokenAddress, address _sgrTokenAddress, address _sgaMonetaryModelStateAddress, address _sgrMonetaryModelStateAddress, address _sgaToSGRTokenExchangeAddress) public { require(_redButtonAddress != address(0), "red button address is illegal"); require(_sgaTokenAddress != address(0), "SGA token address is illegal"); require(_sgrTokenAddress != address(0), "SGR token address is illegal"); require(_sgaMonetaryModelStateAddress != address(0), "SGA MonetaryModelState address is illegal"); require(_sgrMonetaryModelStateAddress != address(0), "SGR MonetaryModelState address is illegal"); require(_sgaToSGRTokenExchangeAddress != address(0), "SGA to SGR token exchange is illegal"); redButton = IRedButton(_redButtonAddress); sgaToken = IERC20(_sgaTokenAddress); sgrToken = SGRToken(_sgrTokenAddress); sgaMonetaryModelState = ISGAToSGRInitializerSGAMonetaryModelState(_sgaMonetaryModelStateAddress); sgrMonetaryModelState = MonetaryModelState(_sgrMonetaryModelStateAddress); sgaToSGRTokenExchangeAddress = _sgaToSGRTokenExchangeAddress; } /** * @dev Reverts if called when the red button is not enabled. */ modifier onlyIfRedButtonIsEnabled() { require(redButton.isEnabled(), "red button must be enabled"); _; } /** * @dev Execute initialization methods. red button must be enabled for initialization. */ function executeInitialization() external onlyIfRedButtonIsEnabled onlyOwner { uint256 initializationSGRAmount = getInitializationAmount(); sgrToken.init(sgaToSGRTokenExchangeAddress, initializationSGRAmount); sgrMonetaryModelState.init(initializationSGRAmount, initializationSGRAmount); } /** * @dev Return final SGA total supply. used as initial SGR total supply. */ function getInitializationAmount() public view returns (uint256) { uint256 sga1 = sgaToken.totalSupply(); uint256 sga2 = sgaMonetaryModelState.getSgaTotal(); require(sga1 == sga2, "abnormal SGA token state"); uint256 sdr = sgaMonetaryModelState.getSdrTotal(); require(sga2 == sdr, "abnormal SGA monetary model state"); return sga1; } }
SGAToSGRInitializer SGA Monetary Model State Interface./
interface ISGAToSGRInitializerSGAMonetaryModelState { function getSgaTotal() external view returns (uint256); function getSdrTotal() external view returns (uint256); } }
233,102
/** *Submitted for verification at Etherscan.io on 2021-05-13 */ // Southparkcoins ICO // Version of compiler pragma solidity ^0.4.11; // SPDX-License-Identifier: unlicensed contract Southparkcoins { // Introducing the maximum number of Southparkcoins available for sale uint public max_southparkcoins = 9000000000000; // Introducing the USD to Southparkcoins conversion rate uint public usd_to_southparkcoins = 1; // Introducing the total number of Southparkcoins that have been bought by the investors uint public total_southparkcoins_bought = 0; //Mapping from the investor address to its equity in Southparkcoins and usd_to_southparkcoins mapping(address => uint) equity_southparkcoins; mapping(address => uint) equity_usd; // Checking if an investor can buy Southparkcoins modifier can_buy_southparkcoins(uint usd_invested) { require (usd_invested * usd_to_southparkcoins + total_southparkcoins_bought <= max_southparkcoins); _; } // Getting the equity in southparkcoins of an investor function equity_in_southparkcoins(address investor) external constant returns (uint) { return equity_southparkcoins[investor]; } // Getting the equity_in_southparkcoins in USD of an investor function equity_in_usd(address investor) external constant returns (uint) { return equity_usd[investor]; } // Buying southparkcoins function buy_southparkcoins(address investor, uint usd_invested) external can_buy_southparkcoins(usd_invested) { uint southparkcoins_bought = usd_invested * usd_to_southparkcoins; equity_southparkcoins[investor] += southparkcoins_bought; equity_usd[investor] = equity_southparkcoins[investor] / 1 ; total_southparkcoins_bought += southparkcoins_bought; } // Selling Southparkcoins function sell_southparkcoins(address investor, uint southparkcoins_sold) external { equity_southparkcoins[investor] -= southparkcoins_sold; equity_usd[investor] = equity_southparkcoins[investor] / 1; total_southparkcoins_bought -= southparkcoins_sold; } }
Buying southparkcoins
function buy_southparkcoins(address investor, uint usd_invested) external can_buy_southparkcoins(usd_invested) { uint southparkcoins_bought = usd_invested * usd_to_southparkcoins; equity_southparkcoins[investor] += southparkcoins_bought; equity_usd[investor] = equity_southparkcoins[investor] / 1 ; total_southparkcoins_bought += southparkcoins_bought; }
7,984,180
./full_match/4/0x6d20CBCEF3D856Cdf2f7b67935D283cDde7A5ADE/sources/ceshi721.sol
Returns the unpacked `TokenOwnership` struct at `index`./
function _ownershipAt(uint256 index) internal view returns (TokenOwnership memory) { return _unpackedOwnership(_packedOwnerships[index]); }
804,997
./partial_match/1/0x0ace20a35eE382Bda90D1D93CEE65f5970FC01c8/sources/Chip.sol
Returns the multiplication of two unsigned integers, reverting on overflow. Counterpart to Solidity's `` operator. Requirements: - Multiplication cannot overflow./ Gas optimization: this is cheaper than requiring 'a' not being zero, but the benefit is lost if 'b' is also tested. See: https:github.com/OpenZeppelin/openzeppelin-contracts/pull/522
function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; }
4,257,918
./full_match/4/0x64463F7B0d395cFfE20c7a63b009D759eaA9418e/sources/_thirdweb-dev/contracts/ThirdwebContract.sol
Returns the publish metadata for this contract.
function getPublishMetadataUri() external view returns (string memory) { return publishMetadataUri; }
12,395,658
pragma solidity ^0.5.0; contract ResolverBase { bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7; function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == INTERFACE_META_ID; } function isAuthorised(bytes32 node) internal view returns(bool); modifier authorised(bytes32 node) { require(isAuthorised(node)); _; } function bytesToAddress(bytes memory b) internal pure returns(address payable a) { require(b.length == 20); assembly { a := div(mload(add(b, 32)), exp(256, 12)) } } function addressToBytes(address a) internal pure returns(bytes memory b) { b = new bytes(20); assembly { mstore(add(b, 32), mul(a, exp(256, 12))) } } } pragma solidity >=0.5.0; interface ENS { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); // Logged when an operator is added or removed. event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external; function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external; function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external returns(bytes32); function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function setApprovalForAll(address operator, bool approved) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); function recordExists(bytes32 node) external view returns (bool); function isApprovedForAll(address owner, address operator) external view returns (bool); } /** * The ENS registry contract. */ contract ENSRegistry is ENS { struct Record { address owner; address resolver; uint64 ttl; } mapping (bytes32 => Record) records; mapping (address => mapping(address => bool)) operators; // Permits modifications only by the owner of the specified node. modifier authorised(bytes32 node) { address owner = records[node].owner; require(owner == msg.sender || operators[owner][msg.sender]); _; } /** * @dev Constructs a new ENS registrar. */ constructor() public { records[0x0].owner = msg.sender; } /** * @dev Sets the record for a node. * @param node The node to update. * @param owner The address of the new owner. * @param resolver The address of the resolver. * @param ttl The TTL in seconds. */ function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external { setOwner(node, owner); _setResolverAndTTL(node, resolver, ttl); } /** * @dev Sets the record for a subnode. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. * @param resolver The address of the resolver. * @param ttl The TTL in seconds. */ function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external { bytes32 subnode = setSubnodeOwner(node, label, owner); _setResolverAndTTL(subnode, resolver, ttl); } /** * @dev Transfers ownership of a node to a new address. May only be called by the current owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) public authorised(node) { _setOwner(node, owner); emit Transfer(node, owner); } /** * @dev Transfers ownership of a subnode keccak256(node, label) to a new address. May only be called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public authorised(node) returns(bytes32) { bytes32 subnode = keccak256(abi.encodePacked(node, label)); _setOwner(subnode, owner); emit NewOwner(node, label, owner); return subnode; } /** * @dev Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) public authorised(node) { emit NewResolver(node, resolver); records[node].resolver = resolver; } /** * @dev Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) public authorised(node) { emit NewTTL(node, ttl); records[node].ttl = ttl; } /** * @dev Enable or disable approval for a third party ("operator") to manage * all of `msg.sender`'s ENS records. Emits the ApprovalForAll event. * @param operator Address to add to the set of authorized operators. * @param approved True if the operator is approved, false to revoke approval. */ function setApprovalForAll(address operator, bool approved) external { operators[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev Returns the address that owns the specified node. * @param node The specified node. * @return address of the owner. */ function owner(bytes32 node) public view returns (address) { address addr = records[node].owner; if (addr == address(this)) { return address(0x0); } return addr; } /** * @dev Returns the address of the resolver for the specified node. * @param node The specified node. * @return address of the resolver. */ function resolver(bytes32 node) public view returns (address) { return records[node].resolver; } /** * @dev Returns the TTL of a node, and any records associated with it. * @param node The specified node. * @return ttl of the node. */ function ttl(bytes32 node) public view returns (uint64) { return records[node].ttl; } /** * @dev Returns whether a record has been imported to the registry. * @param node The specified node. * @return Bool if record exists */ function recordExists(bytes32 node) public view returns (bool) { return records[node].owner != address(0x0); } /** * @dev Query if an address is an authorized operator for another address. * @param owner The address that owns the records. * @param operator The address that acts on behalf of the owner. * @return True if `operator` is an approved operator for `owner`, false otherwise. */ function isApprovedForAll(address owner, address operator) external view returns (bool) { return operators[owner][operator]; } function _setOwner(bytes32 node, address owner) internal { records[node].owner = owner; } function _setResolverAndTTL(bytes32 node, address resolver, uint64 ttl) internal { if(resolver != records[node].resolver) { records[node].resolver = resolver; emit NewResolver(node, resolver); } if(ttl != records[node].ttl) { records[node].ttl = ttl; emit NewTTL(node, ttl); } } } pragma solidity ^0.5.0; contract ABIResolver is ResolverBase { bytes4 constant private ABI_INTERFACE_ID = 0x2203ab56; event ABIChanged(bytes32 indexed node, uint256 indexed contentType); mapping(bytes32=>mapping(uint256=>bytes)) abis; /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes calldata data) external authorised(node) { // Content types must be powers of 2 require(((contentType - 1) & contentType) == 0); abis[node][contentType] = data; emit ABIChanged(node, contentType); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) { mapping(uint256=>bytes) storage abiset = abis[node]; for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) { return (contentType, abiset[contentType]); } } return (0, bytes("")); } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == ABI_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract AddrResolver is ResolverBase { bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant private ADDRESS_INTERFACE_ID = 0xf1cb7e06; uint constant private COIN_TYPE_ETH = 60; event AddrChanged(bytes32 indexed node, address a); event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); mapping(bytes32=>mapping(uint=>bytes)) _addresses; /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param a The address to set. */ function setAddr(bytes32 node, address a) external authorised(node) { setAddr(node, COIN_TYPE_ETH, addressToBytes(a)); } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public view returns (address payable) { bytes memory a = addr(node, COIN_TYPE_ETH); if(a.length == 0) { return address(0); } return bytesToAddress(a); } function setAddr(bytes32 node, uint coinType, bytes memory a) public authorised(node) { emit AddressChanged(node, coinType, a); if(coinType == COIN_TYPE_ETH) { emit AddrChanged(node, bytesToAddress(a)); } _addresses[node][coinType] = a; } function addr(bytes32 node, uint coinType) public view returns(bytes memory) { return _addresses[node][coinType]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == ADDRESS_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract ContentHashResolver is ResolverBase { bytes4 constant private CONTENT_HASH_INTERFACE_ID = 0xbc1c58d1; event ContenthashChanged(bytes32 indexed node, bytes hash); mapping(bytes32=>bytes) hashes; /** * Sets the contenthash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param hash The contenthash to set */ function setContenthash(bytes32 node, bytes calldata hash) external authorised(node) { hashes[node] = hash; emit ContenthashChanged(node, hash); } /** * Returns the contenthash associated with an ENS node. * @param node The ENS node to query. * @return The associated contenthash. */ function contenthash(bytes32 node) external view returns (bytes memory) { return hashes[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == CONTENT_HASH_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity >0.4.23; library BytesUtils { /* * @dev Returns the keccak-256 hash of a byte range. * @param self The byte string to hash. * @param offset The position to start hashing at. * @param len The number of bytes to hash. * @return The hash of the byte range. */ function keccak(bytes memory self, uint offset, uint len) internal pure returns (bytes32 ret) { require(offset + len <= self.length); assembly { ret := keccak256(add(add(self, 32), offset), len) } } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two bytes are equal. * @param self The first bytes to compare. * @param other The second bytes to compare. * @return The result of the comparison. */ function compare(bytes memory self, bytes memory other) internal pure returns (int) { return compare(self, 0, self.length, other, 0, other.length); } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two bytes are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first bytes to compare. * @param offset The offset of self. * @param len The length of self. * @param other The second bytes to compare. * @param otheroffset The offset of the other string. * @param otherlen The length of the other string. * @return The result of the comparison. */ function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) { uint shortest = len; if (otherlen < len) shortest = otherlen; uint selfptr; uint otherptr; assembly { selfptr := add(self, add(offset, 32)) otherptr := add(other, add(otheroffset, 32)) } for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint mask; if (shortest > 32) { mask = uint256(- 1); // aka 0xffffff.... } else { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(len) - int(otherlen); } /* * @dev Returns true if the two byte ranges are equal. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @param otherOffset The offset into the second byte range. * @param len The number of bytes to compare * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset, uint len) internal pure returns (bool) { return keccak(self, offset, len) == keccak(other, otherOffset, len); } /* * @dev Returns true if the two byte ranges are equal with offsets. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @param otherOffset The offset into the second byte range. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset) internal pure returns (bool) { return keccak(self, offset, self.length - offset) == keccak(other, otherOffset, other.length - otherOffset); } /* * @dev Compares a range of 'self' to all of 'other' and returns True iff * they are equal. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other) internal pure returns (bool) { return self.length >= offset + other.length && equals(self, offset, other, 0, other.length); } /* * @dev Returns true if the two byte ranges are equal. * @param self The first byte range to compare. * @param other The second byte range to compare. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, bytes memory other) internal pure returns(bool) { return self.length == other.length && equals(self, 0, other, 0, self.length); } /* * @dev Returns the 8-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 8 bits of the string, interpreted as an integer. */ function readUint8(bytes memory self, uint idx) internal pure returns (uint8 ret) { return uint8(self[idx]); } /* * @dev Returns the 16-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 16 bits of the string, interpreted as an integer. */ function readUint16(bytes memory self, uint idx) internal pure returns (uint16 ret) { require(idx + 2 <= self.length); assembly { ret := and(mload(add(add(self, 2), idx)), 0xFFFF) } } /* * @dev Returns the 32-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bits of the string, interpreted as an integer. */ function readUint32(bytes memory self, uint idx) internal pure returns (uint32 ret) { require(idx + 4 <= self.length); assembly { ret := and(mload(add(add(self, 4), idx)), 0xFFFFFFFF) } } /* * @dev Returns the 32 byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bytes of the string. */ function readBytes32(bytes memory self, uint idx) internal pure returns (bytes32 ret) { require(idx + 32 <= self.length); assembly { ret := mload(add(add(self, 32), idx)) } } /* * @dev Returns the 32 byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bytes of the string. */ function readBytes20(bytes memory self, uint idx) internal pure returns (bytes20 ret) { require(idx + 20 <= self.length); assembly { ret := and(mload(add(add(self, 32), idx)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000) } } /* * @dev Returns the n byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes. * @param len The number of bytes. * @return The specified 32 bytes of the string. */ function readBytesN(bytes memory self, uint idx, uint len) internal pure returns (bytes32 ret) { require(len <= 32); require(idx + len <= self.length); assembly { let mask := not(sub(exp(256, sub(32, len)), 1)) ret := and(mload(add(add(self, 32), idx)), mask) } } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Copies a substring into a new byte string. * @param self The byte string to copy from. * @param offset The offset to start copying at. * @param len The number of bytes to copy. */ function substring(bytes memory self, uint offset, uint len) internal pure returns(bytes memory) { require(offset + len <= self.length); bytes memory ret = new bytes(len); uint dest; uint src; assembly { dest := add(ret, 32) src := add(add(self, 32), offset) } memcpy(dest, src, len); return ret; } // Maps characters from 0x30 to 0x7A to their base32 values. // 0xFF represents invalid characters in that range. bytes constant base32HexTable = hex'00010203040506070809FFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1FFFFFFFFFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1F'; /** * @dev Decodes unpadded base32 data of up to one word in length. * @param self The data to decode. * @param off Offset into the string to start at. * @param len Number of characters to decode. * @return The decoded data, left aligned. */ function base32HexDecodeWord(bytes memory self, uint off, uint len) internal pure returns(bytes32) { require(len <= 52); uint ret = 0; uint8 decoded; for(uint i = 0; i < len; i++) { bytes1 char = self[off + i]; require(char >= 0x30 && char <= 0x7A); decoded = uint8(base32HexTable[uint(uint8(char)) - 0x30]); require(decoded <= 0x20); if(i == len - 1) { break; } ret = (ret << 5) | decoded; } uint bitlen = len * 5; if(len % 8 == 0) { // Multiple of 8 characters, no padding ret = (ret << 5) | decoded; } else if(len % 8 == 2) { // Two extra characters - 1 byte ret = (ret << 3) | (decoded >> 2); bitlen -= 2; } else if(len % 8 == 4) { // Four extra characters - 2 bytes ret = (ret << 1) | (decoded >> 4); bitlen -= 4; } else if(len % 8 == 5) { // Five extra characters - 3 bytes ret = (ret << 4) | (decoded >> 1); bitlen -= 1; } else if(len % 8 == 7) { // Seven extra characters - 4 bytes ret = (ret << 2) | (decoded >> 3); bitlen -= 3; } else { revert(); } return bytes32(ret << (256 - bitlen)); } } pragma solidity >0.4.18; /** * @dev A library for working with mutable byte buffers in Solidity. * * Byte buffers are mutable and expandable, and provide a variety of primitives * for writing to them. At any time you can fetch a bytes object containing the * current contents of the buffer. The bytes object should not be stored between * operations, as it may change due to resizing of the buffer. */ library Buffer { /** * @dev Represents a mutable buffer. Buffers have a current value (buf) and * a capacity. The capacity may be longer than the current value, in * which case it can be extended without the need to allocate more memory. */ struct buffer { bytes buf; uint capacity; } /** * @dev Initializes a buffer with an initial capacity. * @param buf The buffer to initialize. * @param capacity The number of bytes of space to allocate the buffer. * @return The buffer, for chaining. */ function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) { if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(32, add(ptr, capacity))) } return buf; } /** * @dev Initializes a new buffer from an existing bytes object. * Changes to the buffer may mutate the original value. * @param b The bytes object to initialize the buffer with. * @return A new buffer. */ function fromBytes(bytes memory b) internal pure returns(buffer memory) { buffer memory buf; buf.buf = b; buf.capacity = b.length; return buf; } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if (a > b) { return a; } return b; } /** * @dev Sets buffer length to 0. * @param buf The buffer to truncate. * @return The original buffer, for chaining.. */ function truncate(buffer memory buf) internal pure returns (buffer memory) { assembly { let bufptr := mload(buf) mstore(bufptr, 0) } return buf; } /** * @dev Writes a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The start offset to write to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) { require(len <= data.length); if (off + len > buf.capacity) { resize(buf, max(buf.capacity, len + off) * 2); } uint dest; uint src; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + offset + sizeof(buffer length) dest := add(add(bufptr, 32), off) // Update buffer length if we're extending it if gt(add(len, off), buflen) { mstore(bufptr, add(len, off)) } src := add(data, 32) } // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, len); } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, data.length); } /** * @dev Writes a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write the byte at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) { if (off >= buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + sizeof(buffer length) + off let dest := add(add(bufptr, off), 32) mstore8(dest, data) // Update buffer length if we extended it if eq(off, buflen) { mstore(bufptr, add(buflen, 1)) } } return buf; } /** * @dev Appends a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) { return writeUint8(buf, buf.buf.length, data); } /** * @dev Writes up to 32 bytes to the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (left-aligned). * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; // Right-align data data = data >> (8 * (32 - len)); assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + sizeof(buffer length) + off + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) { return write(buf, off, bytes32(data), 20); } /** * @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chhaining. */ function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, bytes32(data), 20); } /** * @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, 32); } /** * @dev Writes an integer to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (right-aligned). * @return The original buffer, for chaining. */ function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + off + sizeof(buffer length) + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { return writeInt(buf, buf.buf.length, data, len); } } pragma solidity >0.4.23; /** * @dev RRUtils is a library that provides utilities for parsing DNS resource records. */ library RRUtils { using BytesUtils for *; using Buffer for *; /** * @dev Returns the number of bytes in the DNS name at 'offset' in 'self'. * @param self The byte array to read a name from. * @param offset The offset to start reading at. * @return The length of the DNS name at 'offset', in bytes. */ function nameLength(bytes memory self, uint offset) internal pure returns(uint) { uint idx = offset; while (true) { assert(idx < self.length); uint labelLen = self.readUint8(idx); idx += labelLen + 1; if (labelLen == 0) { break; } } return idx - offset; } /** * @dev Returns a DNS format name at the specified offset of self. * @param self The byte array to read a name from. * @param offset The offset to start reading at. * @return The name. */ function readName(bytes memory self, uint offset) internal pure returns(bytes memory ret) { uint len = nameLength(self, offset); return self.substring(offset, len); } /** * @dev Returns the number of labels in the DNS name at 'offset' in 'self'. * @param self The byte array to read a name from. * @param offset The offset to start reading at. * @return The number of labels in the DNS name at 'offset', in bytes. */ function labelCount(bytes memory self, uint offset) internal pure returns(uint) { uint count = 0; while (true) { assert(offset < self.length); uint labelLen = self.readUint8(offset); offset += labelLen + 1; if (labelLen == 0) { break; } count += 1; } return count; } /** * @dev An iterator over resource records. */ struct RRIterator { bytes data; uint offset; uint16 dnstype; uint16 class; uint32 ttl; uint rdataOffset; uint nextOffset; } /** * @dev Begins iterating over resource records. * @param self The byte string to read from. * @param offset The offset to start reading at. * @return An iterator object. */ function iterateRRs(bytes memory self, uint offset) internal pure returns (RRIterator memory ret) { ret.data = self; ret.nextOffset = offset; next(ret); } /** * @dev Returns true iff there are more RRs to iterate. * @param iter The iterator to check. * @return True iff the iterator has finished. */ function done(RRIterator memory iter) internal pure returns(bool) { return iter.offset >= iter.data.length; } /** * @dev Moves the iterator to the next resource record. * @param iter The iterator to advance. */ function next(RRIterator memory iter) internal pure { iter.offset = iter.nextOffset; if (iter.offset >= iter.data.length) { return; } // Skip the name uint off = iter.offset + nameLength(iter.data, iter.offset); // Read type, class, and ttl iter.dnstype = iter.data.readUint16(off); off += 2; iter.class = iter.data.readUint16(off); off += 2; iter.ttl = iter.data.readUint32(off); off += 4; // Read the rdata uint rdataLength = iter.data.readUint16(off); off += 2; iter.rdataOffset = off; iter.nextOffset = off + rdataLength; } /** * @dev Returns the name of the current record. * @param iter The iterator. * @return A new bytes object containing the owner name from the RR. */ function name(RRIterator memory iter) internal pure returns(bytes memory) { return iter.data.substring(iter.offset, nameLength(iter.data, iter.offset)); } /** * @dev Returns the rdata portion of the current record. * @param iter The iterator. * @return A new bytes object containing the RR's RDATA. */ function rdata(RRIterator memory iter) internal pure returns(bytes memory) { return iter.data.substring(iter.rdataOffset, iter.nextOffset - iter.rdataOffset); } /** * @dev Checks if a given RR type exists in a type bitmap. * @param self The byte string to read the type bitmap from. * @param offset The offset to start reading at. * @param rrtype The RR type to check for. * @return True if the type is found in the bitmap, false otherwise. */ function checkTypeBitmap(bytes memory self, uint offset, uint16 rrtype) internal pure returns (bool) { uint8 typeWindow = uint8(rrtype >> 8); uint8 windowByte = uint8((rrtype & 0xff) / 8); uint8 windowBitmask = uint8(uint8(1) << (uint8(7) - uint8(rrtype & 0x7))); for (uint off = offset; off < self.length;) { uint8 window = self.readUint8(off); uint8 len = self.readUint8(off + 1); if (typeWindow < window) { // We've gone past our window; it's not here. return false; } else if (typeWindow == window) { // Check this type bitmap if (len * 8 <= windowByte) { // Our type is past the end of the bitmap return false; } return (self.readUint8(off + windowByte + 2) & windowBitmask) != 0; } else { // Skip this type bitmap off += len + 2; } } return false; } function compareNames(bytes memory self, bytes memory other) internal pure returns (int) { if (self.equals(other)) { return 0; } uint off; uint otheroff; uint prevoff; uint otherprevoff; uint counts = labelCount(self, 0); uint othercounts = labelCount(other, 0); // Keep removing labels from the front of the name until both names are equal length while (counts > othercounts) { prevoff = off; off = progress(self, off); counts--; } while (othercounts > counts) { otherprevoff = otheroff; otheroff = progress(other, otheroff); othercounts--; } // Compare the last nonequal labels to each other while (counts > 0 && !self.equals(off, other, otheroff)) { prevoff = off; off = progress(self, off); otherprevoff = otheroff; otheroff = progress(other, otheroff); counts -= 1; } if (off == 0) { return -1; } if(otheroff == 0) { return 1; } return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff)); } function progress(bytes memory body, uint off) internal pure returns(uint) { return off + 1 + body.readUint8(off); } } pragma solidity ^0.5.0; contract DNSResolver is ResolverBase { using RRUtils for *; using BytesUtils for bytes; bytes4 constant private DNS_RECORD_INTERFACE_ID = 0xa8fa5682; bytes4 constant private DNS_ZONE_INTERFACE_ID = 0x5c47637c; // DNSRecordChanged is emitted whenever a given node/name/resource's RRSET is updated. event DNSRecordChanged(bytes32 indexed node, bytes name, uint16 resource, bytes record); // DNSRecordDeleted is emitted whenever a given node/name/resource's RRSET is deleted. event DNSRecordDeleted(bytes32 indexed node, bytes name, uint16 resource); // DNSZoneCleared is emitted whenever a given node's zone information is cleared. event DNSZoneCleared(bytes32 indexed node); // DNSZonehashChanged is emitted whenever a given node's zone hash is updated. event DNSZonehashChanged(bytes32 indexed node, bytes lastzonehash, bytes zonehash); // Zone hashes for the domains. // A zone hash is an EIP-1577 content hash in binary format that should point to a // resource containing a single zonefile. // node => contenthash mapping(bytes32=>bytes) private zonehashes; // Version the mapping for each zone. This allows users who have lost // track of their entries to effectively delete an entire zone by bumping // the version number. // node => version mapping(bytes32=>uint256) private versions; // The records themselves. Stored as binary RRSETs // node => version => name => resource => data mapping(bytes32=>mapping(uint256=>mapping(bytes32=>mapping(uint16=>bytes)))) private records; // Count of number of entries for a given name. Required for DNS resolvers // when resolving wildcards. // node => version => name => number of records mapping(bytes32=>mapping(uint256=>mapping(bytes32=>uint16))) private nameEntriesCount; /** * Set one or more DNS records. Records are supplied in wire-format. * Records with the same node/name/resource must be supplied one after the * other to ensure the data is updated correctly. For example, if the data * was supplied: * a.example.com IN A 1.2.3.4 * a.example.com IN A 5.6.7.8 * www.example.com IN CNAME a.example.com. * then this would store the two A records for a.example.com correctly as a * single RRSET, however if the data was supplied: * a.example.com IN A 1.2.3.4 * www.example.com IN CNAME a.example.com. * a.example.com IN A 5.6.7.8 * then this would store the first A record, the CNAME, then the second A * record which would overwrite the first. * * @param node the namehash of the node for which to set the records * @param data the DNS wire format records to set */ function setDNSRecords(bytes32 node, bytes calldata data) external authorised(node) { uint16 resource = 0; uint256 offset = 0; bytes memory name; bytes memory value; bytes32 nameHash; // Iterate over the data to add the resource records for (RRUtils.RRIterator memory iter = data.iterateRRs(0); !iter.done(); iter.next()) { if (resource == 0) { resource = iter.dnstype; name = iter.name(); nameHash = keccak256(abi.encodePacked(name)); value = bytes(iter.rdata()); } else { bytes memory newName = iter.name(); if (resource != iter.dnstype || !name.equals(newName)) { setDNSRRSet(node, name, resource, data, offset, iter.offset - offset, value.length == 0); resource = iter.dnstype; offset = iter.offset; name = newName; nameHash = keccak256(name); value = bytes(iter.rdata()); } } } if (name.length > 0) { setDNSRRSet(node, name, resource, data, offset, data.length - offset, value.length == 0); } } /** * Obtain a DNS record. * @param node the namehash of the node for which to fetch the record * @param name the keccak-256 hash of the fully-qualified name for which to fetch the record * @param resource the ID of the resource as per https://en.wikipedia.org/wiki/List_of_DNS_record_types * @return the DNS record in wire format if present, otherwise empty */ function dnsRecord(bytes32 node, bytes32 name, uint16 resource) public view returns (bytes memory) { return records[node][versions[node]][name][resource]; } /** * Check if a given node has records. * @param node the namehash of the node for which to check the records * @param name the namehash of the node for which to check the records */ function hasDNSRecords(bytes32 node, bytes32 name) public view returns (bool) { return (nameEntriesCount[node][versions[node]][name] != 0); } /** * Clear all information for a DNS zone. * @param node the namehash of the node for which to clear the zone */ function clearDNSZone(bytes32 node) public authorised(node) { versions[node]++; emit DNSZoneCleared(node); } /** * setZonehash sets the hash for the zone. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param hash The zonehash to set */ function setZonehash(bytes32 node, bytes calldata hash) external authorised(node) { bytes memory oldhash = zonehashes[node]; zonehashes[node] = hash; emit DNSZonehashChanged(node, oldhash, hash); } /** * zonehash obtains the hash for the zone. * @param node The ENS node to query. * @return The associated contenthash. */ function zonehash(bytes32 node) external view returns (bytes memory) { return zonehashes[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == DNS_RECORD_INTERFACE_ID || interfaceID == DNS_ZONE_INTERFACE_ID || super.supportsInterface(interfaceID); } function setDNSRRSet( bytes32 node, bytes memory name, uint16 resource, bytes memory data, uint256 offset, uint256 size, bool deleteRecord) private { uint256 version = versions[node]; bytes32 nameHash = keccak256(name); bytes memory rrData = data.substring(offset, size); if (deleteRecord) { if (records[node][version][nameHash][resource].length != 0) { nameEntriesCount[node][version][nameHash]--; } delete(records[node][version][nameHash][resource]); emit DNSRecordDeleted(node, name, resource); } else { if (records[node][version][nameHash][resource].length == 0) { nameEntriesCount[node][version][nameHash]++; } records[node][version][nameHash][resource] = rrData; emit DNSRecordChanged(node, name, resource, rrData); } } } pragma solidity ^0.5.0; contract InterfaceResolver is ResolverBase, AddrResolver { bytes4 constant private INTERFACE_INTERFACE_ID = bytes4(keccak256("interfaceImplementer(bytes32,bytes4)")); bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7; event InterfaceChanged(bytes32 indexed node, bytes4 indexed interfaceID, address implementer); mapping(bytes32=>mapping(bytes4=>address)) interfaces; /** * Sets an interface associated with a name. * Setting the address to 0 restores the default behaviour of querying the contract at `addr()` for interface support. * @param node The node to update. * @param interfaceID The EIP 165 interface ID. * @param implementer The address of a contract that implements this interface for this node. */ function setInterface(bytes32 node, bytes4 interfaceID, address implementer) external authorised(node) { interfaces[node][interfaceID] = implementer; emit InterfaceChanged(node, interfaceID, implementer); } /** * Returns the address of a contract that implements the specified interface for this name. * If an implementer has not been set for this interfaceID and name, the resolver will query * the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that * contract implements EIP165 and returns `true` for the specified interfaceID, its address * will be returned. * @param node The ENS node to query. * @param interfaceID The EIP 165 interface ID to check for. * @return The address that implements this interface, or 0 if the interface is unsupported. */ function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) { address implementer = interfaces[node][interfaceID]; if(implementer != address(0)) { return implementer; } address a = addr(node); if(a == address(0)) { return address(0); } (bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", INTERFACE_META_ID)); if(!success || returnData.length < 32 || returnData[31] == 0) { // EIP 165 not supported by target return address(0); } (success, returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", interfaceID)); if(!success || returnData.length < 32 || returnData[31] == 0) { // Specified interface not supported by target return address(0); } return a; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == INTERFACE_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract NameResolver is ResolverBase { bytes4 constant private NAME_INTERFACE_ID = 0x691f3431; event NameChanged(bytes32 indexed node, string name); mapping(bytes32=>string) names; /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string calldata name) external authorised(node) { names[node] = name; emit NameChanged(node, name); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) external view returns (string memory) { return names[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == NAME_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract PubkeyResolver is ResolverBase { bytes4 constant private PUBKEY_INTERFACE_ID = 0xc8690233; event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); struct PublicKey { bytes32 x; bytes32 y; } mapping(bytes32=>PublicKey) pubkeys; /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) external authorised(node) { pubkeys[node] = PublicKey(x, y); emit PubkeyChanged(node, x, y); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y) { return (pubkeys[node].x, pubkeys[node].y); } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == PUBKEY_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract TextResolver is ResolverBase { bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c; event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); mapping(bytes32=>mapping(string=>string)) texts; /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string calldata key, string calldata value) external authorised(node) { texts[node][key] = value; emit TextChanged(node, key, key); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string calldata key) external view returns (string memory) { return texts[node][key]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == TEXT_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver is ABIResolver, AddrResolver, ContentHashResolver, DNSResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver { ENS ens; /** * A mapping of authorisations. An address that is authorised for a name * may make any changes to the name that the owner could, but may not update * the set of authorisations. * (node, owner, caller) => isAuthorised */ mapping(bytes32=>mapping(address=>mapping(address=>bool))) public authorisations; event AuthorisationChanged(bytes32 indexed node, address indexed owner, address indexed target, bool isAuthorised); constructor(ENS _ens) public { ens = _ens; } /** * @dev Sets or clears an authorisation. * Authorisations are specific to the caller. Any account can set an authorisation * for any name, but the authorisation that is checked will be that of the * current owner of a name. Thus, transferring a name effectively clears any * existing authorisations, and new authorisations can be set in advance of * an ownership transfer if desired. * * @param node The name to change the authorisation on. * @param target The address that is to be authorised or deauthorised. * @param isAuthorised True if the address should be authorised, or false if it should be deauthorised. */ function setAuthorisation(bytes32 node, address target, bool isAuthorised) external { authorisations[node][msg.sender][target] = isAuthorised; emit AuthorisationChanged(node, msg.sender, target, isAuthorised); } function isAuthorised(bytes32 node) internal view returns(bool) { address owner = ens.owner(node); return owner == msg.sender || authorisations[node][owner][msg.sender]; } }
Obtain a DNS record. node the namehash of the node for which to fetch the record name the keccak-256 hash of the fully-qualified name for which to fetch the record return the DNS record in wire format if present, otherwise empty/
function dnsRecord(bytes32 node, bytes32 name, uint16 resource) public view returns (bytes memory) { return records[node][versions[node]][name][resource]; }
15,583
./full_match/5/0xe20F8D937A6Ce8EA0500D7975e0ba497a13df32D/sources/republic.sol
Sets the data for a specific token. token The address of the token. tokenType The type of the token (ERC721 or ERC1155). isAllowed Whether the token is allowed to be burnt.
function setTokenData(address token, TokenType tokenType, bool isAllowed) public onlyOwner { tokenData[token] = TokenData(tokenType, isAllowed); }
7,069,914
// Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts // // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../dependencies/open-zeppelin/SafeERC20.sol'; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SM1Admin } from '../v1_1/impl/SM1Admin.sol'; import { SM1Getters } from '../v1_1/impl/SM1Getters.sol'; import { SM1Operators } from '../v1_1/impl/SM1Operators.sol'; import { SM1Slashing } from '../v1_1/impl/SM1Slashing.sol'; import { SM1Staking } from '../v1_1/impl/SM1Staking.sol'; /** * @title SafetyModuleV2 * @author dYdX * * @notice Contract for staking tokens, which may be slashed by the permissioned slasher. * * NOTE: Most functions will revert if epoch zero has not started. */ contract SafetyModuleV2 is SM1Slashing, SM1Operators, SM1Admin, SM1Getters { using SafeERC20 for IERC20; // ============ Constants ============ string public constant EIP712_DOMAIN_NAME = 'dYdX Safety Module'; string public constant EIP712_DOMAIN_VERSION = '1'; bytes32 public constant EIP712_DOMAIN_SCHEMA_HASH = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1Staking(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ /** * @notice Initializer for v2, intended to fix the deployment bug that affected v1. * * Responsible for the following: * * 1. Funds recovery and staker compensation: * - Transfer all Safety Module DYDX to the recovery contract. * - Transfer compensation amount from the rewards treasury to the recovery contract. * * 2. Storage recovery and cleanup: * - Set the _EXCHANGE_RATE_ to EXCHANGE_RATE_BASE. * - Clean up invalid storage values at slots 115 and 125. * * @param recoveryContract The address of the contract which will distribute * recovered funds to stakers. * @param recoveryCompensationAmount Amount to transfer out of the rewards treasury, for staker * compensation, on top of the return of staked funds. */ function initialize( address recoveryContract, uint256 recoveryCompensationAmount ) external initializer { // Funds recovery and staker compensation. uint256 balance = STAKED_TOKEN.balanceOf(address(this)); STAKED_TOKEN.safeTransfer(recoveryContract, balance); REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recoveryContract, recoveryCompensationAmount); // Storage recovery and cleanup. __SM1ExchangeRate_init(); // solhint-disable-next-line no-inline-assembly assembly { sstore(115, 0) sstore(125, 0) } } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 2; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SafeMath } from './SafeMath.sol'; import { Address } from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1Admin * @author dYdX * * @dev Admin-only functions. */ abstract contract SM1Admin is SM1StakedBalances, SM1Roles { using SafeMath for uint256; // ============ External Functions ============ /** * @notice Set the parameters defining the function from timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Reverts if epoch zero already started, and the new parameters would change the current epoch. * Reverts if epoch zero has not started, but would have had started under the new parameters. * * @param interval The length `a` of an epoch, in seconds. * @param offset The offset `b`, i.e. the start of epoch zero, in seconds. */ function setEpochParameters( uint256 interval, uint256 offset ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { if (!hasEpochZeroStarted()) { require( block.timestamp < offset, 'SM1Admin: Started epoch zero' ); _setEpochParameters(interval, offset); return; } // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the epoch formula. _settleTotalActiveBalance(); // Update the epoch parameters. Require that the current epoch number is unchanged. uint256 originalCurrentEpoch = getCurrentEpoch(); _setEpochParameters(interval, offset); uint256 newCurrentEpoch = getCurrentEpoch(); require( originalCurrentEpoch == newCurrentEpoch, 'SM1Admin: Changed epochs' ); } /** * @notice Set the blackout window, during which one cannot request withdrawals of staked funds. */ function setBlackoutWindow( uint256 blackoutWindow ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { _setBlackoutWindow(blackoutWindow); } /** * @notice Set the emission rate of rewards. * * @param emissionPerSecond The new number of rewards tokens given out per second. */ function setRewardsPerSecond( uint256 emissionPerSecond ) external onlyRole(REWARDS_RATE_ROLE) nonReentrant { uint256 totalStaked = 0; if (hasEpochZeroStarted()) { // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the emission rate. totalStaked = _settleTotalActiveBalance(); } _setRewardsPerSecond(emissionPerSecond, totalStaked); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Getters * @author dYdX * * @dev Some external getter functions. */ abstract contract SM1Getters is SM1Storage { using SafeMath for uint256; // ============ External Functions ============ /** * @notice The parameters specifying the function from timestamp to epoch number. * * @return The parameters struct with `interval` and `offset` fields. */ function getEpochParameters() external view returns (SM1Types.EpochParameters memory) { return _EPOCH_PARAMETERS_; } /** * @notice The period of time at the end of each epoch in which withdrawals cannot be requested. * * @return The blackout window duration, in seconds. */ function getBlackoutWindow() external view returns (uint256) { return _BLACKOUT_WINDOW_; } /** * @notice Get the domain separator used for EIP-712 signatures. * * @return The EIP-712 domain separator. */ function getDomainSeparator() external view returns (bytes32) { return _DOMAIN_SEPARATOR_; } /** * @notice The value of one underlying token, in the units used for staked balances, denominated * as a mutiple of EXCHANGE_RATE_BASE for additional precision. * * To convert from an underlying amount to a staked amount, multiply by the exchange rate. * * @return The exchange rate. */ function getExchangeRate() external view returns (uint256) { return _EXCHANGE_RATE_; } /** * @notice Get an exchange rate snapshot. * * @param index The index number of the exchange rate snapshot. * * @return The snapshot struct with `blockNumber` and `value` fields. */ function getExchangeRateSnapshot( uint256 index ) external view returns (SM1Types.Snapshot memory) { return _EXCHANGE_RATE_SNAPSHOTS_[index]; } /** * @notice Get the number of exchange rate snapshots. * * @return The number of snapshots that have been taken of the exchange rate. */ function getExchangeRateSnapshotCount() external view returns (uint256) { return _EXCHANGE_RATE_SNAPSHOT_COUNT_; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1Staking } from './SM1Staking.sol'; /** * @title SM1Operators * @author dYdX * * @dev Actions which may be called by authorized operators, nominated by the contract owner. * * There are two types of operators. These should be smart contracts, which can be used to * provide additional functionality to users: * * STAKE_OPERATOR_ROLE: * * This operator is allowed to request withdrawals and withdraw funds on behalf of stakers. This * role could be used by a smart contract to provide a staking interface with additional * features, for example, optional lock-up periods that pay out additional rewards (from a * separate rewards pool). * * CLAIM_OPERATOR_ROLE: * * This operator is allowed to claim rewards on behalf of stakers. This role could be used by a * smart contract to provide an interface for claiming rewards from multiple incentive programs * at once. */ abstract contract SM1Operators is SM1Staking, SM1Roles { using SafeMath for uint256; // ============ Events ============ event OperatorStakedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrawalRequestedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrewStakeFor( address indexed staker, address recipient, uint256 amount, address operator ); event OperatorClaimedRewardsFor( address indexed staker, address recipient, uint256 claimedRewards, address operator ); // ============ External Functions ============ /** * @notice Request a withdrawal on behalf of a staker. * * Reverts if we are currently in the blackout window. * * @param staker The staker whose stake to request a withdrawal for. * @param stakeAmount The amount of stake to move from the active to the inactive balance. */ function requestWithdrawalFor( address staker, uint256 stakeAmount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _requestWithdrawal(staker, stakeAmount); emit OperatorWithdrawalRequestedFor(staker, stakeAmount, msg.sender); } /** * @notice Withdraw a staker's stake, and send to the specified recipient. * * @param staker The staker whose stake to withdraw. * @param recipient The address that should receive the funds. * @param stakeAmount The amount of stake to withdraw from the staker's inactive balance. */ function withdrawStakeFor( address staker, address recipient, uint256 stakeAmount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _withdrawStake(staker, recipient, stakeAmount); emit OperatorWithdrewStakeFor(staker, recipient, stakeAmount, msg.sender); } /** * @notice Claim rewards on behalf of a staker, and send them to the specified recipient. * * @param staker The staker whose rewards to claim. * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewardsFor( address staker, address recipient ) external onlyRole(CLAIM_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 rewards = _settleAndClaimRewards(staker, recipient); // Emits an event internally. emit OperatorClaimedRewardsFor(staker, recipient, rewards, msg.sender); return rewards; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1Staking } from './SM1Staking.sol'; /** * @title SM1Slashing * @author dYdX * * @dev Provides the slashing function for removing funds from the contract. * * SLASHING: * * All funds in the contract, active or inactive, are slashable. Slashes are recorded by updating * the exchange rate, and to simplify the technical implementation, we disallow full slashes. * To reduce the possibility of overflow in the exchange rate, we place an upper bound on the * fraction of funds that may be slashed in a single slash. * * Warning: Slashing is not possible if the slash would cause the exchange rate to overflow. * * REWARDS AND GOVERNANCE POWER ACCOUNTING: * * Since all slashes are accounted for by a global exchange rate, slashes do not require any * update to staked balances. The earning of rewards is unaffected by slashes. * * Governance power takes slashes into account by using snapshots of the exchange rate inside * the getPowerAtBlock() function. Note that getPowerAtBlock() returns the governance power as of * the end of the specified block. */ abstract contract SM1Slashing is SM1Staking, SM1Roles { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice The maximum fraction of funds that may be slashed in a single slash (numerator). uint256 public constant MAX_SLASH_NUMERATOR = 95; /// @notice The maximum fraction of funds that may be slashed in a single slash (denominator). uint256 public constant MAX_SLASH_DENOMINATOR = 100; // ============ Events ============ event Slashed( uint256 amount, address recipient, uint256 newExchangeRate ); // ============ External Functions ============ /** * @notice Slash staked token balances and withdraw those funds to the specified address. * * @param requestedSlashAmount The request slash amount, denominated in the underlying token. * @param recipient The address to receive the slashed tokens. * * @return The amount slashed, denominated in the underlying token. */ function slash( uint256 requestedSlashAmount, address recipient ) external onlyRole(SLASHER_ROLE) nonReentrant returns (uint256) { uint256 underlyingBalance = STAKED_TOKEN.balanceOf(address(this)); if (underlyingBalance == 0) { return 0; } // Get the slash amount and remaining amount. Note that remainingAfterSlash is nonzero. uint256 maxSlashAmount = underlyingBalance.mul(MAX_SLASH_NUMERATOR).div(MAX_SLASH_DENOMINATOR); uint256 slashAmount = Math.min(requestedSlashAmount, maxSlashAmount); uint256 remainingAfterSlash = underlyingBalance.sub(slashAmount); if (slashAmount == 0) { return 0; } // Update the exchange rate. // // Warning: Can revert if the max exchange rate is exceeded. uint256 newExchangeRate = updateExchangeRate(underlyingBalance, remainingAfterSlash); // Transfer the slashed token. STAKED_TOKEN.safeTransfer(recipient, slashAmount); emit Slashed(slashAmount, recipient, newExchangeRate); return slashAmount; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1ERC20 } from './SM1ERC20.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1Staking * @author dYdX * * @dev External functions for stakers. See SM1StakedBalances for details on staker accounting. * * UNDERLYING AND STAKED AMOUNTS: * * We distinguish between underlying amounts and stake amounts. An underlying amount is denoted * in the original units of the token being staked. A stake amount is adjusted by the exchange * rate, which can increase due to slashing. Before any slashes have occurred, the exchange rate * is equal to one. */ abstract contract SM1Staking is SM1StakedBalances, SM1ERC20 { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Staked( address indexed staker, address spender, uint256 underlyingAmount, uint256 stakeAmount ); event WithdrawalRequested( address indexed staker, uint256 stakeAmount ); event WithdrewStake( address indexed staker, address recipient, uint256 underlyingAmount, uint256 stakeAmount ); // ============ Constants ============ IERC20 public immutable STAKED_TOKEN; // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1StakedBalances(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) { STAKED_TOKEN = stakedToken; } // ============ External Functions ============ /** * @notice Deposit and stake funds. These funds are active and start earning rewards immediately. * * @param underlyingAmount The amount of underlying token to stake. */ function stake( uint256 underlyingAmount ) external nonReentrant { _stake(msg.sender, underlyingAmount); } /** * @notice Deposit and stake on behalf of another address. * * @param staker The staker who will receive the stake. * @param underlyingAmount The amount of underlying token to stake. */ function stakeFor( address staker, uint256 underlyingAmount ) external nonReentrant { _stake(staker, underlyingAmount); } /** * @notice Request to withdraw funds. Starting in the next epoch, the funds will be “inactive” * and available for withdrawal. Inactive funds do not earn rewards. * * Reverts if we are currently in the blackout window. * * @param stakeAmount The amount of stake to move from the active to the inactive balance. */ function requestWithdrawal( uint256 stakeAmount ) external nonReentrant { _requestWithdrawal(msg.sender, stakeAmount); } /** * @notice Withdraw the sender's inactive funds, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param stakeAmount The amount of stake to withdraw from the sender's inactive balance. */ function withdrawStake( address recipient, uint256 stakeAmount ) external nonReentrant { _withdrawStake(msg.sender, recipient, stakeAmount); } /** * @notice Withdraw the max available inactive funds, and send to the specified recipient. * * This is less gas-efficient than querying the max via eth_call and calling withdrawStake(). * * @param recipient The address that should receive the funds. * * @return The withdrawn amount. */ function withdrawMaxStake( address recipient ) external nonReentrant returns (uint256) { uint256 stakeAmount = getStakeAvailableToWithdraw(msg.sender); _withdrawStake(msg.sender, recipient, stakeAmount); return stakeAmount; } /** * @notice Settle and claim all rewards, and send them to the specified recipient. * * Call this function with eth_call to query the claimable rewards balance. * * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewards( address recipient ) external nonReentrant returns (uint256) { return _settleAndClaimRewards(msg.sender, recipient); // Emits an event internally. } // ============ Public Functions ============ /** * @notice Get the amount of stake available for a given staker to withdraw. * * @param staker The address whose balance to check. * * @return The staker's stake amount that is inactive and available to withdraw. */ function getStakeAvailableToWithdraw( address staker ) public view returns (uint256) { // Note that the next epoch inactive balance is always at least that of the current epoch. return getInactiveBalanceCurrentEpoch(staker); } // ============ Internal Functions ============ function _stake( address staker, uint256 underlyingAmount ) internal { // Convert using the exchange rate. uint256 stakeAmount = stakeAmountFromUnderlyingAmount(underlyingAmount); // Update staked balances and delegate snapshots. _increaseCurrentAndNextActiveBalance(staker, stakeAmount); _moveDelegatesForTransfer(address(0), staker, stakeAmount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), underlyingAmount); emit Staked(staker, msg.sender, underlyingAmount, stakeAmount); emit Transfer(address(0), msg.sender, stakeAmount); } function _requestWithdrawal( address staker, uint256 stakeAmount ) internal { require( !inBlackoutWindow(), 'SM1Staking: Withdraw requests restricted in the blackout window' ); // Get the staker's requestable amount and revert if there is not enough to request withdrawal. uint256 requestableBalance = getActiveBalanceNextEpoch(staker); require( stakeAmount <= requestableBalance, 'SM1Staking: Withdraw request exceeds next active balance' ); // Move amount from active to inactive in the next epoch. _moveNextBalanceActiveToInactive(staker, stakeAmount); emit WithdrawalRequested(staker, stakeAmount); } function _withdrawStake( address staker, address recipient, uint256 stakeAmount ) internal { // Get staker withdrawable balance and revert if there is not enough to withdraw. uint256 withdrawableBalance = getInactiveBalanceCurrentEpoch(staker); require( stakeAmount <= withdrawableBalance, 'SM1Staking: Withdraw amount exceeds staker inactive balance' ); // Update staked balances and delegate snapshots. _decreaseCurrentAndNextInactiveBalance(staker, stakeAmount); _moveDelegatesForTransfer(staker, address(0), stakeAmount); // Convert using the exchange rate. uint256 underlyingAmount = underlyingAmountFromStakeAmount(stakeAmount); // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, underlyingAmount); emit Transfer(msg.sender, address(0), stakeAmount); emit WithdrewStake(staker, recipient, underlyingAmount, stakeAmount); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; library SM1Types { /** * @dev The parameters used to convert a timestamp to an epoch number. */ struct EpochParameters { uint128 interval; uint128 offset; } /** * @dev Snapshot of a value at a specific block, used to track historical governance power. */ struct Snapshot { uint256 blockNumber; uint256 value; } /** * @dev A balance, possibly with a change scheduled for the next epoch. * * @param currentEpoch The epoch in which the balance was last updated. * @param currentEpochBalance The balance at epoch `currentEpoch`. * @param nextEpochBalance The balance at epoch `currentEpoch + 1`. */ struct StoredBalance { uint16 currentEpoch; uint240 currentEpochBalance; uint240 nextEpochBalance; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Roles * @author dYdX * * @dev Defines roles used in the SafetyModuleV1 contract. The hierarchy of roles and powers * of each role are described below. * * Roles: * * OWNER_ROLE * | -> May add or remove addresses from any of the roles below. * | * +-- SLASHER_ROLE * | -> Can slash staked token balances and withdraw those funds. * | * +-- EPOCH_PARAMETERS_ROLE * | -> May set epoch parameters such as the interval, offset, and blackout window. * | * +-- REWARDS_RATE_ROLE * | -> May set the emission rate of rewards. * | * +-- CLAIM_OPERATOR_ROLE * | -> May claim rewards on behalf of a user. * | * +-- STAKE_OPERATOR_ROLE * -> May manipulate user's staked funds (e.g. perform withdrawals on behalf of a user). */ abstract contract SM1Roles is SM1Storage { bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant SLASHER_ROLE = keccak256('SLASHER_ROLE'); bytes32 public constant EPOCH_PARAMETERS_ROLE = keccak256('EPOCH_PARAMETERS_ROLE'); bytes32 public constant REWARDS_RATE_ROLE = keccak256('REWARDS_RATE_ROLE'); bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE'); bytes32 public constant STAKE_OPERATOR_ROLE = keccak256('STAKE_OPERATOR_ROLE'); function __SM1Roles_init() internal { // Assign roles to the sender. // // The STAKE_OPERATOR_ROLE and CLAIM_OPERATOR_ROLE roles are not initially assigned. // These can be assigned to other smart contracts to provide additional functionality for users. _setupRole(OWNER_ROLE, msg.sender); _setupRole(SLASHER_ROLE, msg.sender); _setupRole(EPOCH_PARAMETERS_ROLE, msg.sender); _setupRole(REWARDS_RATE_ROLE, msg.sender); // Set OWNER_ROLE as the admin of all roles. _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(SLASHER_ROLE, OWNER_ROLE); _setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE); _setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE); _setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Rewards } from './SM1Rewards.sol'; /** * @title SM1StakedBalances * @author dYdX * * @dev Accounting of staked balances. * * NOTE: Functions may revert if epoch zero has not started. * * NOTE: All amounts dealt with in this file are denominated in staked units, which because of the * exchange rate, may not correspond one-to-one with the underlying token. See SM1Staking.sol. * * STAKED BALANCE ACCOUNTING: * * A staked balance is in one of two states: * - active: Earning staking rewards; cannot be withdrawn by staker; may be slashed. * - inactive: Not earning rewards; can be withdrawn by the staker; may be slashed. * * A staker may have a combination of active and inactive balances. The following operations * affect staked balances as follows: * - deposit: Increase active balance. * - request withdrawal: At the end of the current epoch, move some active funds to inactive. * - withdraw: Decrease inactive balance. * - transfer: Move some active funds to another staker. * * To encode the fact that a balance may be scheduled to change at the end of a certain epoch, we * store each balance as a struct of three fields: currentEpoch, currentEpochBalance, and * nextEpochBalance. * * REWARDS ACCOUNTING: * * Active funds earn rewards for the period of time that they remain active. This means, after * requesting a withdrawal of some funds, those funds will continue to earn rewards until the end * of the epoch. For example: * * epoch: n n + 1 n + 2 n + 3 * | | | | * +----------+----------+----------+-----... * ^ t_0: User makes a deposit. * ^ t_1: User requests a withdrawal of all funds. * ^ t_2: The funds change state from active to inactive. * * In the above scenario, the user would earn rewards for the period from t_0 to t_2, varying * with the total staked balance in that period. If the user only request a withdrawal for a part * of their balance, then the remaining balance would continue earning rewards beyond t_2. * * User rewards must be settled via SM1Rewards any time a user's active balance changes. Special * attention is paid to the the epoch boundaries, where funds may have transitioned from active * to inactive. * * SETTLEMENT DETAILS: * * Internally, this module uses the following types of operations on stored balances: * - Load: Loads a balance, while applying settlement logic internally to get the * up-to-date result. Returns settlement results without updating state. * - Store: Stores a balance. * - Load-for-update: Performs a load and applies updates as needed to rewards accounting. * Since this is state-changing, it must be followed by a store operation. * - Settle: Performs load-for-update and store operations. * * This module is responsible for maintaining the following invariants to ensure rewards are * calculated correctly: * - When an active balance is loaded for update, if a rollover occurs from one epoch to the * next, the rewards index must be settled up to the boundary at which the rollover occurs. * - Because the global rewards index is needed to update the user rewards index, the total * active balance must be settled before any staker balances are settled or loaded for update. * - A staker's balance must be settled before their rewards are settled. */ abstract contract SM1StakedBalances is SM1Rewards { using SafeCast for uint256; using SafeMath for uint256; // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1Rewards(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ Public Functions ============ /** * @notice Get the current active balance of a staker. */ function getActiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _ACTIVE_BALANCES_[staker] ); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch active balance of a staker. */ function getActiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _ACTIVE_BALANCES_[staker] ); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total active balance. */ function getTotalActiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _TOTAL_ACTIVE_BALANCE_ ); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total active balance. */ function getTotalActiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _TOTAL_ACTIVE_BALANCE_ ); return uint256(balance.nextEpochBalance); } /** * @notice Get the current inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total inactive balance. */ function getTotalInactiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total inactive balance. */ function getTotalInactiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @notice Get the current transferable balance for a user. The user can * only transfer their balance that is not currently inactive or going to be * inactive in the next epoch. Note that this means the user's transferable funds * are their active balance of the next epoch. * * @param account The account to get the transferable balance of. * * @return The user's transferable balance. */ function getTransferableBalance( address account ) public view returns (uint256) { return getActiveBalanceNextEpoch(account); } // ============ Internal Functions ============ function _increaseCurrentAndNextActiveBalance( address staker, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 oldTotalBalance = _increaseCurrentAndNextBalances(address(0), true, amount); uint256 oldUserBalance = _increaseCurrentAndNextBalances(staker, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(staker, oldUserBalance, oldTotalBalance); } function _moveNextBalanceActiveToInactive( address staker, uint256 amount ) internal { // Decrease the active balance for the next epoch. // Always settle total active balance before settling a staker active balance. _decreaseNextBalance(address(0), true, amount); _decreaseNextBalance(staker, true, amount); // Increase the inactive balance for the next epoch. _increaseNextBalance(address(0), false, amount); _increaseNextBalance(staker, false, amount); // Note that we don't need to settle rewards since the current active balance did not change. } function _transferCurrentAndNextActiveBalance( address sender, address recipient, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Move current and next active balances from sender to recipient. uint256 oldSenderBalance = _decreaseCurrentAndNextBalances(sender, true, amount); uint256 oldRecipientBalance = _increaseCurrentAndNextBalances(recipient, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(sender, oldSenderBalance, totalBalance); _settleUserRewardsUpToNow(recipient, oldRecipientBalance, totalBalance); } function _decreaseCurrentAndNextInactiveBalance( address staker, uint256 amount ) internal { // Decrease the inactive balance for the next epoch. _decreaseCurrentAndNextBalances(address(0), false, amount); _decreaseCurrentAndNextBalances(staker, false, amount); // Note that we don't settle rewards since active balances are not affected. } function _settleTotalActiveBalance() internal returns (uint256) { return _settleBalance(address(0), true); } function _settleAndClaimRewards( address staker, address recipient ) internal returns (uint256) { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Always settle staker active balance before settling staker rewards. uint256 userBalance = _settleBalance(staker, true); // Settle rewards balance since we want to claim the full accrued amount. _settleUserRewardsUpToNow(staker, userBalance, totalBalance); // Claim rewards balance. return _claimRewards(staker, recipient); } // ============ Private Functions ============ /** * @dev Load a balance for update and then store it. */ function _settleBalance( address maybeStaker, bool isActiveBalance ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 currentBalance = uint256(balance.currentEpochBalance); _storeBalance(balancePtr, balance); return currentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.add(amount).toUint240(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying a decrease. */ function _decreaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.sub(amount).toUint240(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240(); _storeBalance(balancePtr, balance); } /** * @dev Settle a balance while applying a decrease. */ function _decreaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240(); _storeBalance(balancePtr, balance); } function _getBalancePtr( address maybeStaker, bool isActiveBalance ) private view returns (SM1Types.StoredBalance storage) { // Active. if (isActiveBalance) { if (maybeStaker != address(0)) { return _ACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_ACTIVE_BALANCE_; } // Inactive. if (maybeStaker != address(0)) { return _INACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_INACTIVE_BALANCE_; } /** * @dev Load a balance for updating. * * IMPORTANT: This function may modify state, and so the balance MUST be stored afterwards. * - For active balances: * - If a rollover occurs, rewards are settled up to the epoch boundary. * * @param balancePtr A storage pointer to the balance. * @param maybeStaker The user address, or address(0) to update total balance. * @param isActiveBalance Whether the balance is an active balance. */ function _loadBalanceForUpdate( SM1Types.StoredBalance storage balancePtr, address maybeStaker, bool isActiveBalance ) private returns (SM1Types.StoredBalance memory) { // Active balance. if (isActiveBalance) { ( SM1Types.StoredBalance memory balance, uint256 beforeRolloverEpoch, uint256 beforeRolloverBalance, bool didRolloverOccur ) = _loadActiveBalance(balancePtr); if (didRolloverOccur) { // Handle the effect of the balance rollover on rewards. We must partially settle the index // up to the epoch boundary where the change in balance occurred. We pass in the balance // from before the boundary. if (maybeStaker == address(0)) { // If it's the total active balance... _settleGlobalIndexUpToEpoch(beforeRolloverBalance, beforeRolloverEpoch); } else { // If it's a user active balance... _settleUserRewardsUpToEpoch(maybeStaker, beforeRolloverBalance, beforeRolloverEpoch); } } return balance; } // Inactive balance. return _loadInactiveBalance(balancePtr); } function _loadActiveBalance( SM1Types.StoredBalance storage balancePtr ) private view returns ( SM1Types.StoredBalance memory, uint256, uint256, bool ) { SM1Types.StoredBalance memory balance = balancePtr; // Return these as they may be needed for rewards settlement. uint256 beforeRolloverEpoch = uint256(balance.currentEpoch); uint256 beforeRolloverBalance = uint256(balance.currentEpochBalance); bool didRolloverOccur = false; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { didRolloverOccur = balance.currentEpochBalance != balance.nextEpochBalance; balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return (balance, beforeRolloverEpoch, beforeRolloverBalance, didRolloverOccur); } function _loadInactiveBalance( SM1Types.StoredBalance storage balancePtr ) private view returns (SM1Types.StoredBalance memory) { SM1Types.StoredBalance memory balance = balancePtr; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return balance; } /** * @dev Store a balance. */ function _storeBalance( SM1Types.StoredBalance storage balancePtr, SM1Types.StoredBalance memory balance ) private { // Note: This should use a single `sstore` when compiler optimizations are enabled. balancePtr.currentEpoch = balance.currentEpoch; balancePtr.currentEpochBalance = balance.currentEpochBalance; balancePtr.nextEpochBalance = balance.nextEpochBalance; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { AccessControlUpgradeable } from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol'; import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol'; import { SM1Types } from '../lib/SM1Types.sol'; /** * @title SM1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contract with storage. */ abstract contract SM1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Epoch Schedule ============ /// @dev The parameters specifying the function from timestamp to epoch number. SM1Types.EpochParameters internal _EPOCH_PARAMETERS_; /// @dev The period of time at the end of each epoch in which withdrawals cannot be requested. uint256 internal _BLACKOUT_WINDOW_; // ============ Staked Token ERC20 ============ /// @dev Allowances for ERC-20 transfers. mapping(address => mapping(address => uint256)) internal _ALLOWANCES_; // ============ Governance Power Delegation ============ /// @dev Domain separator for EIP-712 signatures. bytes32 internal _DOMAIN_SEPARATOR_; /// @dev Mapping from (owner) => (next valid nonce) for EIP-712 signatures. mapping(address => uint256) internal _NONCES_; /// @dev Snapshots and delegates for governance voting power. mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _VOTING_SNAPSHOTS_; mapping(address => uint256) internal _VOTING_SNAPSHOT_COUNTS_; mapping(address => address) internal _VOTING_DELEGATES_; /// @dev Snapshots and delegates for governance proposition power. mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _PROPOSITION_SNAPSHOTS_; mapping(address => uint256) internal _PROPOSITION_SNAPSHOT_COUNTS_; mapping(address => address) internal _PROPOSITION_DELEGATES_; // ============ Rewards Accounting ============ /// @dev The emission rate of rewards. uint256 internal _REWARDS_PER_SECOND_; /// @dev The cumulative rewards earned per staked token. (Shared storage slot.) uint224 internal _GLOBAL_INDEX_; /// @dev The timestamp at which the global index was last updated. (Shared storage slot.) uint32 internal _GLOBAL_INDEX_TIMESTAMP_; /// @dev The value of the global index when the user's staked balance was last updated. mapping(address => uint256) internal _USER_INDEXES_; /// @dev The user's accrued, unclaimed rewards (as of the last update to the user index). mapping(address => uint256) internal _USER_REWARDS_BALANCES_; /// @dev The value of the global index at the end of a given epoch. mapping(uint256 => uint256) internal _EPOCH_INDEXES_; // ============ Staker Accounting ============ /// @dev The active balance by staker. mapping(address => SM1Types.StoredBalance) internal _ACTIVE_BALANCES_; /// @dev The total active balance of stakers. SM1Types.StoredBalance internal _TOTAL_ACTIVE_BALANCE_; /// @dev The inactive balance by staker. mapping(address => SM1Types.StoredBalance) internal _INACTIVE_BALANCES_; /// @dev The total inactive balance of stakers. SM1Types.StoredBalance internal _TOTAL_INACTIVE_BALANCE_; // ============ Exchange Rate ============ /// @dev The value of one underlying token, in the units used for staked balances, denominated /// as a mutiple of EXCHANGE_RATE_BASE for additional precision. uint256 internal _EXCHANGE_RATE_; /// @dev Historical snapshots of the exchange rate, in each block that it has changed. mapping(uint256 => SM1Types.Snapshot) internal _EXCHANGE_RATE_SNAPSHOTS_; /// @dev Number of snapshots of the exchange rate. uint256 internal _EXCHANGE_RATE_SNAPSHOT_COUNT_; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; import './Strings.sol'; import './ERC165.sol'; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( 'AccessControl: account ', Strings.toHexString(uint160(account), 20), ' is missing role ', Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), 'AccessControl: can only renounce roles for self'); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ abstract contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor() internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call'); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = '0123456789abcdef'; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return '0'; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = '0'; buffer[1] = 'x'; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, 'Strings: hex length insufficient'); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './IERC165.sol'; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @dev Methods for downcasting unsigned integers, reverting on overflow. */ library SafeCast { /** * @dev Downcast to a uint16, reverting on overflow. */ function toUint16( uint256 a ) internal pure returns (uint16) { uint16 b = uint16(a); require( uint256(b) == a, 'SafeCast: toUint16 overflow' ); return b; } /** * @dev Downcast to a uint32, reverting on overflow. */ function toUint32( uint256 a ) internal pure returns (uint32) { uint32 b = uint32(a); require( uint256(b) == a, 'SafeCast: toUint32 overflow' ); return b; } /** * @dev Downcast to a uint128, reverting on overflow. */ function toUint128( uint256 a ) internal pure returns (uint128) { uint128 b = uint128(a); require( uint256(b) == a, 'SafeCast: toUint128 overflow' ); return b; } /** * @dev Downcast to a uint224, reverting on overflow. */ function toUint224( uint256 a ) internal pure returns (uint224) { uint224 b = uint224(a); require( uint256(b) == a, 'SafeCast: toUint224 overflow' ); return b; } /** * @dev Downcast to a uint240, reverting on overflow. */ function toUint240( uint256 a ) internal pure returns (uint240) { uint240 b = uint240(a); require( uint256(b) == a, 'SafeCast: toUint240 overflow' ); return b; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1EpochSchedule } from './SM1EpochSchedule.sol'; /** * @title SM1Rewards * @author dYdX * * @dev Manages the distribution of token rewards. * * Rewards are distributed continuously. After each second, an account earns rewards `r` according * to the following formula: * * r = R * s / S * * Where: * - `R` is the rewards distributed globally each second, also called the “emission rate.” * - `s` is the account's staked balance in that second (technically, it is measured at the * end of the second) * - `S` is the sum total of all staked balances in that second (again, measured at the end of * the second) * * The parameter `R` can be configured by the contract owner. For every second that elapses, * exactly `R` tokens will accrue to users, save for rounding errors, and with the exception that * while the total staked balance is zero, no tokens will accrue to anyone. * * The accounting works as follows: A global index is stored which represents the cumulative * number of rewards tokens earned per staked token since the start of the distribution. * The value of this index increases over time, and there are two factors affecting the rate of * increase: * 1) The emission rate (in the numerator) * 2) The total number of staked tokens (in the denominator) * * Whenever either factor changes, in some timestamp T, we settle the global index up to T by * calculating the increase in the index since the last update using the OLD values of the factors: * * indexDelta = timeDelta * emissionPerSecond * INDEX_BASE / totalStaked * * Where `INDEX_BASE` is a scaling factor used to allow more precision in the storage of the index. * * For each user we store an accrued rewards balance, as well as a user index, which is a cache of * the global index at the time that the user's accrued rewards balance was last updated. Then at * any point in time, a user's claimable rewards are represented by the following: * * rewards = _USER_REWARDS_BALANCES_[user] + userStaked * ( * settledGlobalIndex - _USER_INDEXES_[user] * ) / INDEX_BASE */ abstract contract SM1Rewards is SM1EpochSchedule { using SafeCast for uint256; using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @dev Additional precision used to represent the global and user index values. uint256 private constant INDEX_BASE = 10**18; /// @notice The rewards token. IERC20 public immutable REWARDS_TOKEN; /// @notice Address to pull rewards from. Must have provided an allowance to this contract. address public immutable REWARDS_TREASURY; /// @notice Start timestamp (inclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_START; /// @notice End timestamp (exclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_END; // ============ Events ============ event RewardsPerSecondUpdated( uint256 emissionPerSecond ); event GlobalIndexUpdated( uint256 index ); event UserIndexUpdated( address indexed user, uint256 index, uint256 unclaimedRewards ); event ClaimedRewards( address indexed user, address recipient, uint256 claimedRewards ); // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) { require( distributionEnd >= distributionStart, 'SM1Rewards: Invalid parameters' ); REWARDS_TOKEN = rewardsToken; REWARDS_TREASURY = rewardsTreasury; DISTRIBUTION_START = distributionStart; DISTRIBUTION_END = distributionEnd; } // ============ External Functions ============ /** * @notice The current emission rate of rewards. * * @return The number of rewards tokens issued globally each second. */ function getRewardsPerSecond() external view returns (uint256) { return _REWARDS_PER_SECOND_; } // ============ Internal Functions ============ /** * @dev Initialize the contract. */ function __SM1Rewards_init() internal { _GLOBAL_INDEX_TIMESTAMP_ = Math.max(block.timestamp, DISTRIBUTION_START).toUint32(); } /** * @dev Set the emission rate of rewards. * * IMPORTANT: Do not call this function without settling the total staked balance first, to * ensure that the index is settled up to the epoch boundaries. * * @param emissionPerSecond The new number of rewards tokens to give out each second. * @param totalStaked The total staked balance. */ function _setRewardsPerSecond( uint256 emissionPerSecond, uint256 totalStaked ) internal { _settleGlobalIndexUpToNow(totalStaked); _REWARDS_PER_SECOND_ = emissionPerSecond; emit RewardsPerSecondUpdated(emissionPerSecond); } /** * @dev Claim tokens, sending them to the specified recipient. * * Note: In order to claim all accrued rewards, the total and user staked balances must first be * settled before calling this function. * * @param user The user's address. * @param recipient The address to send rewards to. * * @return The number of rewards tokens claimed. */ function _claimRewards( address user, address recipient ) internal returns (uint256) { uint256 accruedRewards = _USER_REWARDS_BALANCES_[user]; _USER_REWARDS_BALANCES_[user] = 0; REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recipient, accruedRewards); emit ClaimedRewards(user, recipient, accruedRewards); return accruedRewards; } /** * @dev Settle a user's rewards up to the latest global index as of `block.timestamp`. Triggers a * settlement of the global index up to `block.timestamp`. Should be called with the OLD user * and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param totalStaked Total tokens staked by all users during the period since the last global * index update. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToNow( address user, uint256 userStaked, uint256 totalStaked ) internal returns (uint256) { uint256 globalIndex = _settleGlobalIndexUpToNow(totalStaked); return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle a user's rewards up to an epoch boundary. Should be used to partially settle a * user's rewards if their balance was known to have changed on that epoch boundary. * * @param user The user's address. * @param userStaked Tokens staked by the user. Should be accurate for the time period * since the last update to this user and up to the end of the * specified epoch. * @param epochNumber Settle the user's rewards up to the end of this epoch. * * @return The user's accrued rewards, including past unclaimed rewards, up to the end of the * specified epoch. */ function _settleUserRewardsUpToEpoch( address user, uint256 userStaked, uint256 epochNumber ) internal returns (uint256) { uint256 globalIndex = _EPOCH_INDEXES_[epochNumber]; return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle the global index up to the end of the given epoch. * * IMPORTANT: This function should only be called under conditions which ensure the following: * - `epochNumber` < the current epoch number * - `_GLOBAL_INDEX_TIMESTAMP_ < settleUpToTimestamp` * - `_EPOCH_INDEXES_[epochNumber] = 0` */ function _settleGlobalIndexUpToEpoch( uint256 totalStaked, uint256 epochNumber ) internal returns (uint256) { uint256 settleUpToTimestamp = getStartOfEpoch(epochNumber.add(1)); uint256 globalIndex = _settleGlobalIndexUpToTimestamp(totalStaked, settleUpToTimestamp); _EPOCH_INDEXES_[epochNumber] = globalIndex; return globalIndex; } // ============ Private Functions ============ /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * since the last update to the global index. * * @return The new global index. */ function _settleGlobalIndexUpToNow( uint256 totalStaked ) private returns (uint256) { return _settleGlobalIndexUpToTimestamp(totalStaked, block.timestamp); } /** * @dev Helper function which settles a user's rewards up to a global index. Should be called * any time a user's staked balance changes, with the OLD user and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param newGlobalIndex The new index value to bring the user index up to. MUST NOT be less * than the user's index. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToIndex( address user, uint256 userStaked, uint256 newGlobalIndex ) private returns (uint256) { uint256 oldAccruedRewards = _USER_REWARDS_BALANCES_[user]; uint256 oldUserIndex = _USER_INDEXES_[user]; if (oldUserIndex == newGlobalIndex) { return oldAccruedRewards; } uint256 newAccruedRewards; if (userStaked == 0) { // Note: Even if the user's staked balance is zero, we still need to update the user index. newAccruedRewards = oldAccruedRewards; } else { // Calculate newly accrued rewards since the last update to the user's index. uint256 indexDelta = newGlobalIndex.sub(oldUserIndex); uint256 accruedRewardsDelta = userStaked.mul(indexDelta).div(INDEX_BASE); newAccruedRewards = oldAccruedRewards.add(accruedRewardsDelta); // Update the user's rewards. _USER_REWARDS_BALANCES_[user] = newAccruedRewards; } // Update the user's index. _USER_INDEXES_[user] = newGlobalIndex; emit UserIndexUpdated(user, newGlobalIndex, newAccruedRewards); return newAccruedRewards; } /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * (_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp). * @param settleUpToTimestamp The timestamp up to which to settle rewards. It MUST satisfy * `settleUpToTimestamp <= block.timestamp`. * * @return The new global index. */ function _settleGlobalIndexUpToTimestamp( uint256 totalStaked, uint256 settleUpToTimestamp ) private returns (uint256) { uint256 oldGlobalIndex = uint256(_GLOBAL_INDEX_); // The goal of this function is to calculate rewards earned since the last global index update. // These rewards are earned over the time interval which is the intersection of the intervals // [_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp] and [DISTRIBUTION_START, DISTRIBUTION_END]. // // We can simplify a bit based on the assumption: // `_GLOBAL_INDEX_TIMESTAMP_ >= DISTRIBUTION_START` // // Get the start and end of the time interval under consideration. uint256 intervalStart = uint256(_GLOBAL_INDEX_TIMESTAMP_); uint256 intervalEnd = Math.min(settleUpToTimestamp, DISTRIBUTION_END); // Return early if the interval has length zero (incl. case where intervalEnd < intervalStart). if (intervalEnd <= intervalStart) { return oldGlobalIndex; } // Note: If we reach this point, we must update _GLOBAL_INDEX_TIMESTAMP_. uint256 emissionPerSecond = _REWARDS_PER_SECOND_; if (emissionPerSecond == 0 || totalStaked == 0) { // Ensure a log is emitted if the timestamp changed, even if the index does not change. _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); emit GlobalIndexUpdated(oldGlobalIndex); return oldGlobalIndex; } // Calculate the change in index over the interval. uint256 timeDelta = intervalEnd.sub(intervalStart); uint256 indexDelta = timeDelta.mul(emissionPerSecond).mul(INDEX_BASE).div(totalStaked); // Calculate, update, and return the new global index. uint256 newGlobalIndex = oldGlobalIndex.add(indexDelta); // Update storage. (Shared storage slot.) _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); _GLOBAL_INDEX_ = newGlobalIndex.toUint224(); emit GlobalIndexUpdated(newGlobalIndex); return newGlobalIndex; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol'; /** * @title Math * @author dYdX * * @dev Library for non-standard Math functions. */ library Math { using SafeMath for uint256; // ============ Library Functions ============ /** * @dev Return `ceil(numerator / denominator)`. */ function divRoundUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return numerator.sub(1).div(denominator).add(1); } /** * @dev Returns the minimum between a and b. */ function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the maximum between a and b. */ function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1EpochSchedule * @author dYdX * * @dev Defines a function from block timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Note that by restricting `b` to be non-negative, we limit ourselves to functions in which epoch * zero starts at a non-negative timestamp. * * The recommended epoch length and blackout window are 28 and 7 days respectively; however, these * are modifiable by the admin, within the specified bounds. */ abstract contract SM1EpochSchedule is SM1Storage { using SafeCast for uint256; using SafeMath for uint256; // ============ Events ============ event EpochParametersChanged( SM1Types.EpochParameters epochParameters ); event BlackoutWindowChanged( uint256 blackoutWindow ); // ============ Initializer ============ function __SM1EpochSchedule_init( uint256 interval, uint256 offset, uint256 blackoutWindow ) internal { require( block.timestamp < offset, 'SM1EpochSchedule: Epoch zero must start after initialization' ); _setBlackoutWindow(blackoutWindow); _setEpochParameters(interval, offset); } // ============ Public Functions ============ /** * @notice Get the epoch at the current block timestamp. * * NOTE: Reverts if epoch zero has not started. * * @return The current epoch number. */ function getCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); return offsetTimestamp.div(interval); } /** * @notice Get the time remaining in the current epoch. * * NOTE: Reverts if epoch zero has not started. * * @return The number of seconds until the next epoch. */ function getTimeRemainingInCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); uint256 timeElapsedInEpoch = offsetTimestamp.mod(interval); return interval.sub(timeElapsedInEpoch); } /** * @notice Given an epoch number, get the start of that epoch. Calculated as `t = (n * a) + b`. * * @return The timestamp in seconds representing the start of that epoch. */ function getStartOfEpoch( uint256 epochNumber ) public view returns (uint256) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); return epochNumber.mul(interval).add(offset); } /** * @notice Check whether we are at or past the start of epoch zero. * * @return Boolean `true` if the current timestamp is at least the start of epoch zero, * otherwise `false`. */ function hasEpochZeroStarted() public view returns (bool) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 offset = uint256(epochParameters.offset); return block.timestamp >= offset; } /** * @notice Check whether we are in a blackout window, where withdrawal requests are restricted. * Note that before epoch zero has started, there are no blackout windows. * * @return Boolean `true` if we are in a blackout window, otherwise `false`. */ function inBlackoutWindow() public view returns (bool) { return hasEpochZeroStarted() && getTimeRemainingInCurrentEpoch() <= _BLACKOUT_WINDOW_; } // ============ Internal Functions ============ function _setEpochParameters( uint256 interval, uint256 offset ) internal { SM1Types.EpochParameters memory epochParameters = SM1Types.EpochParameters({interval: interval.toUint128(), offset: offset.toUint128()}); _EPOCH_PARAMETERS_ = epochParameters; emit EpochParametersChanged(epochParameters); } function _setBlackoutWindow( uint256 blackoutWindow ) internal { _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); } // ============ Private Functions ============ /** * @dev Helper function to read params from storage and apply offset to the given timestamp. * Recall that the formula for epoch number is `n = (t - b) / a`. * * NOTE: Reverts if epoch zero has not started. * * @return The values `a` and `(t - b)`. */ function _getIntervalAndOffsetTimestamp() private view returns (uint256, uint256) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); require( block.timestamp >= offset, 'SM1EpochSchedule: Epoch zero has not started' ); uint256 offsetTimestamp = block.timestamp.sub(offset); return (interval, offsetTimestamp); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { IERC20Detailed } from '../../../interfaces/IERC20Detailed.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1GovernancePowerDelegation } from './SM1GovernancePowerDelegation.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1ERC20 * @author dYdX * * @dev ERC20 interface for staked tokens. Implements governance functionality for the tokens. * * Also allows a user with an active stake to transfer their staked tokens to another user, * even if they would otherwise be restricted from withdrawing. */ abstract contract SM1ERC20 is SM1StakedBalances, SM1GovernancePowerDelegation, IERC20Detailed { using SafeMath for uint256; // ============ Constants ============ /// @notice EIP-712 typehash for token approval via EIP-2612 permit. bytes32 public constant PERMIT_TYPEHASH = keccak256( 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' ); // ============ External Functions ============ function name() external pure override returns (string memory) { return 'Staked DYDX'; } function symbol() external pure override returns (string memory) { return 'stkDYDX'; } function decimals() external pure override returns (uint8) { return 18; } /** * @notice Get the total supply of staked balances. * * Note that due to the exchange rate, this is different than querying the total balance of * underyling token staked to this contract. * * @return The sum of all staked balances. */ function totalSupply() external view override returns (uint256) { return getTotalActiveBalanceCurrentEpoch() + getTotalInactiveBalanceCurrentEpoch(); } /** * @notice Get a user's staked balance. * * Note that due to the exchange rate, one unit of staked balance may not be equivalent to one * unit of the underlying token. Also note that a user's staked balance is different from a * user's transferable balance. * * @param account The account to get the balance of. * * @return The user's staked balance. */ function balanceOf( address account ) public view override(SM1GovernancePowerDelegation, IERC20) returns (uint256) { return getActiveBalanceCurrentEpoch(account) + getInactiveBalanceCurrentEpoch(account); } function transfer( address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance( address owner, address spender ) external view override returns (uint256) { return _ALLOWANCES_[owner][spender]; } function approve( address spender, uint256 amount ) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _ALLOWANCES_[sender][msg.sender].sub(amount, 'SM1ERC20: transfer amount exceeds allowance') ); return true; } function increaseAllowance( address spender, uint256 addedValue ) external returns (bool) { _approve(msg.sender, spender, _ALLOWANCES_[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) external returns (bool) { _approve( msg.sender, spender, _ALLOWANCES_[msg.sender][spender].sub( subtractedValue, 'SM1ERC20: Decreased allowance below zero' ) ); return true; } /** * @notice Implements the permit function as specified in EIP-2612. * * @param owner Address of the token owner. * @param spender Address of the spender. * @param value Amount of allowance. * @param deadline Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require( owner != address(0), 'SM1ERC20: INVALID_OWNER' ); require( block.timestamp <= deadline, 'SM1ERC20: INVALID_EXPIRATION' ); uint256 currentValidNonce = _NONCES_[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', _DOMAIN_SEPARATOR_, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require( owner == ecrecover(digest, v, r, s), 'SM1ERC20: INVALID_SIGNATURE' ); _NONCES_[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } // ============ Internal Functions ============ function _transfer( address sender, address recipient, uint256 amount ) internal { require( sender != address(0), 'SM1ERC20: Transfer from address(0)' ); require( recipient != address(0), 'SM1ERC20: Transfer to address(0)' ); require( getTransferableBalance(sender) >= amount, 'SM1ERC20: Transfer exceeds next epoch active balance' ); // Update staked balances and delegate snapshots. _transferCurrentAndNextActiveBalance(sender, recipient, amount); _moveDelegatesForTransfer(sender, recipient, amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) internal { require( owner != address(0), 'SM1ERC20: Approve from address(0)' ); require( spender != address(0), 'SM1ERC20: Approve to address(0)' ); _ALLOWANCES_[owner][spender] = amount; emit Approval(owner, spender, amount); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; import { IERC20 } from './IERC20.sol'; /** * @dev Interface for ERC20 including metadata **/ interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IGovernancePowerDelegationERC20 } from '../../../interfaces/IGovernancePowerDelegationERC20.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1ExchangeRate } from './SM1ExchangeRate.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1GovernancePowerDelegation * @author dYdX * * @dev Provides support for two types of governance powers which are separately delegatable. * Provides functions for delegation and for querying a user's power at a certain block number. * * Internally, makes use of staked balances denoted in staked units, but returns underlying token * units from the getPowerAtBlock() and getPowerCurrent() functions. * * This is based on, and is designed to match, Aave's implementation, which is used in their * governance token and staked token contracts. */ abstract contract SM1GovernancePowerDelegation is SM1ExchangeRate, IGovernancePowerDelegationERC20 { using SafeMath for uint256; // ============ Constants ============ /// @notice EIP-712 typehash for delegation by signature of a specific governance power type. bytes32 public constant DELEGATE_BY_TYPE_TYPEHASH = keccak256( 'DelegateByType(address delegatee,uint256 type,uint256 nonce,uint256 expiry)' ); /// @notice EIP-712 typehash for delegation by signature of all governance powers. bytes32 public constant DELEGATE_TYPEHASH = keccak256( 'Delegate(address delegatee,uint256 nonce,uint256 expiry)' ); // ============ External Functions ============ /** * @notice Delegates a specific governance power of the sender to a delegatee. * * @param delegatee The address to delegate power to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function delegateByType( address delegatee, DelegationType delegationType ) external override { _delegateByType(msg.sender, delegatee, delegationType); } /** * @notice Delegates all governance powers of the sender to a delegatee. * * @param delegatee The address to delegate power to. */ function delegate( address delegatee ) external override { _delegateByType(msg.sender, delegatee, DelegationType.VOTING_POWER); _delegateByType(msg.sender, delegatee, DelegationType.PROPOSITION_POWER); } /** * @dev Delegates specific governance power from signer to `delegatee` using an EIP-712 signature. * * @param delegatee The address to delegate votes to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). * @param nonce The signer's nonce for EIP-712 signatures on this contract. * @param expiry Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function delegateByTypeBySig( address delegatee, DelegationType delegationType, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 structHash = keccak256( abi.encode(DELEGATE_BY_TYPE_TYPEHASH, delegatee, uint256(delegationType), nonce, expiry) ); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash)); address signer = ecrecover(digest, v, r, s); require( signer != address(0), 'SM1GovernancePowerDelegation: INVALID_SIGNATURE' ); require( nonce == _NONCES_[signer]++, 'SM1GovernancePowerDelegation: INVALID_NONCE' ); require( block.timestamp <= expiry, 'SM1GovernancePowerDelegation: INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, delegationType); } /** * @dev Delegates both governance powers from signer to `delegatee` using an EIP-712 signature. * * @param delegatee The address to delegate votes to. * @param nonce The signer's nonce for EIP-712 signatures on this contract. * @param expiry Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 structHash = keccak256(abi.encode(DELEGATE_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash)); address signer = ecrecover(digest, v, r, s); require( signer != address(0), 'SM1GovernancePowerDelegation: INVALID_SIGNATURE' ); require( nonce == _NONCES_[signer]++, 'SM1GovernancePowerDelegation: INVALID_NONCE' ); require( block.timestamp <= expiry, 'SM1GovernancePowerDelegation: INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, DelegationType.VOTING_POWER); _delegateByType(signer, delegatee, DelegationType.PROPOSITION_POWER); } /** * @notice Returns the delegatee of a user. * * @param delegator The address of the delegator. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function getDelegateeByType( address delegator, DelegationType delegationType ) external override view returns (address) { (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); return _getDelegatee(delegator, delegates); } /** * @notice Returns the current power of a user. The current power is the power delegated * at the time of the last snapshot. * * @param user The user whose power to query. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerCurrent( address user, DelegationType delegationType ) external override view returns (uint256) { return getPowerAtBlock(user, block.number, delegationType); } /** * @notice Get the next valid nonce for EIP-712 signatures. * * This nonce should be used when signing for any of the following functions: * - permit() * - delegateByTypeBySig() * - delegateBySig() */ function nonces( address owner ) external view returns (uint256) { return _NONCES_[owner]; } // ============ Public Functions ============ function balanceOf( address account ) public view virtual returns (uint256); /** * @notice Returns the power of a user at a certain block, denominated in underlying token units. * * @param user The user whose power to query. * @param blockNumber The block number at which to get the user's power. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). * * @return The user's governance power of the specified type, in underlying token units. */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) public override view returns (uint256) { ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotCounts, // unused: delegates ) = _getDelegationDataByType(delegationType); uint256 stakeAmount = _findValueAtBlock( snapshots[user], snapshotCounts[user], blockNumber, 0 ); uint256 exchangeRate = _findValueAtBlock( _EXCHANGE_RATE_SNAPSHOTS_, _EXCHANGE_RATE_SNAPSHOT_COUNT_, blockNumber, EXCHANGE_RATE_BASE ); return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, exchangeRate); } // ============ Internal Functions ============ /** * @dev Delegates one specific power to a delegatee. * * @param delegator The user whose power to delegate. * @param delegatee The address to delegate power to. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _delegateByType( address delegator, address delegatee, DelegationType delegationType ) internal { require( delegatee != address(0), 'SM1GovernancePowerDelegation: INVALID_DELEGATEE' ); (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); uint256 delegatorBalance = balanceOf(delegator); address previousDelegatee = _getDelegatee(delegator, delegates); delegates[delegator] = delegatee; _moveDelegatesByType(previousDelegatee, delegatee, delegatorBalance, delegationType); emit DelegateChanged(delegator, delegatee, delegationType); } /** * @dev Update delegate snapshots whenever staked tokens are transfered, minted, or burned. * * @param from The sender. * @param to The recipient. * @param stakedAmount The amount being transfered, denominated in staked units. */ function _moveDelegatesForTransfer( address from, address to, uint256 stakedAmount ) internal { address votingPowerFromDelegatee = _getDelegatee(from, _VOTING_DELEGATES_); address votingPowerToDelegatee = _getDelegatee(to, _VOTING_DELEGATES_); _moveDelegatesByType( votingPowerFromDelegatee, votingPowerToDelegatee, stakedAmount, DelegationType.VOTING_POWER ); address propositionPowerFromDelegatee = _getDelegatee(from, _PROPOSITION_DELEGATES_); address propositionPowerToDelegatee = _getDelegatee(to, _PROPOSITION_DELEGATES_); _moveDelegatesByType( propositionPowerFromDelegatee, propositionPowerToDelegatee, stakedAmount, DelegationType.PROPOSITION_POWER ); } /** * @dev Moves power from one user to another. * * @param from The user from which delegated power is moved. * @param to The user that will receive the delegated power. * @param amount The amount of power to be moved. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _moveDelegatesByType( address from, address to, uint256 amount, DelegationType delegationType ) internal { if (from == to) { return; } ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotCounts, // unused: delegates ) = _getDelegationDataByType(delegationType); if (from != address(0)) { mapping(uint256 => SM1Types.Snapshot) storage fromSnapshots = snapshots[from]; uint256 fromSnapshotCount = snapshotCounts[from]; uint256 previousBalance = 0; if (fromSnapshotCount != 0) { previousBalance = fromSnapshots[fromSnapshotCount - 1].value; } uint256 newBalance = previousBalance.sub(amount); snapshotCounts[from] = _writeSnapshot( fromSnapshots, fromSnapshotCount, newBalance ); emit DelegatedPowerChanged(from, newBalance, delegationType); } if (to != address(0)) { mapping(uint256 => SM1Types.Snapshot) storage toSnapshots = snapshots[to]; uint256 toSnapshotCount = snapshotCounts[to]; uint256 previousBalance = 0; if (toSnapshotCount != 0) { previousBalance = toSnapshots[toSnapshotCount - 1].value; } uint256 newBalance = previousBalance.add(amount); snapshotCounts[to] = _writeSnapshot( toSnapshots, toSnapshotCount, newBalance ); emit DelegatedPowerChanged(to, newBalance, delegationType); } } /** * @dev Returns delegation data (snapshot, snapshotCount, delegates) by delegation type. * * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). * * @return The mapping of each user to a mapping of snapshots. * @return The mapping of each user to the total number of snapshots for that user. * @return The mapping of each user to the user's delegate. */ function _getDelegationDataByType( DelegationType delegationType ) internal view returns ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage, mapping(address => uint256) storage, mapping(address => address) storage ) { if (delegationType == DelegationType.VOTING_POWER) { return ( _VOTING_SNAPSHOTS_, _VOTING_SNAPSHOT_COUNTS_, _VOTING_DELEGATES_ ); } else { return ( _PROPOSITION_SNAPSHOTS_, _PROPOSITION_SNAPSHOT_COUNTS_, _PROPOSITION_DELEGATES_ ); } } /** * @dev Returns the delegatee of a user. If a user never performed any delegation, their * delegated address will be 0x0, in which case we return the user's own address. * * @param delegator The address of the user for which return the delegatee. * @param delegates The mapping of delegates for a particular type of delegation. */ function _getDelegatee( address delegator, mapping(address => address) storage delegates ) internal view returns (address) { address previousDelegatee = delegates[delegator]; if (previousDelegatee == address(0)) { return delegator; } return previousDelegatee; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; interface IGovernancePowerDelegationERC20 { enum DelegationType { VOTING_POWER, PROPOSITION_POWER } /** * @dev Emitted when a user delegates governance power to another user. * * @param delegator The delegator. * @param delegatee The delegatee. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ event DelegateChanged( address indexed delegator, address indexed delegatee, DelegationType delegationType ); /** * @dev Emitted when an action changes the delegated power of a user. * * @param user The user whose delegated power has changed. * @param amount The new amount of delegated power for the user. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ event DelegatedPowerChanged(address indexed user, uint256 amount, DelegationType delegationType); /** * @dev Delegates a specific governance power to a delegatee. * * @param delegatee The address to delegate power to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function delegateByType(address delegatee, DelegationType delegationType) external virtual; /** * @dev Delegates all governance powers to a delegatee. * * @param delegatee The user to which the power will be delegated. */ function delegate(address delegatee) external virtual; /** * @dev Returns the delegatee of an user. * * @param delegator The address of the delegator. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function getDelegateeByType(address delegator, DelegationType delegationType) external view virtual returns (address); /** * @dev Returns the current delegated power of a user. The current power is the power delegated * at the time of the last snapshot. * * @param user The user whose power to query. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerCurrent(address user, DelegationType delegationType) external view virtual returns (uint256); /** * @dev Returns the delegated power of a user at a certain block. * * @param user The user whose power to query. * @param blockNumber The block number at which to get the user's power. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Snapshots } from './SM1Snapshots.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1ExchangeRate * @author dYdX * * @dev Performs math using the exchange rate, which converts between underlying units of the token * that was staked (e.g. STAKED_TOKEN.balanceOf(account)), and staked units, used by this contract * for all staked balances (e.g. this.balanceOf(account)). * * OVERVIEW: * * The exchange rate is stored as a multiple of EXCHANGE_RATE_BASE, and represents the number of * staked balance units that each unit of underlying token is worth. Before any slashes have * occurred, the exchange rate is equal to one. The exchange rate can increase with each slash, * indicating that staked balances are becoming less and less valuable, per unit, relative to the * underlying token. * * AVOIDING OVERFLOW AND UNDERFLOW: * * Staked balances are represented internally as uint240, so the result of an operation returning * a staked balances must return a value less than 2^240. Intermediate values in calcuations are * represented as uint256, so all operations within a calculation must return values under 2^256. * * In the functions below operating on the exchange rate, we are strategic in our choice of the * order of multiplication and division operations, in order to avoid both overflow and underflow. * * We use the following assumptions and principles to implement this module: * - (ASSUMPTION) An amount denoted in underlying token units is never greater than 10^28. * - If the exchange rate is greater than 10^46, then we may perform division on the exchange * rate before performing multiplication, provided that the denominator is not greater * than 10^28 (to ensure a result with at least 18 decimals of precision). Specifically, * we use EXCHANGE_RATE_MAY_OVERFLOW as the cutoff, which is a number greater than 10^46. * - Since staked balances are stored as uint240, we cap the exchange rate to ensure that a * staked balance can never overflow (using the assumption above). */ abstract contract SM1ExchangeRate is SM1Snapshots, SM1Storage { using SafeMath for uint256; // ============ Constants ============ /// @notice The assumed upper bound on the total supply of the staked token. uint256 public constant MAX_UNDERLYING_BALANCE = 1e28; /// @notice Base unit used to represent the exchange rate, for additional precision. uint256 public constant EXCHANGE_RATE_BASE = 1e18; /// @notice Cutoff where an exchange rate may overflow after multiplying by an underlying balance. /// @dev Approximately 1.2e49 uint256 public constant EXCHANGE_RATE_MAY_OVERFLOW = (2 ** 256 - 1) / MAX_UNDERLYING_BALANCE; /// @notice Cutoff where a stake amount may overflow after multiplying by EXCHANGE_RATE_BASE. /// @dev Approximately 1.2e59 uint256 public constant STAKE_AMOUNT_MAY_OVERFLOW = (2 ** 256 - 1) / EXCHANGE_RATE_BASE; /// @notice Max exchange rate. /// @dev Approximately 1.8e62 uint256 public constant MAX_EXCHANGE_RATE = ( ((2 ** 240 - 1) / MAX_UNDERLYING_BALANCE) * EXCHANGE_RATE_BASE ); // ============ Initializer ============ function __SM1ExchangeRate_init() internal { _EXCHANGE_RATE_ = EXCHANGE_RATE_BASE; } function stakeAmountFromUnderlyingAmount( uint256 underlyingAmount ) internal view returns (uint256) { uint256 exchangeRate = _EXCHANGE_RATE_; if (exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) { uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE); return underlyingAmount.mul(exchangeRateUnbased); } else { return underlyingAmount.mul(exchangeRate).div(EXCHANGE_RATE_BASE); } } function underlyingAmountFromStakeAmount( uint256 stakeAmount ) internal view returns (uint256) { return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, _EXCHANGE_RATE_); } function underlyingAmountFromStakeAmountWithExchangeRate( uint256 stakeAmount, uint256 exchangeRate ) internal pure returns (uint256) { if (stakeAmount > STAKE_AMOUNT_MAY_OVERFLOW) { // Note that this case implies that exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW. uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE); return stakeAmount.div(exchangeRateUnbased); } else { return stakeAmount.mul(EXCHANGE_RATE_BASE).div(exchangeRate); } } function updateExchangeRate( uint256 numerator, uint256 denominator ) internal returns (uint256) { uint256 oldExchangeRate = _EXCHANGE_RATE_; // Avoid overflow. // Note that the numerator and denominator are both denominated in underlying token units. uint256 newExchangeRate; if (oldExchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) { newExchangeRate = oldExchangeRate.div(denominator).mul(numerator); } else { newExchangeRate = oldExchangeRate.mul(numerator).div(denominator); } require( newExchangeRate <= MAX_EXCHANGE_RATE, 'SM1ExchangeRate: Max exchange rate exceeded' ); _EXCHANGE_RATE_SNAPSHOT_COUNT_ = _writeSnapshot( _EXCHANGE_RATE_SNAPSHOTS_, _EXCHANGE_RATE_SNAPSHOT_COUNT_, newExchangeRate ); _EXCHANGE_RATE_ = newExchangeRate; return newExchangeRate; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Snapshots * @author dYdX * * @dev Handles storage and retrieval of historical values by block number. * * Note that the snapshot stored at a given block number represents the value as of the end of * that block. */ abstract contract SM1Snapshots { /** * @dev Writes a snapshot of a value at the current block. * * @param snapshots Storage mapping from snapshot index to snapshot struct. * @param snapshotCount The total number of snapshots in the provided mapping. * @param newValue The new value to snapshot at the current block. * * @return The new snapshot count. */ function _writeSnapshot( mapping(uint256 => SM1Types.Snapshot) storage snapshots, uint256 snapshotCount, uint256 newValue ) internal returns (uint256) { uint256 currentBlock = block.number; if ( snapshotCount != 0 && snapshots[snapshotCount - 1].blockNumber == currentBlock ) { // If there was a previous snapshot for this block, overwrite it. snapshots[snapshotCount - 1].value = newValue; return snapshotCount; } else { snapshots[snapshotCount] = SM1Types.Snapshot(currentBlock, newValue); return snapshotCount + 1; } } /** * @dev Search for the snapshot value at a given block. Uses binary search. * * Reverts if `blockNumber` is greater than the current block number. * * @param snapshots Storage mapping from snapshot index to snapshot struct. * @param snapshotCount The total number of snapshots in the provided mapping. * @param blockNumber The block number to search for. * @param initialValue The value to return if `blockNumber` is before the earliest snapshot. * * @return The snapshot value at the specified block number. */ function _findValueAtBlock( mapping(uint256 => SM1Types.Snapshot) storage snapshots, uint256 snapshotCount, uint256 blockNumber, uint256 initialValue ) internal view returns (uint256) { require( blockNumber <= block.number, 'SM1Snapshots: INVALID_BLOCK_NUMBER' ); if (snapshotCount == 0) { return initialValue; } // Check earliest snapshot. if (blockNumber < snapshots[0].blockNumber) { return initialValue; } // Check latest snapshot. if (blockNumber >= snapshots[snapshotCount - 1].blockNumber) { return snapshots[snapshotCount - 1].value; } uint256 lower = 0; uint256 upper = snapshotCount - 1; while (upper > lower) { uint256 center = upper - (upper - lower) / 2; // Ceil, avoiding overflow. SM1Types.Snapshot memory snapshot = snapshots[center]; if (snapshot.blockNumber == blockNumber) { return snapshot.value; } else if (snapshot.blockNumber < blockNumber) { lower = center; } else { upper = center - 1; } } return snapshots[lower].value; } }
Check whether we are in a blackout window, where withdrawal requests are restricted. Note that before epoch zero has started, there are no blackout windows. return Boolean `true` if we are in a blackout window, otherwise `false`./
function inBlackoutWindow() public view returns (bool) { return hasEpochZeroStarted() && getTimeRemainingInCurrentEpoch() <= _BLACKOUT_WINDOW_; }
204,024
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; interface IController { function admin() external view returns (address); } contract ControllerV1 is IController, Initializable, ContextUpgradeable, PausableUpgradeable { // IMPORTANT!: For future reference, when adding new variables for following versions of the controller. // All the previous ones should be kept in place and not change locations, types or names. // If thye're modified this would cause issues with the memory slots. address public pauseAdmin; address public override admin; address public recoveryAdmin; function initialize( address _pauseAdmin, address _admin, address _recoveryAdmin ) public initializer { pauseAdmin = _pauseAdmin; admin = _admin; recoveryAdmin = _recoveryAdmin; } function getVersion() external pure returns (uint256) { return 1; } }
IMPORTANT!: For future reference, when adding new variables for following versions of the controller. All the previous ones should be kept in place and not change locations, types or names. If thye're modified this would cause issues with the memory slots.
{ address public pauseAdmin; address public override admin; address public recoveryAdmin; function initialize( address _pauseAdmin, address _admin, address _recoveryAdmin ) public initializer { pauseAdmin = _pauseAdmin; admin = _admin; recoveryAdmin = _recoveryAdmin; } function getVersion() external pure returns (uint256) { return 1; } }
12,992,829
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./AllocationPool.sol"; import "./LinearPool.sol"; contract StakingPool is Initializable, OwnableUpgradeable, LinearPool, AllocationPool { /** * @notice Initialize the contract, get called in the first time deploy * @param _rewardToken the reward token for the allocation pool and the accepted token for the linear pool * @param _rewardPerBlock the number of reward tokens that got unlocked each block * @param _startBlock the number of block when farming start */ function __StakingPool_init( IERC20 _rewardToken, uint128 _rewardPerBlock, uint64 _startBlock ) external initializer { __Ownable_init(); __AllocationPool_init(_rewardToken, _rewardPerBlock, _startBlock); __LinearPool_init(_rewardToken); } /** * @notice Withdraw from allocation pool and deposit to linear pool * @param _allocPoolId id of the allocation pool * @param _linearPoolId id of the linear pool * @param _amount amount to convert * @param _harvestAllocReward whether the user want to claim the rewards from the allocation pool or not */ function fromAllocToLinear( uint256 _allocPoolId, uint256 _linearPoolId, uint128 _amount, bool _harvestAllocReward ) external allocValidatePoolById(_allocPoolId) linearValidatePoolById(_linearPoolId) { address account = msg.sender; AllocPoolInfo storage allocPool = allocPoolInfo[_allocPoolId]; require( allocPool.lpToken == linearAcceptedToken, "AllocStakingPool: invalid allocation pool" ); _allocWithdraw(_allocPoolId, _amount, _harvestAllocReward); emit AllocWithdraw(account, _allocPoolId, _amount); _linearDeposit(_linearPoolId, _amount, account); emit LinearDeposit(_linearPoolId, account, _amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; contract AllocationPool is Initializable, OwnableUpgradeable { using SafeERC20 for IERC20; using SafeCastUpgradeable for uint256; uint64 private constant ACCUMULATED_MULTIPLIER = 1e12; uint64 public constant ALLOC_MAXIMUM_DELAY_DURATION = 35 days; // maximum 35 days delay // Info of each user. struct AllocUserInfo { uint128 amount; // How many LP tokens the user has provided. uint128 rewardDebt; // Reward debt. See explanation below. uint128 pendingReward; // Reward but not harvest // // pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accRewardPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct AllocPoolInfo { IERC20 lpToken; // Address of LP token contract. uint128 lpSupply; // Total lp tokens deposited to this pool. uint64 allocPoint; // How many allocation points assigned to this pool. Rewards to distribute per block. uint64 lastRewardBlock; // Last block number that rewards distribution occurs. uint128 accRewardPerShare; // Accumulated rewards per share, times 1e12. See below. uint128 delayDuration; // The duration user need to wait when withdraw. } struct AllocPendingWithdrawal { uint128 amount; uint128 applicableAt; } // The reward token! IERC20 public allocRewardToken; // Total rewards for each block. uint128 public allocRewardPerBlock; // The reward distribution address address public allocRewardDistributor; // Allow emergency withdraw feature bool public allocAllowEmergencyWithdraw; // Info of each pool. AllocPoolInfo[] public allocPoolInfo; // A record status of LP pool. mapping(IERC20 => bool) public allocIsAdded; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => AllocUserInfo)) public allocUserInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint64 public totalAllocPoint; // The block number when rewards mining starts. uint64 public allocStartBlockNumber; // The block number when rewards mining ends. uint64 public allocEndBlockNumber; // Info of pending withdrawals. mapping(uint256 => mapping(address => AllocPendingWithdrawal)) public allocPendingWithdrawals; event AllocPoolCreated( uint256 indexed pid, address indexed token, uint256 allocPoint ); event AllocDeposit( address indexed user, uint256 indexed pid, uint256 amount ); event AllocWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event AllocPendingWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event AllocEmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event AllocRewardsHarvested( address indexed user, uint256 indexed pid, uint256 amount ); /** * @notice Initialize the contract, get called in the first time deploy * @param _rewardToken the reward token address * @param _rewardPerBlock the number of reward tokens that got unlocked each block * @param _startBlock the block number when farming start */ function __AllocationPool_init( IERC20 _rewardToken, uint128 _rewardPerBlock, uint64 _startBlock ) public initializer { __Ownable_init(); require( address(_rewardToken) != address(0), "AllocStakingPool: invalid reward token address" ); allocRewardToken = _rewardToken; allocRewardPerBlock = _rewardPerBlock; allocStartBlockNumber = _startBlock; totalAllocPoint = 0; } /** * @notice Validate pool by pool ID * @param _pid id of the pool */ modifier allocValidatePoolById(uint256 _pid) { require( _pid < allocPoolInfo.length, "AllocStakingPool: pool are not exist" ); _; } /** * @notice Return total number of pools */ function allocPoolLength() external view returns (uint256) { return allocPoolInfo.length; } /** * @notice Add a new lp to the pool. Can only be called by the owner. * @param _allocPoint the allocation point of the pool, used when calculating total reward the whole pool will receive each block * @param _lpToken the token which this pool will accept * @param _delayDuration the time user need to wait when withdraw */ function allocAddPool( uint64 _allocPoint, IERC20 _lpToken, uint128 _delayDuration ) external onlyOwner { require( !allocIsAdded[_lpToken], "AllocStakingPool: pool already is added" ); require( _delayDuration <= ALLOC_MAXIMUM_DELAY_DURATION, "AllocStakingPool: delay duration is too long" ); allocMassUpdatePools(); uint64 lastRewardBlock = block.number > allocStartBlockNumber ? block.number.toUint64() : allocStartBlockNumber; totalAllocPoint = totalAllocPoint + _allocPoint; allocPoolInfo.push( AllocPoolInfo({ lpToken: _lpToken, lpSupply: 0, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0, delayDuration: _delayDuration }) ); allocIsAdded[_lpToken] = true; emit AllocPoolCreated( allocPoolInfo.length - 1, address(_lpToken), _allocPoint ); } /** * @notice Update the given pool's reward allocation point. Can only be called by the owner. * @param _pid id of the pool * @param _allocPoint the allocation point of the pool, used when calculating total reward the whole pool will receive each block * @param _delayDuration the time user need to wait when withdraw */ function allocSetPool( uint256 _pid, uint64 _allocPoint, uint128 _delayDuration ) external onlyOwner allocValidatePoolById(_pid) { require( _delayDuration <= ALLOC_MAXIMUM_DELAY_DURATION, "AllocStakingPool: delay duration is too long" ); allocMassUpdatePools(); totalAllocPoint = totalAllocPoint - allocPoolInfo[_pid].allocPoint + _allocPoint; allocPoolInfo[_pid].allocPoint = _allocPoint; allocPoolInfo[_pid].delayDuration = _delayDuration; } /** * @notice Set the reward distributor. Can only be called by the owner. * @param _allocRewardDistributor the reward distributor */ function allocSetRewardDistributor(address _allocRewardDistributor) external onlyOwner { require( _allocRewardDistributor != address(0), "AllocStakingPool: invalid reward distributor" ); allocRewardDistributor = _allocRewardDistributor; } /** * @notice Set the end block number. Can only be called by the owner. */ function allocSetEndBlock(uint64 _endBlockNumber) external onlyOwner { require( _endBlockNumber > block.number, "AllocStakingPool: invalid reward distributor" ); allocEndBlockNumber = _endBlockNumber; } /** * @notice Return time multiplier over the given _from to _to block. * @param _from the number of starting block * @param _to the number of ending block */ function allocTimeMultiplier(uint128 _from, uint128 _to) public view returns (uint128) { if (allocEndBlockNumber > 0 && _to > allocEndBlockNumber) { return allocEndBlockNumber > _from ? allocEndBlockNumber - _from : 0; } return _to - _from; } /** * @notice Update number of reward per block * @param _rewardPerBlock the number of reward tokens that got unlocked each block */ function allocSetRewardPerBlock(uint128 _rewardPerBlock) external onlyOwner { allocMassUpdatePools(); allocRewardPerBlock = _rewardPerBlock; } /** * @notice View function to see pending rewards on frontend. * @param _pid id of the pool * @param _user the address of the user */ function allocPendingReward(uint256 _pid, address _user) public view allocValidatePoolById(_pid) returns (uint128) { AllocPoolInfo storage pool = allocPoolInfo[_pid]; AllocUserInfo storage user = allocUserInfo[_pid][_user]; uint128 accRewardPerShare = pool.accRewardPerShare; uint128 lpSupply = pool.lpSupply; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint128 multiplier = allocTimeMultiplier( pool.lastRewardBlock, block.number.toUint128() ); uint128 poolReward = (multiplier * allocRewardPerBlock * pool.allocPoint) / totalAllocPoint; accRewardPerShare = accRewardPerShare + ((poolReward * ACCUMULATED_MULTIPLIER) / lpSupply); } return user.pendingReward + (((user.amount * accRewardPerShare) / ACCUMULATED_MULTIPLIER) - user.rewardDebt); } /** * @notice Update reward vairables for all pools. Be careful of gas spending! */ function allocMassUpdatePools() public { uint256 length = allocPoolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { allocUpdatePool(pid); } } /** * @notice Update reward variables of the given pool to be up-to-date. * @param _pid id of the pool */ function allocUpdatePool(uint256 _pid) public allocValidatePoolById(_pid) { AllocPoolInfo storage pool = allocPoolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpSupply; if (lpSupply == 0) { pool.lastRewardBlock = block.number.toUint64(); return; } uint256 multiplier = allocTimeMultiplier( pool.lastRewardBlock, block.number.toUint128() ); uint256 poolReward = (multiplier * allocRewardPerBlock * pool.allocPoint) / totalAllocPoint; pool.accRewardPerShare = (pool.accRewardPerShare + ((poolReward * ACCUMULATED_MULTIPLIER) / lpSupply)).toUint128(); pool.lastRewardBlock = block.number.toUint64(); } /** * @notice Deposit LP tokens to the farm for reward allocation. * @param _pid id of the pool * @param _amount amount to deposit */ function allocDeposit(uint256 _pid, uint128 _amount) external allocValidatePoolById(_pid) { AllocPoolInfo storage pool = allocPoolInfo[_pid]; AllocUserInfo storage user = allocUserInfo[_pid][msg.sender]; allocUpdatePool(_pid); uint128 pending = ((user.amount * pool.accRewardPerShare) / ACCUMULATED_MULTIPLIER) - user.rewardDebt; user.pendingReward = user.pendingReward + pending; user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accRewardPerShare) / ACCUMULATED_MULTIPLIER; pool.lpSupply = pool.lpSupply + _amount; pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); emit AllocDeposit(msg.sender, _pid, _amount); } /** * @notice Withdraw LP tokens from Pool. * @param _pid id of the pool * @param _amount amount to withdraw * @param _harvestReward whether the user want to claim the rewards or not */ function allocWithdraw( uint256 _pid, uint128 _amount, bool _harvestReward ) external allocValidatePoolById(_pid) { _allocWithdraw(_pid, _amount, _harvestReward); AllocPoolInfo storage pool = allocPoolInfo[_pid]; if (pool.delayDuration == 0) { pool.lpToken.safeTransfer(address(msg.sender), _amount); emit AllocWithdraw(msg.sender, _pid, _amount); return; } AllocPendingWithdrawal storage pendingWithdraw = allocPendingWithdrawals[_pid][msg.sender]; pendingWithdraw.amount = pendingWithdraw.amount + _amount; pendingWithdraw.applicableAt = block.timestamp.toUint128() + pool.delayDuration; } /** * @notice Claim pending withdrawal * @param _pid id of the pool */ function allocClaimPendingWithdraw(uint256 _pid) external allocValidatePoolById(_pid) { AllocPoolInfo storage pool = allocPoolInfo[_pid]; AllocPendingWithdrawal storage pendingWithdraw = allocPendingWithdrawals[_pid][msg.sender]; uint256 amount = pendingWithdraw.amount; require(amount > 0, "AllocStakingPool: nothing is currently pending"); require( pendingWithdraw.applicableAt <= block.timestamp, "AllocStakingPool: not released yet" ); delete allocPendingWithdrawals[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), amount); emit AllocWithdraw(msg.sender, _pid, amount); } /** * @notice Update allowance for emergency withdraw * @param _shouldAllow should allow emergency withdraw or not */ function allocSetAllowEmergencyWithdraw(bool _shouldAllow) external onlyOwner { allocAllowEmergencyWithdraw = _shouldAllow; } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. * @param _pid id of the pool */ function allocEmergencyWithdraw(uint256 _pid) external allocValidatePoolById(_pid) { require( allocAllowEmergencyWithdraw, "AllocStakingPool: emergency withdrawal is not allowed yet" ); AllocPoolInfo storage pool = allocPoolInfo[_pid]; AllocUserInfo storage user = allocUserInfo[_pid][msg.sender]; uint128 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpSupply = pool.lpSupply - amount; pool.lpToken.safeTransfer(address(msg.sender), amount); emit AllocEmergencyWithdraw(msg.sender, _pid, amount); } /** * @notice Compound rewards to reward pool * @param _rewardPoolId id of the reward pool */ function allocCompoundReward(uint256 _rewardPoolId) external allocValidatePoolById(_rewardPoolId) { AllocPoolInfo storage pool = allocPoolInfo[_rewardPoolId]; AllocUserInfo storage user = allocUserInfo[_rewardPoolId][msg.sender]; require( pool.lpToken == allocRewardToken, "AllocStakingPool: invalid reward pool" ); uint128 totalPending = allocPendingReward(_rewardPoolId, msg.sender); require(totalPending > 0, "AllocStakingPool: invalid reward amount"); user.pendingReward = 0; allocSafeRewardTransfer(address(this), totalPending); emit AllocRewardsHarvested(msg.sender, _rewardPoolId, totalPending); allocUpdatePool(_rewardPoolId); user.amount = user.amount + totalPending; user.rewardDebt = (user.amount * pool.accRewardPerShare) / ACCUMULATED_MULTIPLIER; pool.lpSupply = pool.lpSupply + totalPending; emit AllocDeposit(msg.sender, _rewardPoolId, totalPending); } /** * @notice Harvest proceeds msg.sender * @param _pid id of the pool */ function allocClaimReward(uint256 _pid) public allocValidatePoolById(_pid) returns (uint128) { allocUpdatePool(_pid); AllocPoolInfo storage pool = allocPoolInfo[_pid]; AllocUserInfo storage user = allocUserInfo[_pid][msg.sender]; uint128 totalPending = allocPendingReward(_pid, msg.sender); user.pendingReward = 0; user.rewardDebt = (user.amount * pool.accRewardPerShare) / (ACCUMULATED_MULTIPLIER); if (totalPending > 0) { allocSafeRewardTransfer(msg.sender, totalPending); } emit AllocRewardsHarvested(msg.sender, _pid, totalPending); return totalPending; } /** * @notice Harvest proceeds of all pools for msg.sender * @param _pids ids of the pools */ function allocClaimAll(uint256[] memory _pids) external { uint256 length = _pids.length; for (uint256 pid = 0; pid < length; ++pid) { allocClaimReward(pid); } } /** * @notice Withdraw LP tokens from Pool. * @param _pid id of the pool * @param _amount amount to withdraw * @param _harvestReward whether the user want to claim the rewards or not */ function _allocWithdraw( uint256 _pid, uint128 _amount, bool _harvestReward ) internal { AllocPoolInfo storage pool = allocPoolInfo[_pid]; AllocUserInfo storage user = allocUserInfo[_pid][msg.sender]; require(user.amount >= _amount, "AllocStakingPool: invalid amount"); if (_harvestReward || user.amount == _amount) { allocClaimReward(_pid); } else { allocUpdatePool(_pid); uint128 pending = ((user.amount * pool.accRewardPerShare) / ACCUMULATED_MULTIPLIER) - user.rewardDebt; if (pending > 0) { user.pendingReward = user.pendingReward + pending; } } user.amount -= _amount; user.rewardDebt = (user.amount * pool.accRewardPerShare) / ACCUMULATED_MULTIPLIER; pool.lpSupply = pool.lpSupply - _amount; } /** * @notice Safe reward transfer function, just in case if reward distributor dose not have enough reward tokens. * @param _to address of the receiver * @param _amount amount of the reward token */ function allocSafeRewardTransfer(address _to, uint128 _amount) internal { uint256 bal = allocRewardToken.balanceOf(allocRewardDistributor); require(_amount <= bal, "AllocStakingPool: not enough reward token"); allocRewardToken.safeTransferFrom(allocRewardDistributor, _to, _amount); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; contract LinearPool is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeCastUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; uint32 private constant ONE_YEAR_IN_SECONDS = 365 days; uint64 public constant LINEAR_MAXIMUM_DELAY_DURATION = 35 days; // maximum 35 days delay // The accepted token IERC20 public linearAcceptedToken; // The reward distribution address address public linearRewardDistributor; // Info of each pool LinearPoolInfo[] public linearPoolInfo; // Info of each user that stakes in pools mapping(uint256 => mapping(address => LinearStakingData)) public linearStakingData; // Info of pending withdrawals. mapping(uint256 => mapping(address => LinearPendingWithdrawal)) public linearPendingWithdrawals; // The flexible lock duration. Users who stake in the flexible pool will be affected by this uint128 public linearFlexLockDuration; // Allow emergency withdraw feature bool public linearAllowEmergencyWithdraw; event LinearPoolCreated(uint256 indexed poolId, uint256 APR); event LinearDeposit( uint256 indexed poolId, address indexed account, uint256 amount ); event LinearWithdraw( uint256 indexed poolId, address indexed account, uint256 amount ); event LinearRewardsHarvested( uint256 indexed poolId, address indexed account, uint256 reward ); event LinearPendingWithdraw( uint256 indexed poolId, address indexed account, uint256 amount ); event LinearEmergencyWithdraw( uint256 indexed poolId, address indexed account, uint256 amount ); struct LinearPoolInfo { uint128 cap; uint128 totalStaked; uint128 minInvestment; uint128 maxInvestment; uint64 APR; uint128 lockDuration; uint128 delayDuration; uint128 startJoinTime; uint128 endJoinTime; } struct LinearStakingData { uint128 balance; uint128 joinTime; uint128 updatedTime; uint128 reward; } struct LinearPendingWithdrawal { uint128 amount; uint128 applicableAt; } /** * @notice Initialize the contract, get called in the first time deploy * @param _acceptedToken the token that the pools will use as staking and reward token */ function __LinearPool_init(IERC20 _acceptedToken) public initializer { __Ownable_init(); linearAcceptedToken = _acceptedToken; } /** * @notice Validate pool by pool ID * @param _poolId id of the pool */ modifier linearValidatePoolById(uint256 _poolId) { require( _poolId < linearPoolInfo.length, "LinearStakingPool: Pool are not exist" ); _; } /** * @notice Return total number of pools */ function linearPoolLength() external view returns (uint256) { return linearPoolInfo.length; } /** * @notice Return total tokens staked in a pool * @param _poolId id of the pool */ function linearTotalStaked(uint256 _poolId) external view linearValidatePoolById(_poolId) returns (uint256) { return linearPoolInfo[_poolId].totalStaked; } /** * @notice Add a new pool with different APR and conditions. Can only be called by the owner. * @param _cap the maximum number of staking tokens the pool will receive. If this limit is reached, users can not deposit into this pool. * @param _minInvestment the minimum investment amount users need to use in order to join the pool. * @param _maxInvestment the maximum investment amount users can deposit to join the pool. * @param _APR the APR rate of the pool. * @param _lockDuration the duration users need to wait before being able to withdraw and claim the rewards. * @param _delayDuration the duration users need to wait to receive the principal amount, after unstaking from the pool. * @param _startJoinTime the time when users can start to join the pool * @param _endJoinTime the time when users can no longer join the pool */ function linearAddPool( uint128 _cap, uint128 _minInvestment, uint128 _maxInvestment, uint64 _APR, uint128 _lockDuration, uint128 _delayDuration, uint128 _startJoinTime, uint128 _endJoinTime ) external onlyOwner { require( _endJoinTime >= block.timestamp && _endJoinTime > _startJoinTime, "LinearStakingPool: invalid end join time" ); require( _delayDuration <= LINEAR_MAXIMUM_DELAY_DURATION, "LinearStakingPool: delay duration is too long" ); linearPoolInfo.push( LinearPoolInfo({ cap: _cap, totalStaked: 0, minInvestment: _minInvestment, maxInvestment: _maxInvestment, APR: _APR, lockDuration: _lockDuration, delayDuration: _delayDuration, startJoinTime: _startJoinTime, endJoinTime: _endJoinTime }) ); emit LinearPoolCreated(linearPoolInfo.length - 1, _APR); } /** * @notice Update the given pool's info. Can only be called by the owner. * @param _poolId id of the pool * @param _cap the maximum number of staking tokens the pool will receive. If this limit is reached, users can not deposit into this pool. * @param _minInvestment minimum investment users need to use in order to join the pool. * @param _maxInvestment the maximum investment amount users can deposit to join the pool. * @param _APR the APR rate of the pool. * @param _endJoinTime the time when users can no longer join the pool */ function linearSetPool( uint128 _poolId, uint128 _cap, uint128 _minInvestment, uint128 _maxInvestment, uint64 _APR, uint128 _endJoinTime ) external onlyOwner linearValidatePoolById(_poolId) { LinearPoolInfo storage pool = linearPoolInfo[_poolId]; require( _endJoinTime >= block.timestamp && _endJoinTime > pool.startJoinTime, "LinearStakingPool: invalid end join time" ); linearPoolInfo[_poolId].cap = _cap; linearPoolInfo[_poolId].minInvestment = _minInvestment; linearPoolInfo[_poolId].maxInvestment = _maxInvestment; linearPoolInfo[_poolId].APR = _APR; linearPoolInfo[_poolId].endJoinTime = _endJoinTime; } /** * @notice Set the flexible lock time. This will affects the flexible pool. Can only be called by the owner. * @param _flexLockDuration the minimum lock duration */ function linearSetFlexLockDuration(uint128 _flexLockDuration) external onlyOwner { require( _flexLockDuration <= LINEAR_MAXIMUM_DELAY_DURATION, "LinearStakingPool: flexible lock duration is too long" ); linearFlexLockDuration = _flexLockDuration; } /** * @notice Set the reward distributor. Can only be called by the owner. * @param _linearRewardDistributor the reward distributor */ function linearSetRewardDistributor(address _linearRewardDistributor) external onlyOwner { require( _linearRewardDistributor != address(0), "LinearStakingPool: invalid reward distributor" ); linearRewardDistributor = _linearRewardDistributor; } /** * @notice Deposit token to earn rewards * @param _poolId id of the pool * @param _amount amount of token to deposit */ function linearDeposit(uint256 _poolId, uint128 _amount) external nonReentrant linearValidatePoolById(_poolId) { address account = msg.sender; _linearDeposit(_poolId, _amount, account); linearAcceptedToken.safeTransferFrom(account, address(this), _amount); emit LinearDeposit(_poolId, account, _amount); } /** * @notice Withdraw token from a pool * @param _poolId id of the pool * @param _amount amount to withdraw */ function linearWithdraw(uint256 _poolId, uint128 _amount) external nonReentrant linearValidatePoolById(_poolId) { address account = msg.sender; LinearPoolInfo storage pool = linearPoolInfo[_poolId]; LinearStakingData storage stakingData = linearStakingData[_poolId][ account ]; uint128 lockDuration = pool.lockDuration > 0 ? pool.lockDuration : linearFlexLockDuration; require( block.timestamp >= stakingData.joinTime + lockDuration, "LinearStakingPool: still locked" ); require( stakingData.balance >= _amount, "LinearStakingPool: invalid withdraw amount" ); _linearHarvest(_poolId, account); if (stakingData.reward > 0) { require( linearRewardDistributor != address(0), "LinearStakingPool: invalid reward distributor" ); uint128 reward = stakingData.reward; stakingData.reward = 0; linearAcceptedToken.safeTransferFrom( linearRewardDistributor, account, reward ); emit LinearRewardsHarvested(_poolId, account, reward); } stakingData.balance -= _amount; if (pool.delayDuration == 0) { linearAcceptedToken.safeTransfer(account, _amount); emit LinearWithdraw(_poolId, account, _amount); return; } LinearPendingWithdrawal storage pending = linearPendingWithdrawals[ _poolId ][account]; pending.amount += _amount; pending.applicableAt = block.timestamp.toUint128() + pool.delayDuration; } /** * @notice Claim pending withdrawal * @param _poolId id of the pool */ function linearClaimPendingWithdraw(uint256 _poolId) external nonReentrant linearValidatePoolById(_poolId) { address account = msg.sender; LinearPendingWithdrawal storage pending = linearPendingWithdrawals[ _poolId ][account]; uint128 amount = pending.amount; require(amount > 0, "LinearStakingPool: nothing is currently pending"); require( pending.applicableAt <= block.timestamp, "LinearStakingPool: not released yet" ); delete linearPendingWithdrawals[_poolId][account]; linearAcceptedToken.safeTransfer(account, amount); emit LinearWithdraw(_poolId, account, amount); } /** * @notice Claim reward token from a pool * @param _poolId id of the pool */ function linearClaimReward(uint256 _poolId) external nonReentrant linearValidatePoolById(_poolId) { address account = msg.sender; LinearStakingData storage stakingData = linearStakingData[_poolId][ account ]; _linearHarvest(_poolId, account); if (stakingData.reward > 0) { require( linearRewardDistributor != address(0), "LinearStakingPool: invalid reward distributor" ); uint128 reward = stakingData.reward; stakingData.reward = 0; linearAcceptedToken.safeTransferFrom( linearRewardDistributor, account, reward ); emit LinearRewardsHarvested(_poolId, account, reward); } } /** * @notice Gets number of reward tokens of a user from a pool * @param _poolId id of the pool * @param _account address of a user * @return reward earned reward of a user */ function linearPendingReward(uint256 _poolId, address _account) public view linearValidatePoolById(_poolId) returns (uint128 reward) { LinearPoolInfo storage pool = linearPoolInfo[_poolId]; LinearStakingData storage stakingData = linearStakingData[_poolId][ _account ]; uint128 startTime = stakingData.updatedTime > 0 ? stakingData.updatedTime : block.timestamp.toUint128(); uint128 endTime = block.timestamp.toUint128(); if ( pool.lockDuration > 0 && stakingData.joinTime + pool.lockDuration < block.timestamp ) { endTime = stakingData.joinTime + pool.lockDuration; } uint128 stakedTimeInSeconds = endTime > startTime ? endTime - startTime : 0; uint128 pendingReward = ((stakingData.balance * stakedTimeInSeconds * pool.APR) / ONE_YEAR_IN_SECONDS) / 100; reward = stakingData.reward + pendingReward; } /** * @notice Gets number of deposited tokens in a pool * @param _poolId id of the pool * @param _account address of a user * @return total token deposited in a pool by a user */ function linearBalanceOf(uint256 _poolId, address _account) external view linearValidatePoolById(_poolId) returns (uint128) { return linearStakingData[_poolId][_account].balance; } /** * @notice Update allowance for emergency withdraw * @param _shouldAllow should allow emergency withdraw or not */ function linearSetAllowEmergencyWithdraw(bool _shouldAllow) external onlyOwner { linearAllowEmergencyWithdraw = _shouldAllow; } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. * @param _poolId id of the pool */ function linearEmergencyWithdraw(uint256 _poolId) external nonReentrant linearValidatePoolById(_poolId) { require( linearAllowEmergencyWithdraw, "LinearStakingPool: emergency withdrawal is not allowed yet" ); address account = msg.sender; LinearStakingData storage stakingData = linearStakingData[_poolId][ account ]; require( stakingData.balance > 0, "LinearStakingPool: nothing to withdraw" ); uint128 amount = stakingData.balance; stakingData.balance = 0; stakingData.reward = 0; stakingData.updatedTime = block.timestamp.toUint128(); linearAcceptedToken.safeTransfer(account, amount); emit LinearEmergencyWithdraw(_poolId, account, amount); } function _linearDeposit( uint256 _poolId, uint128 _amount, address account ) internal { LinearPoolInfo storage pool = linearPoolInfo[_poolId]; LinearStakingData storage stakingData = linearStakingData[_poolId][ account ]; require( block.timestamp >= pool.startJoinTime, "LinearStakingPool: pool is not started yet" ); require( block.timestamp <= pool.endJoinTime, "LinearStakingPool: pool is already closed" ); require( stakingData.balance + _amount >= pool.minInvestment, "LinearStakingPool: insufficient amount" ); if (pool.maxInvestment > 0) { require( stakingData.balance + _amount <= pool.maxInvestment, "LinearStakingPool: too large amount" ); } if (pool.cap > 0) { require( pool.totalStaked + _amount <= pool.cap, "LinearStakingPool: pool is full" ); } _linearHarvest(_poolId, account); stakingData.balance += _amount; stakingData.joinTime = block.timestamp.toUint128(); pool.totalStaked += _amount; } function _linearHarvest(uint256 _poolId, address _account) private { LinearStakingData storage stakingData = linearStakingData[_poolId][ _account ]; stakingData.reward = linearPendingReward(_poolId, _account); stakingData.updatedTime = block.timestamp.toUint128(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCastUpgradeable { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; }
View function to see pending rewards on frontend. _pid id of the pool _user the address of the user/
function allocPendingReward(uint256 _pid, address _user) public view allocValidatePoolById(_pid) returns (uint128) { AllocPoolInfo storage pool = allocPoolInfo[_pid]; AllocUserInfo storage user = allocUserInfo[_pid][_user]; uint128 accRewardPerShare = pool.accRewardPerShare; uint128 lpSupply = pool.lpSupply; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint128 multiplier = allocTimeMultiplier( pool.lastRewardBlock, block.number.toUint128() ); uint128 poolReward = (multiplier * allocRewardPerBlock * pool.allocPoint) / totalAllocPoint; accRewardPerShare = accRewardPerShare + ((poolReward * ACCUMULATED_MULTIPLIER) / lpSupply); } return user.pendingReward + (((user.amount * accRewardPerShare) / ACCUMULATED_MULTIPLIER) - user.rewardDebt); }
11,892,668
/** *Submitted for verification at Etherscan.io on 2022-03-26 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: contracts/abc.sol pragma solidity >=0.7.0 <0.9.0; contract StrongDragons is ERC721, Ownable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supply; string public uriPrefix = ""; string public uriSuffix = ".json"; string public hiddenMetadataUri; uint256 public cost = 0.05 ether; uint256 public maxSupply = 10000; uint256 public maxMintAmountPerTx = 10 ; uint256 public maxMintAmount = 150; bool public paused = true; bool public revealed = false; constructor() ERC721("STRONG DRAGONS", "DRGNS") { setHiddenMetadataUri("ipfs://QmUFTrnvXsuRcdyc5XEizFtxHjyXEYzSywrtyZBAnEXdBe/hidden_Dragon_Metadata.json"); } modifier mintCompliance(uint256 _mintAmount) { require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!"); require(balanceOf(msg.sender) < 150, 'You have reached the max wallet limit'); require(_mintAmount <= maxMintAmount, 'transaction exceeds the maximum amount of tokens'); _; } function totalSupply() public view returns (uint256) { return supply.current(); } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); require(msg.value >= cost * _mintAmount, "Insufficient funds!"); _mintLoop(msg.sender, _mintAmount); } function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _mintLoop(_receiver, _mintAmount); } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } function setRevealed(bool _state) public onlyOwner { revealed = _state; } function setCost(uint256 _cost) public onlyOwner { cost = _cost; } function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } function setPaused(bool _state) public onlyOwner { paused = _state; } function withdraw() public onlyOwner { // This will transfer the remaining contract balance to the owner. // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); // ============================================================================= } function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } }
Performs a Solidity function call using a low level `call`. A plain `call` is an unsafe replacement for a function call: use this function instead. If `target` reverts with a revert reason, it is bubbled up by this function (like regular Solidity function calls). Returns the raw returned data. To convert to the expected return value, Requirements: - `target` must be a contract. - calling `target` with `data` must not revert. _Available since v3.1._/
function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); }
8,025,836
./full_match/4/0xC2D1fAC9517544A839D35e67008c76A1839366aA/sources/SampleBEP20Token.sol
Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism. `amount` is then deducted from the caller's allowance. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event./
function transferFrom( address _from, address _to, uint256 _value ) public returns (bool success) { require(_value <= balanceOf[_from]); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; balanceOf[_to] += _value; allowance[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; }
647,276
./full_match/43114/0xc9070B3EFE0aacC5AfB4B31C5DbDCA7C6B4bAAA9/sources/contracts/YieldWolf.sol
updates the deposit fee can only be called by the owner _depositFee new deposit fee in basis points/
function setDepositFee(uint256 _depositFee) external onlyOwner { require(_depositFee <= DEPOSIT_FEE_CAP, 'setDepositFee: CAP_EXCEEDED'); depositFee = _depositFee; emit SetDepositFee(_depositFee); }
4,507,349
// SPDX-License-Identifier: MIT pragma solidity ^0.5.0; contract Marketplace { string public name; uint256 public ticketCount = 0; mapping(uint256 => Ticket) public tickets; struct Ticket { uint256 id; // string imgHash; string name; uint256 price; string startDate; string location; string description; address payable owner; bool purchased; } event TicketCreated( uint256 id, // string imgHash, string name, uint256 price, string startDate, string location, string description, address payable owner, bool purchased ); event TicketPurchased( uint256 id, // string imgHash, string name, uint256 price, string startDate, string location, string description, address payable owner, bool purchased ); constructor() public { name = "Marketplace"; } function createTicket(/*string memory _imgHash,*/ string memory _name, uint256 _price, string memory _startDate, string memory _location, string memory _description) public { // //Validate uploader address exists // require(msg.sender!=address(0)); // //Validate hash exists // require(bytes(_imgHash).length > 0); //Require a valid name require(bytes(_name).length > 0); // Reuire a valid price require(_price > 0); // Require valid date require(bytes(_startDate).length > 0); // Require a valid location require(bytes(_location).length > 0); // Require a valid description require(bytes(_description).length > 0); // Make sure parameters are correct // Increment Ticket count ticketCount++; //Create the ticket tickets[ticketCount] = Ticket( ticketCount, // _imgHash, _name, _price, _startDate, _location, _description, msg.sender, false ); //Trigger an event emit TicketCreated(ticketCount, /*_imgHash,*/ _name, _price, _startDate, _location, _description, msg.sender, false); } function purchaseTicket(uint256 _id) public payable { // Fetch the product Ticket memory _ticket = tickets[_id]; // Fetch the owner address payable _seller = _ticket.owner; // Make sure the ticket has a valid id require(_ticket.id > 0 && _ticket.id <= ticketCount); // Require that there is enough Ether in the transaction require(msg.value >= _ticket.price); // Require that the ticket has not been purchased already require(!_ticket.purchased); // Require that the buyer is not the seller require(_seller != msg.sender); // Transfer ownership to the buyer _ticket.owner = msg.sender; // Mark as purchased _ticket.purchased = true; // Update the product tickets[_id] = _ticket; // Pay the seller by sending them Ether address(_seller).transfer(msg.value); //Trigger an event emit TicketPurchased( ticketCount, // _ticket.imgHash, _ticket.name, _ticket.price, _ticket.startDate, _ticket.location, _ticket.description, msg.sender, true ); } }
Fetch the product Fetch the owner Make sure the ticket has a valid id Require that there is enough Ether in the transaction Require that the ticket has not been purchased already Require that the buyer is not the seller Transfer ownership to the buyer Mark as purchased Update the product Pay the seller by sending them EtherTrigger an event _ticket.imgHash,
function purchaseTicket(uint256 _id) public payable { Ticket memory _ticket = tickets[_id]; address payable _seller = _ticket.owner; require(_ticket.id > 0 && _ticket.id <= ticketCount); require(msg.value >= _ticket.price); require(!_ticket.purchased); require(_seller != msg.sender); _ticket.owner = msg.sender; _ticket.purchased = true; tickets[_id] = _ticket; address(_seller).transfer(msg.value); emit TicketPurchased( ticketCount, _ticket.name, _ticket.price, _ticket.startDate, _ticket.location, _ticket.description, msg.sender, true ); }
13,121,034
./partial_match/56/0xa9eB28df890A88077487eBEF47974527656433E6/sources/MasterPepe.sol
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "PEPE::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "PEPE::delegateBySig: invalid nonce"); require(now <= expiry, "PEPE::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
11,088,554
./full_match/1/0xF76EFB82b079c5e75E4f7503A5eC60297b2EC982/sources/contracts/Base_rogue1.sol
refund defines the conditions for the customer to get a refund if the validator is not delivered and online within a specific amount of itme. The address must match the deposit address, amd the time defined in the deposit function must have elapsed./
function refund(address payable customer) public { require(lockedUntil[msg.sender] < block.timestamp, "time not yet expired"); require(customer == msg.sender, "invalid address"); uint256 payment = _deposits[customer]; _deposits[customer] = 0; customer.transfer(payment); emit Refunded(customer, payment); }
8,460,959
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Helpers/ERC20.sol"; import "./Helpers/SafeMath.sol"; /** * @title PlaypointFactory * @dev PlaypointFactory is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with bnb. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract PlaypointFactory { using SafeMath for uint256; ERC20 public token; address payable public wallet; uint256 public rate; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _token Address of the token being sold */ constructor(uint256 _rate, ERC20 _token) { require(_rate > 0); rate = _rate; wallet = payable(msg.sender); token = _token; } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(uint256 _weiAmount) internal view { require(msg.sender != address(0)); require( _weiAmount >= 5 * 10**16, "Minimum purchase amount is 0.05 BNB!" ); } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(uint256 _tokenAmount) internal { token.transfer(payable(msg.sender), _tokenAmount); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how BNB is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** */ function buyTokens() public payable { uint256 weiAmount = msg.value; _preValidatePurchase(weiAmount); uint256 tokens = _getTokenAmount(weiAmount); _deliverTokens(tokens); emit TokenPurchase(msg.sender, weiAmount, tokens); _forwardFunds(); } function withdrawTokenToWallet(uint256 _amount) public { require(msg.sender == wallet, "Only the wallet can withdraw tokens!"); token.transfer(wallet, _amount); } }
low level token purchase DO NOT OVERRIDE/
function buyTokens() public payable { uint256 weiAmount = msg.value; _preValidatePurchase(weiAmount); uint256 tokens = _getTokenAmount(weiAmount); _deliverTokens(tokens); emit TokenPurchase(msg.sender, weiAmount, tokens); _forwardFunds(); }
5,367,665
pragma solidity ^0.4.25; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } library SafeERC20 { function safeTransfer( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } contract TokenRecoverable is Ownable { using SafeERC20 for ERC20Basic; function recoverTokens(ERC20Basic token, address to, uint256 amount) public onlyOwner { uint256 balance = token.balanceOf(address(this)); require(balance >= amount); token.safeTransfer(to, amount); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } contract ERC820Registry { function getManager(address addr) public view returns(address); function setManager(address addr, address newManager) public; function getInterfaceImplementer(address addr, bytes32 iHash) public constant returns (address); function setInterfaceImplementer(address addr, bytes32 iHash, address implementer) public; } contract ERC820Implementer { ERC820Registry erc820Registry = ERC820Registry(0x991a1bcb077599290d7305493c9A630c20f8b798); function setInterfaceImplementation(string ifaceLabel, address impl) internal { bytes32 ifaceHash = keccak256(abi.encodePacked(ifaceLabel)); erc820Registry.setInterfaceImplementer(this, ifaceHash, impl); } function interfaceAddr(address addr, string ifaceLabel) internal constant returns(address) { bytes32 ifaceHash = keccak256(abi.encodePacked(ifaceLabel)); return erc820Registry.getInterfaceImplementer(addr, ifaceHash); } function delegateManagement(address newManager) internal { erc820Registry.setManager(this, newManager); } } contract ERC20Token { function name() public view returns (string); function symbol() public view returns (string); function decimals() public view returns (uint8); function totalSupply() public view returns (uint256); function balanceOf(address owner) public view returns (uint256); function transfer(address to, uint256 amount) public returns (bool); function transferFrom(address from, address to, uint256 amount) public returns (bool); function approve(address spender, uint256 amount) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } contract ERC777Token { function name() public view returns (string); function symbol() public view returns (string); function totalSupply() public view returns (uint256); function balanceOf(address owner) public view returns (uint256); function granularity() public view returns (uint256); function defaultOperators() public view returns (address[]); function isOperatorFor(address operator, address tokenHolder) public view returns (bool); function authorizeOperator(address operator) public; function revokeOperator(address operator) public; function send(address to, uint256 amount, bytes holderData) public; function operatorSend(address from, address to, uint256 amount, bytes holderData, bytes operatorData) public; function burn(uint256 amount, bytes holderData) public; function operatorBurn(address from, uint256 amount, bytes holderData, bytes operatorData) public; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes holderData, bytes operatorData ); // solhint-disable-next-line separate-by-one-line-in-contract event Minted(address indexed operator, address indexed to, uint256 amount, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes holderData, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } contract ERC777TokensRecipient { function tokensReceived( address operator, address from, address to, uint amount, bytes userData, bytes operatorData ) public; } contract ERC777TokensSender { function tokensToSend( address operator, address from, address to, uint amount, bytes userData, bytes operatorData ) public; } contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public view returns (string) { return mName; } /// @return the symbol of the token function symbol() public view returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public view returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public view returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public view returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } emit AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } emit RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal view returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); emit Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); emit Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } } contract ERC777ERC20BaseToken is ERC20Token, ERC777BaseToken { bool internal mErc20compatible; mapping(address => mapping(address => bool)) internal mAuthorized; mapping(address => mapping(address => uint256)) internal mAllowed; constructor( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators ) internal ERC777BaseToken(_name, _symbol, _granularity, _defaultOperators) { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } /// @notice This modifier is applied to erc20 obsolete methods that are /// implemented only to maintain backwards compatibility. When the erc20 /// compatibility is disabled, this methods will fail. modifier erc20 () { require(mErc20compatible); _; } /// @notice For Backwards compatibility /// @return The decimls of the token. Forced to 18 in ERC777. function decimals() public erc20 view returns (uint8) { return uint8(18); } /// @notice ERC20 backwards compatible transfer. /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transfer(address _to, uint256 _amount) public erc20 returns (bool success) { doSend(msg.sender, msg.sender, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible transferFrom. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { require(_amount <= mAllowed[_from][msg.sender]); // Cannot be after doSend because of tokensReceived re-entry mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount); doSend(msg.sender, _from, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible approve. /// `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf. /// @param _spender The address of the account able to transfer the tokens /// @param _amount The number of tokens to be approved for transfer /// @return `true`, if the approve can't be done, it should fail. function approve(address _spender, uint256 _amount) public erc20 returns (bool success) { mAllowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /// @notice ERC20 backwards compatible allowance. /// This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public erc20 view returns (uint256 remaining) { return mAllowed[_owner][_spender]; } function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { super.doSend(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); if (mErc20compatible) { emit Transfer(_from, _to, _amount); } } function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { super.doBurn(_operator, _tokenHolder, _amount, _holderData, _operatorData); if (mErc20compatible) { emit Transfer(_tokenHolder, 0x0, _amount); } } } /** * @title Eliptic curve signature operations * * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 * */ library ECRecovery { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * @dev and hash the result */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", hash ) ); } } contract FilesFMToken is TokenRecoverable, ERC777ERC20BaseToken { using SafeMath for uint256; using ECRecovery for bytes32; string private constant name_ = "Files.fm Token"; string private constant symbol_ = "FFM"; uint256 private constant granularity_ = 1; mapping(bytes => bool) private signatures; address public tokenMinter; address public tokenBag; bool public throwOnIncompatibleContract = true; bool public burnEnabled = false; bool public transfersEnabled = false; bool public defaultOperatorsComplete = false; event TokenBagChanged(address indexed oldAddress, address indexed newAddress, uint256 balance); event DefaultOperatorAdded(address indexed operator); event DefaultOperatorRemoved(address indexed operator); event DefaultOperatorsCompleted(); /// @notice Constructor to create a token constructor() public ERC777ERC20BaseToken(name_, symbol_, granularity_, new address[](0)) { } modifier canTransfer(address from, address to) { require(transfersEnabled || from == tokenBag || to == tokenBag); _; } modifier canBurn() { require(burnEnabled); _; } modifier hasMintPermission() { require(msg.sender == owner || msg.sender == tokenMinter, "Only owner or token minter can mint tokens"); _; } modifier canManageDefaultOperator() { require(!defaultOperatorsComplete, "Default operator list is not editable"); _; } /// @notice Disables the ERC20 interface. This function can only be called /// by the owner. function disableERC20() public onlyOwner { mErc20compatible = false; setInterfaceImplementation("ERC20Token", 0x0); } /// @notice Re enables the ERC20 interface. This function can only be called /// by the owner. function enableERC20() public onlyOwner { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } function send(address _to, uint256 _amount, bytes _userData) public canTransfer(msg.sender, _to) { super.send(_to, _amount, _userData); } function operatorSend( address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public canTransfer(_from, _to) { super.operatorSend(_from, _to, _amount, _userData, _operatorData); } function transfer(address _to, uint256 _amount) public erc20 canTransfer(msg.sender, _to) returns (bool success) { return super.transfer(_to, _amount); } function transferFrom(address _from, address _to, uint256 _amount) public erc20 canTransfer(_from, _to) returns (bool success) { return super.transferFrom(_from, _to, _amount); } /* -- Mint And Burn Functions (not part of the ERC777 standard, only the Events/tokensReceived call are) -- */ // /// @notice Generates `_amount` tokens to be assigned to `_tokenHolder` /// Sample mint function to showcase the use of the `Minted` event and the logic to notify the recipient. /// @param _tokenHolder The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @param _operatorData Data that will be passed to the recipient as a first transfer function mint(address _tokenHolder, uint256 _amount, bytes _operatorData) public hasMintPermission { doMint(_tokenHolder, _amount, _operatorData); } function mintToken(address _tokenHolder, uint256 _amount) public hasMintPermission { doMint(_tokenHolder, _amount, ""); } function mintTokens(address[] _tokenHolders, uint256[] _amounts) public hasMintPermission { require(_tokenHolders.length > 0 && _tokenHolders.length <= 100); require(_tokenHolders.length == _amounts.length); for (uint256 i = 0; i < _tokenHolders.length; i++) { doMint(_tokenHolders[i], _amounts[i], ""); } } /// @notice Burns `_amount` tokens from `_tokenHolder` /// Sample burn function to showcase the use of the `Burned` event. /// @param _amount The quantity of tokens to burn function burn(uint256 _amount, bytes _holderData) public canBurn { super.burn(_amount, _holderData); } function permitTransfers() public onlyOwner { require(!transfersEnabled); transfersEnabled = true; } function setThrowOnIncompatibleContract(bool _throwOnIncompatibleContract) public onlyOwner { throwOnIncompatibleContract = _throwOnIncompatibleContract; } function permitBurning(bool _enable) public onlyOwner { burnEnabled = _enable; } function completeDefaultOperators() public onlyOwner canManageDefaultOperator { defaultOperatorsComplete = true; emit DefaultOperatorsCompleted(); } function setTokenMinter(address _tokenMinter) public onlyOwner { tokenMinter = _tokenMinter; } function setTokenBag(address _tokenBag) public onlyOwner { uint256 balance = mBalances[tokenBag]; if (_tokenBag == address(0)) { require(balance == 0, "Token Bag balance must be 0"); } else if (balance > 0) { doSend(msg.sender, tokenBag, _tokenBag, balance, "", "", false); } emit TokenBagChanged(tokenBag, _tokenBag, balance); tokenBag = _tokenBag; } function renounceOwnership() public onlyOwner { tokenMinter = address(0); super.renounceOwnership(); } function transferOwnership(address _newOwner) public onlyOwner { tokenMinter = address(0); super.transferOwnership(_newOwner); } /// @notice sends tokens using signature to recover token sender /// @param _to the address of the recepient /// @param _amount tokens to send /// @param _fee amound of tokens which goes to msg.sender /// @param _data arbitrary user data /// @param _nonce value to protect from replay attacks /// @param _sig concatenated r,s,v values /// @return `true` if the token transfer is success, otherwise should fail function sendWithSignature(address _to, uint256 _amount, uint256 _fee, bytes _data, uint256 _nonce, bytes _sig) public returns (bool) { doSendWithSignature(_to, _amount, _fee, _data, _nonce, _sig, true); return true; } /// @notice transfers tokens in ERC20 compatible way using signature to recover token sender /// @param _to the address of the recepient /// @param _amount tokens to transfer /// @param _fee amound of tokens which goes to msg.sender /// @param _data arbitrary user data /// @param _nonce value to protect from replay attacks /// @param _sig concatenated r,s,v values /// @return `true` if the token transfer is success, otherwise should fail function transferWithSignature(address _to, uint256 _amount, uint256 _fee, bytes _data, uint256 _nonce, bytes _sig) public returns (bool) { doSendWithSignature(_to, _amount, _fee, _data, _nonce, _sig, false); return true; } function addDefaultOperator(address _operator) public onlyOwner canManageDefaultOperator { require(_operator != address(0), "Default operator cannot be set to address 0x0"); require(mIsDefaultOperator[_operator] == false, "This is already default operator"); mDefaultOperators.push(_operator); mIsDefaultOperator[_operator] = true; emit DefaultOperatorAdded(_operator); } function removeDefaultOperator(address _operator) public onlyOwner canManageDefaultOperator { require(mIsDefaultOperator[_operator] == true, "This operator is not default operator"); uint256 operatorIndex; uint256 count = mDefaultOperators.length; for (operatorIndex = 0; operatorIndex < count; operatorIndex++) { if (mDefaultOperators[operatorIndex] == _operator) { break; } } if (operatorIndex + 1 < count) { mDefaultOperators[operatorIndex] = mDefaultOperators[count - 1]; } mDefaultOperators.length = mDefaultOperators.length - 1; mIsDefaultOperator[_operator] = false; emit DefaultOperatorRemoved(_operator); } function doMint(address _tokenHolder, uint256 _amount, bytes _operatorData) private { require(_tokenHolder != address(0), "Cannot mint to address 0x0"); requireMultiple(_amount); mTotalSupply = mTotalSupply.add(_amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].add(_amount); callRecipient(msg.sender, address(0), _tokenHolder, _amount, "", _operatorData, false); emit Minted(msg.sender, _tokenHolder, _amount, _operatorData); if (mErc20compatible) { emit Transfer(address(0), _tokenHolder, _amount); } } function doSendWithSignature(address _to, uint256 _amount, uint256 _fee, bytes _data, uint256 _nonce, bytes _sig, bool _preventLocking) private { require(_to != address(0)); require(_to != address(this)); // token contract does not accept own tokens require(signatures[_sig] == false); signatures[_sig] = true; bytes memory packed; if (_preventLocking) { packed = abi.encodePacked(address(this), _to, _amount, _fee, _data, _nonce); } else { packed = abi.encodePacked(address(this), _to, _amount, _fee, _data, _nonce, "ERC20Compat"); } address signer = keccak256(packed) .toEthSignedMessageHash() .recover(_sig); // same security considerations as in Ethereum TX require(signer != address(0)); require(transfersEnabled || signer == tokenBag || _to == tokenBag); uint256 total = _amount.add(_fee); require(mBalances[signer] >= total); doSend(msg.sender, signer, _to, _amount, _data, "", _preventLocking); if (_fee > 0) { doSend(msg.sender, signer, msg.sender, _fee, "", "", _preventLocking); } } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (throwOnIncompatibleContract && _preventLocking) { require(isRegularAddress(_to)); } } }
Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. _operator address to check if it has the right to manage the tokens _tokenHolder address which holds the tokens to be managed return `true` if `_operator` is authorized for `_tokenHolder`
function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); }
12,637,614
./partial_match/1/0xf7752941CB46785a51b23859DeB36fdf1e18aF4d/sources/Implementation.sol
Reward committer Dev rewards
function initialize() initializer public { incentivize(msg.sender, Constants.getAdvanceIncentive()); }
4,355,034
// pragma solidity ^0.4.25; pragma solidity ^0.8.10; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false uint256 private numFundedAirlines; // To store count of funded airlines uint256 private numRegisteredAirlines; // To store count of registered airlines uint256 private constant MINIMUM_FUNDING_AMOUNT = 10 ether; struct Airline{ uint256 airlineFunds; address[] registrationVotes; bool isRegistered; bool isFunded; //Once registered and fees paid, the airline will become active } mapping(address => Airline) private airlines; //To store all airline address to airline mapping struct Insurance{ address airlineAddress; mapping(address => uint256) insuredPassengerPremiums; address[] insuredPassengers; bool isPaid; } mapping(bytes32 => Insurance) private insurances; //To store all flightKey to Insurance mapping mapping(address => uint256) passengerWallets; //To store insurance amounts to be given to insured passengers mapping(address => bool) private authorizedCallers; //To store authorized callers /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( ) public { contractOwner = msg.sender; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool mode) external requireContractOwner{ // require(mode != operational, 'Status already set to desired mode'); operational = mode; } function numberOfFundedAirlines() external requireIsOperational returns(uint256){ return numFundedAirlines; } function numberOfRegisteredAirlines() external requireIsOperational returns(uint256){ return numRegisteredAirlines; } function isAirlineRegistered(address airline) external requireIsOperational returns(bool){ return airlines[airline].isRegistered; } function isAirlineFunded(address airline) external requireIsOperational returns(bool){ return airlines[airline].isFunded; } function getVotesForAirline(address airline) external requireIsOperational returns(uint256){ return airlines[airline].registrationVotes.length; } function voteToRegisterAirline(address airline,address voter) external requireIsOperational{ require(msg.sender!=airline, 'Airline cannot vote to register itself'); bool callerHasAlreadyVoted = false; for(uint i=0; i<airlines[airline].registrationVotes.length; i++){ if(airlines[airline].registrationVotes[i]==voter){ callerHasAlreadyVoted = true; break; } } require(!callerHasAlreadyVoted, 'Caller has already voted to register this Airline'); airlines[airline].registrationVotes.push(voter); } function authorizeCaller(address caller) external requireIsOperational requireContractOwner{ authorizedCallers[caller] = true; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline (address airline) external{ airlines[airline].isRegistered = true; numRegisteredAirlines = numRegisteredAirlines.add(1); } /** * @dev Buy insurance for a flight * */ function buy(address payable passenger, bytes32 flightKey, address airlineAddress) external payable requireIsOperational{ //Add the premium paid by the passenger to airline funds uint256 premiumAmount = msg.value; airlines[airlineAddress].airlineFunds = airlines[airlineAddress].airlineFunds.add(premiumAmount); insurances[flightKey].insuredPassengerPremiums[passenger] = insurances[flightKey].insuredPassengerPremiums[passenger].add(premiumAmount); insurances[flightKey].insuredPassengers.push(passenger); } /** * @dev Credits payouts to insurees */ function creditInsurees(address airline, bytes32 flightKey)external requireIsOperational{ require(!insurances[flightKey].isPaid,'This insurance has been credited to insurees already'); for(uint i=0; i<insurances[flightKey].insuredPassengers.length; i++){ //Insurance Amount to be credited uint256 insuranceAmount= insurances[flightKey].insuredPassengerPremiums[insurances[flightKey].insuredPassengers[i]].mul(3).div(2); //First Debit airlines[airline].airlineFunds = airlines[airline].airlineFunds.sub(insuranceAmount); //Then Credit passengerWallets[insurances[flightKey].insuredPassengers[i]] = passengerWallets[insurances[flightKey].insuredPassengers[i]].add(insuranceAmount); } insurances[flightKey].isPaid = true; } /** * @dev Transfers eligible payout funds to insuree * */ function pay (address payable passenger) external requireIsOperational{ require(passengerWallets[passenger] > 0 ,'Passenger does not have any funds in their walelt to withdraw'); //First Debit uint256 amountToTransfer = passengerWallets[passenger]; passengerWallets[passenger] = 0; //Then Credit passenger.transfer(amountToTransfer); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund(address airline) public payable requireIsOperational{ uint fundingAmount = msg.value; airlines[airline].airlineFunds = airlines[airline].airlineFunds.add(fundingAmount); airlines[airline].isFunded = true; numFundedAirlines = numFundedAirlines.add(1); } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ // fallback() external payable {} }
Sets contract operations on/off When operational mode is disabled, all write transactions except for this one will fail/ require(mode != operational, 'Status already set to desired mode');
function setOperatingStatus(bool mode) external requireContractOwner{ operational = mode; }
7,212,338
./full_match/80001/0x4eAA7acf7245d51AeDc78Ef2A9A97B5068602139/sources/contracts/BattleResolutionLibrary.sol
Player 2 attacks, player 1 defends
function handleDefendAttack( StructsLibrary.BattleData storage battle, StructsLibrary.CharacterProxy storage proxyA, StructsLibrary.CharacterProxy storage proxyB ) internal returns ( uint256[2] memory damageDealt, address[2] memory damagedPlayers ) { uint256 damageB = (proxyB.stats.attack * proxyB.attackMultiplier) / 1000; if (proxyA.stats.defense < damageB) { uint256 damage = damageB - proxyA.stats.defense; proxyA.stats.health = proxyA.stats.health > damage ? proxyA.stats.health - damage : 0; damagedPlayers[0] = battle.players[0]; damageDealt[1] = damage; } proxyB.stats.mana -= 3; return (damageDealt, damagedPlayers); }
9,479,696
pragma solidity ^0.5.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract ERC20 { function transfer(address _to, uint256 _value) public; function transferFrom(address _from, address _to, uint256 _value) public returns(bool success); } contract EthTokenToSmthSwaps { using SafeMath for uint; address public owner; uint256 SafeTime = 1 hours; // atomic swap timeOut struct Swap { address token; address payable targetWallet; bytes32 secret; bytes20 secretHash; uint256 createdAt; uint256 balance; } // ETH Owner => BTC Owner => Swap mapping(address => mapping(address => Swap)) public swaps; // ETH Owner => BTC Owner => secretHash => Swap // mapping(address => mapping(address => mapping(bytes20 => Swap))) public swaps; constructor () public { owner = msg.sender; } event CreateSwap(address token, address _buyer, address _seller, uint256 _value, bytes20 _secretHash, uint256 createdAt); // ETH Owner creates Swap with secretHash // ETH Owner make token deposit function createSwap(bytes20 _secretHash, address payable _participantAddress, uint256 _value, address _token) public { require(_value > 0); require(swaps[msg.sender][_participantAddress].balance == uint256(0)); require(ERC20(_token).transferFrom(msg.sender, address(this), _value)); swaps[msg.sender][_participantAddress] = Swap( _token, _participantAddress, bytes32(0), _secretHash, now, _value ); emit CreateSwap(_token, _participantAddress, msg.sender, _value, _secretHash, now); } // ETH Owner creates Swap with secretHash and targetWallet // ETH Owner make token deposit function createSwapTarget(bytes20 _secretHash, address payable _participantAddress, address payable _targetWallet, uint256 _value, address _token) public { require(_value > 0); require(swaps[msg.sender][_participantAddress].balance == uint256(0)); require(ERC20(_token).transferFrom(msg.sender, address(this), _value)); swaps[msg.sender][_participantAddress] = Swap( _token, _targetWallet, bytes32(0), _secretHash, now, _value ); emit CreateSwap(_token, _participantAddress, msg.sender, _value, _secretHash, now); } function getBalance(address _ownerAddress) public view returns (uint256) { return swaps[_ownerAddress][msg.sender].balance; } event Withdraw(address _buyer, address _seller, bytes20 _secretHash, uint256 withdrawnAt); // Get target wallet (buyer check) function getTargetWallet(address tokenOwnerAddress) public view returns (address) { return swaps[tokenOwnerAddress][msg.sender].targetWallet; } // BTC Owner withdraw money and adds secret key to swap // BTC Owner receive +1 reputation function withdraw(bytes32 _secret, address _ownerAddress) public { Swap memory swap = swaps[_ownerAddress][msg.sender]; require(swap.secretHash == ripemd160(abi.encodePacked(_secret))); require(swap.balance > uint256(0)); require(swap.createdAt.add(SafeTime) > now); ERC20(swap.token).transfer(swap.targetWallet, swap.balance); swaps[_ownerAddress][msg.sender].balance = 0; swaps[_ownerAddress][msg.sender].secret = _secret; emit Withdraw(msg.sender, _ownerAddress, swap.secretHash, now); } // Token Owner withdraw money when participan no money for gas and adds secret key to swap // BTC Owner receive +1 reputation... may be function withdrawNoMoney(bytes32 _secret, address participantAddress) public { Swap memory swap = swaps[msg.sender][participantAddress]; require(swap.secretHash == ripemd160(abi.encodePacked(_secret))); require(swap.balance > uint256(0)); require(swap.createdAt.add(SafeTime) > now); ERC20(swap.token).transfer(swap.targetWallet, swap.balance); swaps[msg.sender][participantAddress].balance = 0; swaps[msg.sender][participantAddress].secret = _secret; emit Withdraw(participantAddress, msg.sender, swap.secretHash, now); } // BTC Owner withdraw money and adds secret key to swap // BTC Owner receive +1 reputation function withdrawOther(bytes32 _secret, address _ownerAddress, address participantAddress) public { Swap memory swap = swaps[_ownerAddress][participantAddress]; require(swap.secretHash == ripemd160(abi.encodePacked(_secret))); require(swap.balance > uint256(0)); require(swap.createdAt.add(SafeTime) > now); ERC20(swap.token).transfer(swap.targetWallet, swap.balance); swaps[_ownerAddress][participantAddress].balance = 0; swaps[_ownerAddress][participantAddress].secret = _secret; emit Withdraw(participantAddress, _ownerAddress, swap.secretHash, now); } // ETH Owner receive secret function getSecret(address _participantAddress) public view returns (bytes32) { return swaps[msg.sender][_participantAddress].secret; } event Refund(address _buyer, address _seller, bytes20 _secretHash); // ETH Owner refund money // BTC Owner gets -1 reputation function refund(address _participantAddress) public { Swap memory swap = swaps[msg.sender][_participantAddress]; require(swap.balance > uint256(0)); require(swap.createdAt.add(SafeTime) < now); ERC20(swap.token).transfer(msg.sender, swap.balance); clean(msg.sender, _participantAddress); emit Refund(_participantAddress, msg.sender, swap.secretHash); } function clean(address _ownerAddress, address _participantAddress) internal { delete swaps[_ownerAddress][_participantAddress]; } }
ETH Owner creates Swap with secretHash ETH Owner make token deposit
function createSwap(bytes20 _secretHash, address payable _participantAddress, uint256 _value, address _token) public { require(_value > 0); require(swaps[msg.sender][_participantAddress].balance == uint256(0)); require(ERC20(_token).transferFrom(msg.sender, address(this), _value)); swaps[msg.sender][_participantAddress] = Swap( _token, _participantAddress, bytes32(0), _secretHash, now, _value ); emit CreateSwap(_token, _participantAddress, msg.sender, _value, _secretHash, now); }
5,527,139
./full_match/80001/0x1cb7B639F0aE9a1843D20E5131196Dc9940F6CF4/sources/contracts/base/ERC721Drop.sol
/// Runs before every `claim` function call.
Internal functions function _beforeClaim( address, uint256 _quantity, address, uint256, AllowlistProof calldata, bytes memory ) internal view virtual override { if (_currentIndex + _quantity > nextTokenIdToLazyMint) { revert("Not enough minted tokens"); } }
839,089
./full_match/80001/0x9dd6d73789796eB95d4202949A1d1D35127e06D7/sources/contracts/Marstacktest.sol
verifica se ja existe o stakeholder
function _isStakeholder(address _address) internal view returns(bool, uint256) { for (uint256 s = 0; s < _stakeholders.length; s += 1){ if (_address == _stakeholders[s]) return (true, s); } return (false, 0); }
5,620,451
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'C4F' Coins4Favors contracts // // contracts for C4FEscrow and C4FToken Crowdsale // // (c) C4F Ltd Hongkong 2018 // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // 'C4F' FavorEscrow contract // // Escrow contract for favor request // allows to reserve tokens till a favor is completed, cancelled or arbitrated // handles requester and provider interaction, payout, cancellation and // arbitration if needed. // // (c) C4F Ltd Hongkong 2018 // ---------------------------------------------------------------------------- contract C4FEscrow { using SafeMath for uint; address public owner; address public requester; address public provider; uint256 public startTime; uint256 public closeTime; uint256 public deadline; uint256 public C4FID; uint8 public status; bool public requesterLocked; bool public providerLocked; bool public providerCompleted; bool public requesterDisputed; bool public providerDisputed; uint8 public arbitrationCosts; event ownerChanged(address oldOwner, address newOwner); event deadlineChanged(uint256 oldDeadline, uint256 newDeadline); event favorDisputed(address disputer); event favorUndisputed(address undisputer); event providerSet(address provider); event providerLockSet(bool lockstat); event providerCompletedSet(bool completed_status); event requesterLockSet(bool lockstat); event favorCompleted(address provider, uint256 tokenspaid); event favorCancelled(uint256 tokensreturned); event tokenOfferChanged(uint256 oldValue, uint256 newValue); event escrowArbitrated(address provider, uint256 coinsreturned, uint256 fee); // ---------------------------------------------------------------------------- // modifiers used in this contract to restrict function calls // ---------------------------------------------------------------------------- modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyRequester { require(msg.sender == requester); _; } modifier onlyProvider { require(msg.sender == provider); _; } modifier onlyOwnerOrRequester { require((msg.sender == owner) || (msg.sender == requester)) ; _; } modifier onlyOwnerOrProvider { require((msg.sender == owner) || (msg.sender == provider)) ; _; } modifier onlyProviderOrRequester { require((msg.sender == requester) || (msg.sender == provider)) ; _; } // ---------------------------------------------------------------------------- // Constructor // ---------------------------------------------------------------------------- function C4FEscrow(address newOwner, uint256 ID, address req, uint256 deadl, uint8 arbCostPercent) public { owner = newOwner; // main contract C4FID = ID; requester = req; provider = address(0); startTime = now; deadline = deadl; status = 1; // 1 = open, 2 = cancelled, 3=closed, 4=arbitrated arbitrationCosts = arbCostPercent; requesterLocked = false; providerLocked = false; providerCompleted = false; requesterDisputed = false; providerDisputed = false; } // ---------------------------------------------------------------------------- // returns the owner of the Escrow contract. This is the main C4F Token contract // ---------------------------------------------------------------------------- function getOwner() public view returns (address ownner) { return owner; } function setOwner(address newOwner) public onlyOwner returns (bool success) { require(newOwner != address(0)); ownerChanged(owner,newOwner); owner = newOwner; return true; } // ---------------------------------------------------------------------------- // returns the Requester of the Escrow contract. This is the originator of the favor request // ---------------------------------------------------------------------------- function getRequester() public view returns (address req) { return requester; } // ---------------------------------------------------------------------------- // returns the Provider of the Escrow contract. This is the favor provider // ---------------------------------------------------------------------------- function getProvider() public view returns (address prov) { return provider; } // ---------------------------------------------------------------------------- // returns the startTime of the Escrow contract which is the time it was created // ---------------------------------------------------------------------------- function getStartTime() public view returns (uint256 st) { return startTime; } // ---------------------------------------------------------------------------- // returns the Deadline of the Escrow contract by which completion is needed // Reqeuster can cancel the Escrow 12 hours after deadline expires if favor // is not marked as completed by provider // ---------------------------------------------------------------------------- function getDeadline() public view returns (uint256 actDeadline) { actDeadline = deadline; return actDeadline; } // ---------------------------------------------------------------------------- // adjusts the Deadline of the Escrow contract by which completion is needed // Reqeuster can only change this till a provider accepted (locked) the contract // ---------------------------------------------------------------------------- function changeDeadline(uint newDeadline) public onlyRequester returns (bool success) { // deadline can only be changed if not locked by provider and not completed require ((!providerLocked) && (!providerDisputed) && (!providerCompleted) && (status==1)); deadlineChanged(newDeadline, deadline); deadline = newDeadline; return true; } // ---------------------------------------------------------------------------- // returns the status of the Escrow contract // ---------------------------------------------------------------------------- function getStatus() public view returns (uint8 s) { return status; } // ---------------------------------------------------------------------------- // Initiates dispute of the Escrow contract. Once requester or provider disputeFavor // because they cannot agree on completion, the C4F system can arbitrate the Escrow // based on the internal juror system. // ---------------------------------------------------------------------------- function disputeFavor() public onlyProviderOrRequester returns (bool success) { if(msg.sender == requester) { requesterDisputed = true; } if(msg.sender == provider) { providerDisputed = true; providerLocked = true; } favorDisputed(msg.sender); return true; } // ---------------------------------------------------------------------------- // Allows to take back a dispute on the Escrow if conflict has been resolved // ---------------------------------------------------------------------------- function undisputeFavor() public onlyProviderOrRequester returns (bool success) { if(msg.sender == requester) { requesterDisputed = false; } if(msg.sender == provider) { providerDisputed = false; } favorUndisputed(msg.sender); return true; } // ---------------------------------------------------------------------------- // allows to set the address of the provider for the Favor // this can be done by the requester or the C4F system // once the provider accepts, the providerLock flag disables changes to this // ---------------------------------------------------------------------------- function setProvider(address newProvider) public onlyOwnerOrRequester returns (bool success) { // can only change provider if not locked by current provider require(!providerLocked); require(!requesterLocked); provider = newProvider; providerSet(provider); return true; } // ---------------------------------------------------------------------------- // switches the ProviderLock on or off. Once provider lock is switched on, // it means the provider has formally accepted the offer and changes are // blocked // ---------------------------------------------------------------------------- function setProviderLock(bool lock) public onlyOwnerOrProvider returns (bool res) { providerLocked = lock; providerLockSet(lock); return providerLocked; } // ---------------------------------------------------------------------------- // allows to set Favor to completed from Provider view, indicating that // provider sess Favor as delivered // ---------------------------------------------------------------------------- function setProviderCompleted(bool c) public onlyOwnerOrProvider returns (bool res) { providerCompleted = c; providerCompletedSet(c); return c; } // ---------------------------------------------------------------------------- // allows to set requester lock, indicating requester accepted favor provider // ---------------------------------------------------------------------------- function setRequesterLock(bool lock) public onlyOwnerOrRequester returns (bool res) { requesterLocked = lock; requesterLockSet(lock); return requesterLocked; } function getRequesterLock() public onlyOwnerOrRequester view returns (bool res) { res = requesterLocked; return res; } // ---------------------------------------------------------------------------- // allows the C4F system to change the status of an Escrow contract // ---------------------------------------------------------------------------- function setStatus(uint8 newStatus) public onlyOwner returns (uint8 stat) { status = newStatus; stat = status; return stat; } // ---------------------------------------------------------------------------- // returns the current Token value of the escrow for competing the favor // this is the token balance of the escrow contract in the main contract // ---------------------------------------------------------------------------- function getTokenValue() public view returns (uint256 tokens) { C4FToken C4F = C4FToken(owner); return C4F.balanceOf(address(this)); } // ---------------------------------------------------------------------------- // completes the favor Escrow and pays out the tokens minus the commission fee // ---------------------------------------------------------------------------- function completeFavor() public onlyRequester returns (bool success) { // check if provider has been set require(provider != address(0)); // payout tokens to provider with commission uint256 actTokenvalue = getTokenValue(); C4FToken C4F = C4FToken(owner); if(!C4F.transferWithCommission(provider, actTokenvalue)) revert(); closeTime = now; status = 3; favorCompleted(provider,actTokenvalue); return true; } // ---------------------------------------------------------------------------- // this function cancels a favor request on behalf of the requester // only possible as long as no provider accepted the contract or 12 hours // after the deadline if the provider did not indicate completion or disputed // ---------------------------------------------------------------------------- function cancelFavor() public onlyRequester returns (bool success) { // cannot cancel if locked by provider unless deadline expired by 12 hours and not completed/disputed require((!providerLocked) || ((now > deadline.add(12*3600)) && (!providerCompleted) && (!providerDisputed))); // cannot cancel after completed or arbitrated require(status==1); // send tokens back to requester uint256 actTokenvalue = getTokenValue(); C4FToken C4F = C4FToken(owner); if(!C4F.transfer(requester,actTokenvalue)) revert(); closeTime = now; status = 2; favorCancelled(actTokenvalue); return true; } // ---------------------------------------------------------------------------- // allows the favor originator to reduce the token offer // This can only be done until a provider has accepted (locked) the favor request // ---------------------------------------------------------------------------- function changeTokenOffer(uint256 newOffer) public onlyRequester returns (bool success) { // cannot change if locked by provider require((!providerLocked) && (!providerDisputed) && (!providerCompleted)); // cannot change if cancelled, closed or arbitrated require(status==1); // only use for reducing tokens (to increase simply transfer tokens to contract) uint256 actTokenvalue = getTokenValue(); require(newOffer < actTokenvalue); // cannot set to 0, use cancel to do that require(newOffer > 0); // pay back tokens to reach new offer level C4FToken C4F = C4FToken(owner); if(!C4F.transfer(requester, actTokenvalue.sub(newOffer))) revert(); tokenOfferChanged(actTokenvalue,newOffer); return true; } // ---------------------------------------------------------------------------- // arbitration can be done by the C4F system once requester or provider have // disputed the favor contract. An independent juror system on the platform // will vote on the outcome and define a split of the tokens between the two // parties. The jurors get a percentage which is preset in the contratct for // the arbitration // ---------------------------------------------------------------------------- function arbitrateC4FContract(uint8 percentReturned) public onlyOwner returns (bool success) { // can only arbitrate if one of the two parties has disputed require((providerDisputed) || (requesterDisputed)); // C4F System owner can arbitrate and provide a split of tokens between 0-100% uint256 actTokens = getTokenValue(); // calc. arbitration fee based on percent costs uint256 arbitrationTokens = actTokens.mul(arbitrationCosts); arbitrationTokens = arbitrationTokens.div(100); // subtract these from the tokens to be distributed between requester and provider actTokens = actTokens.sub(arbitrationTokens); // now split the tokens up using provided percentage uint256 requesterTokens = actTokens.mul(percentReturned); requesterTokens = requesterTokens.div(100); // actTokens to hold what gets forwarded to provider actTokens = actTokens.sub(requesterTokens); // distribute the Tokens C4FToken C4F = C4FToken(owner); // arbitration tokens go to commissiontarget of master contract address commissionTarget = C4F.getCommissionTarget(); // requester gets refunded his split if(!C4F.transfer(requester, requesterTokens)) revert(); // provider gets his split of tokens if(!C4F.transfer(provider, actTokens)) revert(); // arbitration fee to system for distribution if(!C4F.transfer(commissionTarget, arbitrationTokens)) revert(); // set status & closeTime status = 4; closeTime = now; success = true; escrowArbitrated(provider,requesterTokens,arbitrationTokens); return success; } } // ---------------------------------------------------------------------------- // 'C4F' 'Coins4Favors FavorCoin contract // // Symbol : C4F // Name : FavorCoin // Total supply: 100,000,000,000.000000000000000000 // Decimals : 18 // // includes the crowdsale price, PreICO bonus structure, limits on sellable tokens // function to pause sale, commission fee transfer and favorcontract management // // (c) C4F Ltd Hongkong 2018 // ---------------------------------------------------------------------------- contract C4FToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint8 public _crowdsalePaused; uint public _totalSupply; uint public _salesprice; uint public _endOfICO; uint public _endOfPreICO; uint public _beginOfICO; uint public _bonusTime1; uint public _bonusTime2; uint public _bonusRatio1; uint public _bonusRatio2; uint public _percentSoldInPreICO; uint public _maxTokenSoldPreICO; uint public _percentSoldInICO; uint public _maxTokenSoldICO; uint public _total_sold; uint public _commission; uint8 public _arbitrationPercent; address public _commissionTarget; uint public _minimumContribution; address[] EscrowAddresses; uint public _escrowIndex; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => uint) whitelisted_amount; mapping(address => bool) C4FEscrowContracts; event newEscrowCreated(uint ID, address contractAddress, address requester); event ICOStartSet(uint256 starttime); event ICOEndSet(uint256 endtime); event PreICOEndSet(uint256 endtime); event BonusTime1Set(uint256 bonustime); event BonusTime2Set(uint256 bonustime); event accountWhitelisted(address account, uint256 limit); event crowdsalePaused(bool paused); event crowdsaleResumed(bool resumed); event commissionSet(uint256 commission); event commissionTargetSet(address target); event arbitrationPctSet(uint8 arbpercent); event contractOwnerChanged(address escrowcontract, address newOwner); event contractProviderChanged(address C4Fcontract, address provider); event contractArbitrated(address C4Fcontract, uint8 percentSplit); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function C4FToken() public { symbol = "C4F"; name = "C4F FavorCoins"; decimals = 18; _totalSupply = 100000000000 * 10**uint(decimals); _salesprice = 2000000; // C4Fs per 1 Eth _minimumContribution = 0.05 * 10**18; // minimum amount is 0.05 Ether _endOfICO = 1532908800; // end of ICO is 30.07.18 _beginOfICO = 1526342400; // begin is 15.05.18 _bonusRatio1 = 110; // 10% Bonus in second week of PreICO _bonusRatio2 = 125; // 25% Bonus in first week of PreICO _bonusTime1 = 1527638400; // prior to 30.05.18 add bonusRatio1 _bonusTime2 = 1526947200; // prior to 22.05.18 add bonusRatio2 _endOfPreICO = 1527811200; // Pre ICO ends 01.06.2018 _percentSoldInPreICO = 10; // we only offer 10% of total Supply during PreICO _maxTokenSoldPreICO = _totalSupply.mul(_percentSoldInPreICO); _maxTokenSoldPreICO = _maxTokenSoldPreICO.div(100); _percentSoldInICO = 60; // in addition to 10% sold in PreICO, 60% sold in ICO _maxTokenSoldICO = _totalSupply.mul(_percentSoldInPreICO.add(_percentSoldInICO)); _maxTokenSoldICO = _maxTokenSoldICO.div(100); _total_sold = 0; // total coins sold _commission = 0; // no comission on transfers _commissionTarget = owner; // default any commission goes to the owner of the contract _arbitrationPercent = 10; // default costs for arbitration of an escrow contract // is transferred to escrow contract at time of creation and kept there _crowdsalePaused = 0; balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // notLocked: ensure no coins are moved by owners prior to end of ICO // ------------------------------------------------------------------------ modifier notLocked { require((msg.sender == owner) || (now >= _endOfICO)); _; } // ------------------------------------------------------------------------ // onlyDuringICO: FavorCoins can only be bought via contract during ICO // ------------------------------------------------------------------------ modifier onlyDuringICO { require((now >= _beginOfICO) && (now <= _endOfICO)); _; } // ------------------------------------------------------------------------ // notPaused: ability to stop crowdsale if problems occur // ------------------------------------------------------------------------ modifier notPaused { require(_crowdsalePaused == 0); _; } // ------------------------------------------------------------------------ // set ICO and PRE ICO Dates // ------------------------------------------------------------------------ function setICOStart(uint ICOdate) public onlyOwner returns (bool success) { _beginOfICO = ICOdate; ICOStartSet(_beginOfICO); return true; } function setICOEnd(uint ICOdate) public onlyOwner returns (bool success) { _endOfICO = ICOdate; ICOEndSet(_endOfICO); return true; } function setPreICOEnd(uint ICOdate) public onlyOwner returns (bool success) { _endOfPreICO = ICOdate; PreICOEndSet(_endOfPreICO); return true; } function setBonusDate1(uint ICOdate) public onlyOwner returns (bool success) { _bonusTime1 = ICOdate; BonusTime1Set(_bonusTime1); return true; } function setBonusDate2(uint ICOdate) public onlyOwner returns (bool success) { _bonusTime2 = ICOdate; BonusTime2Set(_bonusTime2); return true; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Whitelist address up to maximum spending (AML and KYC) // ------------------------------------------------------------------------ function whitelistAccount(address account, uint limit) public onlyOwner { whitelisted_amount[account] = limit*10**18; accountWhitelisted(account,limit); } // ------------------------------------------------------------------------ // return maximum remaining whitelisted amount for account // ------------------------------------------------------------------------ function getWhitelistLimit(address account) public constant returns (uint limit) { return whitelisted_amount[account]; } // ------------------------------------------------------------------------ // Pause crowdsale in case of any problems // ------------------------------------------------------------------------ function pauseCrowdsale() public onlyOwner returns (bool success) { _crowdsalePaused = 1; crowdsalePaused(true); return true; } function resumeCrowdsale() public onlyOwner returns (bool success) { _crowdsalePaused = 0; crowdsaleResumed(true); return true; } // ------------------------------------------------------------------------ // Commission can be added later to a percentage of the transferred // C4F tokens for operating costs of the system. Percentage is capped at 2% // ------------------------------------------------------------------------ function setCommission(uint comm) public onlyOwner returns (bool success) { require(comm < 200); // we allow a maximum of 2% commission _commission = comm; commissionSet(comm); return true; } function setArbitrationPercentage(uint8 arbitPct) public onlyOwner returns (bool success) { require(arbitPct <= 15); // we allow a maximum of 15% arbitration costs _arbitrationPercent = arbitPct; arbitrationPctSet(_arbitrationPercent); return true; } function setCommissionTarget(address ct) public onlyOwner returns (bool success) { _commissionTarget = ct; commissionTargetSet(_commissionTarget); return true; } function getCommissionTarget() public view returns (address ct) { ct = _commissionTarget; return ct; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // - users cannot transfer C4Fs prior to close of ICO // - only owner can transfer anytime to do airdrops, etc. // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public notLocked notPaused returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // this function will be used by the C4F app to charge a Commission // on transfers later // ------------------------------------------------------------------------ function transferWithCommission(address to, uint tokens) public notLocked notPaused returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); // split tokens using commission Percentage uint comTokens = tokens.mul(_commission); comTokens = comTokens.div(10000); // adjust balances balances[to] = balances[to].add(tokens.sub(comTokens)); balances[_commissionTarget] = balances[_commissionTarget].add(comTokens); // trigger events Transfer(msg.sender, to, tokens.sub(comTokens)); Transfer(msg.sender, _commissionTarget, comTokens); return true; } // ------------------------------------------------------------------------ // TransferInternal handles Transfer of Tokens from Owner during ICO and Pre-ICO // ------------------------------------------------------------------------ function transferInternal(address to, uint tokens) private returns (bool success) { balances[owner] = balances[owner].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public notLocked notPaused returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // not possivbe before end of ICO // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public notLocked notPaused returns (bool success) { // check allowance is high enough require(allowed[from][msg.sender] >= tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // startEscrow FavorContract // starts an escrow contract and transfers the tokens into the contract // ------------------------------------------------------------------------ function startFavorEscrow(uint256 ID, uint256 deadl, uint tokens) public notLocked returns (address C4FFavorContractAddr) { // check if sufficient coins available require(balanceOf(msg.sender) >= tokens); // create contract address newFavor = new C4FEscrow(address(this), ID, msg.sender, deadl, _arbitrationPercent); // add to list of C4FEscrowContratcs EscrowAddresses.push(newFavor); C4FEscrowContracts[newFavor] = true; // transfer tokens to contract if(!transfer(newFavor, tokens)) revert(); C4FFavorContractAddr = newFavor; newEscrowCreated(ID, newFavor, msg.sender); return C4FFavorContractAddr; } function isFavorEscrow(uint id, address c4fes) public view returns (bool res) { if(EscrowAddresses[id] == c4fes) { res = true; } else { res = false; } return res; } function getEscrowCount() public view returns (uint) { return EscrowAddresses.length; } function getEscrowAddress(uint ind) public view returns(address esa) { require (ind <= EscrowAddresses.length); esa = EscrowAddresses[ind]; return esa; } // use this function to allow C4F System to adjust owner of C4FEscrows function setC4FContractOwner(address C4Fcontract, address newOwner) public onlyOwner returns (bool success) { require(C4FEscrowContracts[C4Fcontract]); C4FEscrow c4fec = C4FEscrow(C4Fcontract); // call setProvider from there if(!c4fec.setOwner(newOwner)) revert(); contractOwnerChanged(C4Fcontract,newOwner); return true; } // use this function to allow C4F System to adjust provider of C4F Favorcontract function setC4FContractProvider(address C4Fcontract, address provider) public onlyOwner returns (bool success) { // ensure this is a C4FEscrowContract initiated by C4F system require(C4FEscrowContracts[C4Fcontract]); C4FEscrow c4fec = C4FEscrow(C4Fcontract); // call setProvider from there if(!c4fec.setProvider(provider)) revert(); contractProviderChanged(C4Fcontract, provider); return true; } // use this function to allow C4F System to adjust providerLock function setC4FContractProviderLock(address C4Fcontract, bool lock) public onlyOwner returns (bool res) { // ensure this is a C4FEscrowContract initiated by C4F system require(C4FEscrowContracts[C4Fcontract]); C4FEscrow c4fec = C4FEscrow(C4Fcontract); // call setProviderLock from there res = c4fec.setProviderLock(lock); return res; } // use this function to allow C4F System to adjust providerCompleted status function setC4FContractProviderCompleted(address C4Fcontract, bool completed) public onlyOwner returns (bool res) { // ensure this is a C4FEscrowContract initiated by C4F system require(C4FEscrowContracts[C4Fcontract]); C4FEscrow c4fec = C4FEscrow(C4Fcontract); // call setProviderCompleted from there res = c4fec.setProviderCompleted(completed); return res; } // use this function to allow C4F System to adjust providerLock function setC4FContractRequesterLock(address C4Fcontract, bool lock) public onlyOwner returns (bool res) { // ensure this is a C4FEscrowContract initiated by C4F system require(C4FEscrowContracts[C4Fcontract]); C4FEscrow c4fec = C4FEscrow(C4Fcontract); // call setRequesterLock from there res = c4fec.setRequesterLock(lock); return res; } function setC4FContractStatus(address C4Fcontract, uint8 newStatus) public onlyOwner returns (uint8 s) { // ensure this is a C4FEscrowContract initiated by C4F system require(C4FEscrowContracts[C4Fcontract]); C4FEscrow c4fec = C4FEscrow(C4Fcontract); // call setStatus from there s = c4fec.setStatus(newStatus); return s; } function arbitrateC4FContract(address C4Fcontract, uint8 percentSplit) public onlyOwner returns (bool success) { // ensure this is a C4FEscrowContract initiated by C4F system require(C4FEscrowContracts[C4Fcontract]); C4FEscrow c4fec = C4FEscrow(C4Fcontract); // call arbitration if(!c4fec.arbitrateC4FContract(percentSplit)) revert(); contractArbitrated(C4Fcontract, percentSplit); return true; } // ------------------------------------------------------------------------ // Convert to C4Fs using salesprice and bonus period and forward Eth to owner // ------------------------------------------------------------------------ function () public onlyDuringICO notPaused payable { // check bonus ratio uint bonusratio = 100; // check for second week bonus if(now <= _bonusTime1) { bonusratio = _bonusRatio1; } // check for first week bonus if(now <= _bonusTime2) { bonusratio = _bonusRatio2; } // minimum contribution met ? require (msg.value >= _minimumContribution); // send C4F tokens back to sender based on Ether received if (msg.value > 0) { // check if whitelisted and sufficient contribution left (AML & KYC) if(!(whitelisted_amount[msg.sender] >= msg.value)) revert(); // reduce remaining contribution limit whitelisted_amount[msg.sender] = whitelisted_amount[msg.sender].sub(msg.value); // determine amount of C4Fs uint256 token_amount = msg.value.mul(_salesprice); token_amount = token_amount.mul(bonusratio); token_amount = token_amount.div(100); uint256 new_total = _total_sold.add(token_amount); // check if PreICO volume sold off if(now <= _endOfPreICO){ // check if we are above the limit with this transfer, then bounce if(new_total > _maxTokenSoldPreICO) revert(); } // check if exceeding total ICO sale tokens if(new_total > _maxTokenSoldICO) revert(); // transfer tokens from owner account to sender if(!transferInternal(msg.sender, token_amount)) revert(); _total_sold = new_total; // forward received ether to owner account if (!owner.send(msg.value)) revert(); // also reverts the transfer. } } }
---------------------------------------------------------------------------- Allows to take back a dispute on the Escrow if conflict has been resolved ----------------------------------------------------------------------------
function undisputeFavor() public onlyProviderOrRequester returns (bool success) { if(msg.sender == requester) { requesterDisputed = false; } if(msg.sender == provider) { providerDisputed = false; } favorUndisputed(msg.sender); return true; }
1,501,475
//Address: 0x00416B9d728069eDB0cEb04bC2b203fA7336d1F1 //Contract name: AversafeSeedCrowdsale //Balance: 0 Ether //Verification Date: 11/29/2017 //Transacion Count: 36 // CODE STARTS HERE /* Copyright 2017 Cofound.it. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.13; contract ReentrancyHandlingContract { bool locked; modifier noReentrancy() { require(!locked); locked = true; _; locked = false; } } contract Owned { address public owner; address public newOwner; function Owned() public { owner = msg.sender; } modifier onlyOwner { assert(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != owner); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = 0x0; } event OwnerUpdate(address _prevOwner, address _newOwner); } contract PriorityPassInterface { function getAccountLimit(address _accountAddress) public constant returns (uint); function getAccountActivity(address _accountAddress) public constant returns (bool); } contract ERC20TokenInterface { function totalSupply() public constant returns (uint256 _totalSupply); function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract SeedCrowdsaleContract is ReentrancyHandlingContract, Owned { struct ContributorData { uint contributionAmount; } mapping(address => ContributorData) public contributorList; uint public nextContributorIndex; mapping(uint => address) public contributorIndexes; state public crowdsaleState = state.pendingStart; enum state { pendingStart, priorityPass, openedPriorityPass, crowdsaleEnded } uint public presaleStartTime; uint public presaleUnlimitedStartTime; uint public crowdsaleEndedTime; event PresaleStarted(uint blocktime); event PresaleUnlimitedStarted(uint blocktime); event CrowdsaleEnded(uint blocktime); event ErrorSendingETH(address to, uint amount); event MinCapReached(uint blocktime); event MaxCapReached(uint blocktime); event ContributionMade(address indexed contributor, uint amount); PriorityPassInterface priorityPassContract = PriorityPassInterface(0x0); uint public minCap; uint public maxP1Cap; uint public maxCap; uint public ethRaised; address public multisigAddress; uint nextContributorToClaim; mapping(address => bool) hasClaimedEthWhenFail; // // Unnamed function that runs when eth is sent to the contract // @payable // function() noReentrancy payable public { require(msg.value != 0); // Throw if value is 0 require(crowdsaleState != state.crowdsaleEnded); // Check if crowdsale has ended bool stateChanged = checkCrowdsaleState(); // Check blocks time and calibrate crowdsale state if (crowdsaleState == state.priorityPass) { if (priorityPassContract.getAccountActivity(msg.sender)) { // Check if contributor is in priorityPass processTransaction(msg.sender, msg.value); // Process transaction and issue tokens } else { refundTransaction(stateChanged); // Set state and return funds or throw } } else if (crowdsaleState == state.openedPriorityPass) { if (priorityPassContract.getAccountActivity(msg.sender)) { // Check if contributor is in priorityPass processTransaction(msg.sender, msg.value); // Process transaction and issue tokens } else { refundTransaction(stateChanged); // Set state and return funds or throw } } else { refundTransaction(stateChanged); // Set state and return funds or throw } } // // @internal checks crowdsale state and emits events it // @returns boolean // function checkCrowdsaleState() internal returns (bool) { if (ethRaised == maxCap && crowdsaleState != state.crowdsaleEnded) { // Check if max cap is reached crowdsaleState = state.crowdsaleEnded; MaxCapReached(block.timestamp); // Close the crowdsale CrowdsaleEnded(block.timestamp); // Raise event return true; } if (block.timestamp > presaleStartTime && block.timestamp <= presaleUnlimitedStartTime) { // Check if we are in presale phase if (crowdsaleState != state.priorityPass) { // Check if state needs to be changed crowdsaleState = state.priorityPass; // Set new state PresaleStarted(block.timestamp); // Raise event return true; } } else if (block.timestamp > presaleUnlimitedStartTime && block.timestamp <= crowdsaleEndedTime) { // Check if we are in presale unlimited phase if (crowdsaleState != state.openedPriorityPass) { // Check if state needs to be changed crowdsaleState = state.openedPriorityPass; // Set new state PresaleUnlimitedStarted(block.timestamp); // Raise event return true; } } else { if (crowdsaleState != state.crowdsaleEnded && block.timestamp > crowdsaleEndedTime) {// Check if crowdsale is over crowdsaleState = state.crowdsaleEnded; // Set new state CrowdsaleEnded(block.timestamp); // Raise event return true; } } return false; } // // @internal determines if return eth or throw according to changing state // @param _stateChanged boolean message about state change // function refundTransaction(bool _stateChanged) internal { if (_stateChanged) { msg.sender.transfer(msg.value); } else { revert(); } } // // Getter to calculate how much user can contribute // @param _contributor address of the contributor // function calculateMaxContribution(address _contributor) constant public returns (uint maxContribution) { uint maxContrib; if (crowdsaleState == state.priorityPass) { // Check if we are in priority pass maxContrib = priorityPassContract.getAccountLimit(_contributor) - contributorList[_contributor].contributionAmount; if (maxContrib > (maxP1Cap - ethRaised)) { // Check if max contribution is more that max cap maxContrib = maxP1Cap - ethRaised; // Alter max cap } } else { maxContrib = maxCap - ethRaised; // Alter max cap } return maxContrib; } // // Return if there is overflow of contributed eth // @internal processes transactions // @param _contributor address of an contributor // @param _amount contributed amount // function processTransaction(address _contributor, uint _amount) internal { uint maxContribution = calculateMaxContribution(_contributor); // Calculate max users contribution uint contributionAmount = _amount; uint returnAmount = 0; if (maxContribution < _amount) { // Check if max contribution is lower than _amount sent contributionAmount = maxContribution; // Set that user contributes his maximum alowed contribution returnAmount = _amount - maxContribution; // Calculate how much he must get back } if (ethRaised + contributionAmount >= minCap && minCap > ethRaised) { MinCapReached(block.timestamp); } if (contributorList[_contributor].contributionAmount == 0) { // Check if contributor has already contributed contributorList[_contributor].contributionAmount = contributionAmount; // Set their contribution contributorIndexes[nextContributorIndex] = _contributor; // Set contributors index nextContributorIndex++; } else { contributorList[_contributor].contributionAmount += contributionAmount; // Add contribution amount to existing contributor } ethRaised += contributionAmount; // Add to eth raised ContributionMade(msg.sender, contributionAmount); // Raise event about contribution if (returnAmount != 0) { _contributor.transfer(returnAmount); // Return overflow of ether } } // // Recovers ERC20 tokens other than eth that are send to this address // @owner refunds the erc20 tokens // @param _tokenAddress address of the erc20 token // @param _to address to where tokens should be send to // @param _amount amount of tokens to refund // function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner public { ERC20TokenInterface(_tokenAddress).transfer(_to, _amount); } // // withdrawEth when minimum cap is reached // @owner sets contributions to withdraw // function withdrawEth() onlyOwner public { require(this.balance != 0); require(ethRaised >= minCap); pendingEthWithdrawal = this.balance; } uint public pendingEthWithdrawal; // // pulls the funds that were set to send with calling of // withdrawEth when minimum cap is reached // @multisig pulls the contributions to self // function pullBalance() public { require(msg.sender == multisigAddress); require(pendingEthWithdrawal > 0); multisigAddress.transfer(pendingEthWithdrawal); pendingEthWithdrawal = 0; } // // Owner can batch return contributors contributions(eth) // @owner returns contributions // @param _numberOfReturns number of returns to do in one transaction // function batchReturnEthIfFailed(uint _numberOfReturns) onlyOwner public { require(block.timestamp > crowdsaleEndedTime && ethRaised < minCap); // Check if crowdsale has failed address currentParticipantAddress; uint contribution; for (uint cnt = 0; cnt < _numberOfReturns; cnt++) { currentParticipantAddress = contributorIndexes[nextContributorToClaim]; // Get next unclaimed participant if (currentParticipantAddress == 0x0) { return; // Check if all the participants were compensated } if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if participant has already claimed contribution = contributorList[currentParticipantAddress].contributionAmount; // Get contribution of participant hasClaimedEthWhenFail[currentParticipantAddress] = true; // Set that he has claimed if (!currentParticipantAddress.send(contribution)) { // Refund eth ErrorSendingETH(currentParticipantAddress, contribution); // If there is an issue raise event for manual recovery } } nextContributorToClaim += 1; // Repeat } } // // If there were any issue with refund owner can withdraw eth at the end for manual recovery // @owner withdraws remaining funds // function withdrawRemainingBalanceForManualRecovery() onlyOwner public { require(this.balance != 0); // Check if there are any eth to claim require(block.timestamp > crowdsaleEndedTime); // Check if crowdsale is over require(contributorIndexes[nextContributorToClaim] == 0x0); // Check if all the users were refunded multisigAddress.transfer(this.balance); // Withdraw to multisig for manual processing } // // Owner can set multisig address for crowdsale // @owner sets an address where funds will go // @param _newAddress // function setMultisigAddress(address _newAddress) onlyOwner public { multisigAddress = _newAddress; } // // Setter for the whitelist contract // @owner sets address of whitelist contract // @param address // function setPriorityPassContract(address _newAddress) onlyOwner public { priorityPassContract = PriorityPassInterface(_newAddress); } // // Getter for the whitelist contract // @returns white list contract address // function priorityPassContractAddress() constant public returns (address) { return address(priorityPassContract); } // // Before crowdsale starts owner can calibrate time of crowdsale stages // @owner sends new times for the sale // @param _presaleStartTime timestamp for sale limited start // @param _presaleUnlimitedStartTime timestamp for sale unlimited // @param _crowdsaleEndedTime timestamp for ending sale // function setCrowdsaleTimes(uint _presaleStartTime, uint _presaleUnlimitedStartTime, uint _crowdsaleEndedTime) onlyOwner public { require(crowdsaleState == state.pendingStart); // Check if crowdsale has started require(_presaleStartTime != 0); // Check if any value is 0 require(_presaleStartTime < _presaleUnlimitedStartTime); // Check if presaleUnlimitedStartTime is set properly require(_presaleUnlimitedStartTime != 0); // Check if any value is 0 require(_presaleUnlimitedStartTime < _crowdsaleEndedTime); // Check if crowdsaleEndedTime is set properly require(_crowdsaleEndedTime != 0); // Check if any value is 0 presaleStartTime = _presaleStartTime; presaleUnlimitedStartTime = _presaleUnlimitedStartTime; crowdsaleEndedTime = _crowdsaleEndedTime; } } contract AversafeSeedCrowdsale is SeedCrowdsaleContract { function AversafeSeedCrowdsale() { presaleStartTime = 1512032400; presaleUnlimitedStartTime = 1512063000; crowdsaleEndedTime = 1512140400; minCap = 451 ether; maxP1Cap = 802 ether; maxCap = 891 ether; } }
Unnamed function that runs when eth is sent to the contract @payable
function() noReentrancy payable public { if (crowdsaleState == state.priorityPass) { } }
1,003,004
// SPDX-License-Identifier: None // All rights reserved. @2022 /* __ ___ _ _ _____ _ _ \ \ / / | (_) | / ____| | | | | \ \ /\ / /| |__ _| |_ ___| | _ _| |__ ___| | ___ ___ ___ \ \/ \/ / | '_ \| | __/ _ \ | | | | | '_ \ / _ \ |/ _ \/ __/ __| \ /\ / | | | | | || __/ |___| |_| | |_) | __/ | __/\__ \__ \ \/ \/ |_| |_|_|\__\___|\_____\__,_|_.__/ \___|_|\___||___/___/ */ // File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/interfaces/IERC165.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts/interfaces/IERC2981.sol // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981 is IERC165 { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/Cubeless.sol pragma solidity ^0.8.7; abstract contract ERC2981Collection is IERC2981 { // ERC165 // _setRoyalties(address,uint256) => 0x40a04a5a // royaltyInfo(uint256,uint256) => 0x2a55205a // ERC2981Collection => 0x6af56a00 address private royaltyAddress; uint256 private royaltyPercent; // Set to be internal function _setRoyalties // _setRoyalties(address,uint256) => 0x40a04a5a function _setRoyalties(address _receiver, uint256 _percentage) internal { royaltyAddress = _receiver; royaltyPercent = _percentage; } // Override for royaltyInfo(uint256, uint256) // royaltyInfo(uint256,uint256) => 0x2a55205a /* function royaltyInfo( uint256 _tokenId, uint256 _salePrice ) external view override(IERC2981) virtual returns ( address receiver, uint256 royaltyAmount ) { receiver = royaltyAddress; // This sets percentages by price * percentage / 100 royaltyAmount = _salePrice * royaltyPercent / 100; } */ } /// owner: 𝗪𝗛𝗜𝗧𝗘𝗖𝗨𝗕𝗘𝗟𝗘𝗦𝗦 - 𝗦𝗬𝗗𝗡𝗘𝗬 - 𝗔𝗨𝗦𝗧𝗥𝗔𝗟𝗜𝗔 /// author: pamuk.eth /// White Cubeless Pty Ltd is a blockchain technology company registered in Australia. All rights reserved by White Cubeless Pty Ltd. @2022 /// Live Version - /** * @dev Heavily customized ERC721 supporting, * * - Multiple drop management * - Contingent transactions * - Reservation * - Owner mint * - URI recycling * - Merkletree Presale * - Drop-Wise Royalties * - PublicSale * - 3 Way Balance of Powers */ contract WhiteCubeless is ERC721Enumerable,ERC2981Collection { //𝗩𝗔𝗥𝗜𝗔𝗕𝗟𝗘 𝗗𝗘𝗖𝗟𝗔𝗥𝗔𝗧𝗜𝗢𝗡𝗦: //𝗘𝗩𝗘𝗡𝗧𝗦 /// @dev emitted after mint event Mint(address indexed _to, uint256 indexed _tokenId, uint256 indexed _artworkId); /// @dev emitted after burn event Burn( uint256 indexed _tokenId, uint256 indexed _artworkId); /// @dev freezes metadata for marketplaces event PermanentURI( string _value, uint256 indexed _id); /// @dev emitted after artwork adeed event ArtworkAdded( string uri, uint256 _ArtworkId,uint256 _Limit); //𝗚𝗟𝗢𝗕𝗔𝗟 uint256 constant public ONE_MILLION = 1_000_000; //𝗩𝗘𝗥𝗦𝗜𝗢𝗡𝗜𝗡𝗚 /// @dev this is to make sure any tokenID generated by WhiteCubeless is unique even the contract is different. uint256 constant public WhiteCubelessGalleryVersion = 1; /// @dev assign first ID uint256 public nextartworkId = WhiteCubelessGalleryVersion*ONE_MILLION; //𝗚𝗔𝗟𝗟𝗘𝗥𝗬 𝗘𝗗𝗜𝗧𝗜𝗢𝗡𝗦 /// @dev drop struct struct Artwork { string artworkBaseIpfsURI; // 'ipfs://CID/' address royaltyReceiver; // default assigned in init uint256 minted; // already minted + reserved uint256 count; // minted + reserved + burned uint256 artworkLimit; // max limit uint256 royaltiesInBP; // default assigned in init uint256 artworkPrice; // init assignment, can change later uint256 reserved; // count of reserved bool locked; // once locked nobody can change royalty, URI and other ctirical info, locking is irreversible bool paused; // pause for minting bool presale; // init assignment uint256[] available_list; // generated in init for URI recycling [1,2,3] - [0,2,3] } mapping(uint256 => Artwork) internal artworks; mapping(uint256 => bool) internal artworkCheck; mapping(uint256 => uint256) internal tokenIdToArtworkId; mapping(uint256 => uint256) internal tokenIdToIpfsHash; mapping(uint256 => uint256[]) internal artworkIdToTokenIds; mapping (bytes32 => uint256) internal whiteListLimits; mapping (uint256 => bool) public paidWithCard; mapping (uint256 => uint256) public paidDate; mapping (uint256 => bool) public burnDisabled; mapping (uint256 => bool) public isBurned; //𝗣𝗥𝗜𝗩𝗜𝗟𝗘𝗚𝗘𝗦 mapping(address => bool) public isOperator; mapping(address => bool) public isGalleryReserver; address public admin; address public gateKeeperOne; address public gateKeeperTwo; address public defaultRoyaltyReceiver; bytes32 public root; bool public gateKeeperOneAllowMinting=false; bool public gateKeeperTwoAllowMinting=false; bool public gateKeeperOneAppointed=false; bool public gateKeeperTwoAppointed=false; bool public gateKeeperOneChangeAdmin=false; bool public gateKeeperTwoChangeAdmin=false; //𝗥𝗢𝗬𝗔𝗟𝗧𝗜𝗘𝗦 uint256 public defaultRoyaltiesInBP = 800; // 8% uint256 public MINT_HARD_LIMIT=10; // cannot mint more than 10 uint256 public WHITELIST_PER_ACCOUNT_LIMIT=5; // each whitelisted account can get 5 pieces before the whitelist reset uint256 public currentMappingVersion; // resettable mapping uint256 public DAY_LIMIT=90; // cannot burn a credit card sale after this limit //𝗠𝗢𝗗𝗜𝗙𝗜𝗘𝗥𝗦 /// @dev checks if the tokenId exists modifier onlyValidTokenId(uint256 _tokenId) { require(_exists(_tokenId)); _; } /// @dev checks if transaction is direct or from a contract modifier onlyAccounts () { require(msg.sender == tx.origin); _; } /// @dev checks the lock status of the artwork modifier onlyUnlocked(uint256 _artworkId) { require(!artworks[_artworkId].locked); _; } /// @dev checks if the minting is paused or not modifier onlyUnPaused(uint256 _artworkId) { require(!artworks[_artworkId].paused); _; } /// @dev only called by admin modifier onlyAdmin() { require(msg.sender == admin); _; } /// @dev only called by admin and operator modifier onlyOperator() { require(isOperator[msg.sender] || msg.sender==admin ); _; } /// @dev only called by admin and operator and reserver modifier onlyGalleryReserver() { // checks if the msg sender is reserver or not require((isGalleryReserver[msg.sender]) || (isOperator[msg.sender]) || (msg.sender==admin)); _; } /// @dev only called by GateKeeperOne modifier onlyGateKeeperOne() { require(gateKeeperOneAppointed); require(msg.sender == gateKeeperOne); _; } /// @dev only called by GateKeeperTwo modifier onlyGateKeeperTwo() { require(gateKeeperTwoAppointed); require(msg.sender == gateKeeperTwo); _; } /// @dev only called by GateKeeperTwo and GateKeeperOne, makes sure they are appointed as well. modifier onlyGateKeeper() { // checks if the msg sender is gatekeeper or not require((msg.sender == gateKeeperOne) || (msg.sender == gateKeeperTwo)); require(gateKeeperTwoAppointed); require(gateKeeperOneAppointed); _; } constructor(string memory _tokenName, string memory _tokenSymbol, bytes32 merkleroot) ERC721(_tokenName, _tokenSymbol) { admin = msg.sender; root = merkleroot; //gatekeepers are admin in the initial deployment gateKeeperOne=msg.sender; gateKeeperTwo=msg.sender; //minting is toggled to true gateKeeperOneAllowMinting=true; gateKeeperTwoAllowMinting=true; //gatekeepers can change admin if they have unanymous decision gateKeeperOneChangeAdmin=false; gateKeeperTwoChangeAdmin=false; defaultRoyaltyReceiver=msg.sender; //𝗔𝗙𝗧𝗘𝗥 𝗗𝗘𝗣𝗟𝗢𝗬 𝗧𝗢𝗗𝗢: // 1- Appoint GateKeeper - Keep in Mind Admin Can Only Appoint a GateKeeper Once } // 𝗔𝗗𝗠𝗜𝗡 𝗣𝗥𝗜𝗩𝗜𝗟𝗔𝗚𝗘𝗦 /// @dev change admin to a new account function changeAdmin(address _address) onlyAdmin public { admin = _address; } /// @dev adds Operator which can carry daily hot wallet duties - admin only function addOperator(address _address) onlyAdmin public { isOperator[_address] = true; } /// @dev remove privilages - Admin only function removeOperator(address _address) onlyAdmin public { isOperator[_address] = false; } /// @dev add Gallery Reserver can only reserve artwork - Operator function addGalleryReserver(address _address) onlyOperator public { isGalleryReserver[_address] = true; } /// @dev remove privilages - Operator function removeGalleryReserver(address _address) onlyOperator public { isGalleryReserver[_address] = false; } /// @dev GAtekeepers can stop minting, minting is on by default, has to be appointed before first minting function appointGateKeeperOne(address _address) onlyAdmin public { require (gateKeeperOneAppointed== false); gateKeeperOne= _address; gateKeeperOneAppointed=true; } /// @dev GAtekeepers can stop minting, minting is on by default, has to be appointed before first minting function appointGateKeeperTwo(address _address) onlyAdmin public { require (gateKeeperTwoAppointed== false); gateKeeperTwo= _address; gateKeeperTwoAppointed=true; } /// @dev Admin can withdraw ETH to admin account function withdrawAll() public onlyAdmin { uint256 balance = address(this).balance; require(balance > 0); _withdraw(admin, balance); } /// @dev withdraw function function _withdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success); } //𝗚𝗔𝗧𝗘𝗞𝗘𝗘𝗣𝗘𝗥 𝗣𝗥𝗜𝗩𝗜𝗟𝗘𝗚𝗘𝗦 /// @dev Start/Stop Minting, On by default function gateKeeperOneToggleMinting(bool toggle_bool) onlyGateKeeperOne public { gateKeeperOneAllowMinting= toggle_bool; } /// @dev Start/Stop Minting, On by default function gateKeeperTwoToggleMinting(bool toggle_bool) onlyGateKeeperTwo public { gateKeeperTwoAllowMinting= toggle_bool; } /// @dev only Gatekeeper can change itself function gateKeeperOneChangeAddress(address _address) onlyGateKeeperOne public { gateKeeperOne= _address; } /// @dev only Gatekeeper can change itself function gateKeeperTwoChangeAddress(address _address) onlyGateKeeperTwo public { gateKeeperTwo= _address; } /// @dev initiate admin recovery, true to vote to change admin function gateKeeperOneToggleAdminChange(bool toggle_bool) onlyGateKeeperOne public { gateKeeperOneChangeAdmin= toggle_bool; } /// @dev initiate admin recovery, true to vote to change admin function gateKeeperTwoToggleAdminChange(bool toggle_bool) onlyGateKeeperTwo public { gateKeeperTwoChangeAdmin= toggle_bool; } /// @dev if both admin change votes are true, this funtion assigns a new admin function gateKeeperAdminOverride(address _address) onlyGateKeeper public { //gatekeepers can change admin if they agree to do so require(gateKeeperTwoChangeAdmin,"1"); require(gateKeeperOneChangeAdmin,"2"); gateKeeperTwoChangeAdmin=false; gateKeeperOneChangeAdmin=false; admin = _address; } //𝗢𝗣𝗘𝗥𝗔𝗧𝗜𝗢𝗡𝗔𝗟 𝗪𝗛𝗜𝗧𝗘𝗟𝗜𝗦𝗧𝗘𝗗 𝗙𝗨𝗡𝗖𝗧𝗜𝗢𝗡𝗦 /// @dev change multiple mint per artwork function updateMintHardLimit(uint256 _hardlimit) onlyOperator public { MINT_HARD_LIMIT = _hardlimit; } /// @dev freeze metadata of the multiple tokens if neccesary, contact info@whitecubeless.com if you need Frozen badge in marketplaces function freezeMetadataList(uint256[] memory _tokenIds) onlyOperator public { require (_tokenIds.length < 20, "1"); for (uint i; i<_tokenIds.length;) { uint256 tokenId=_tokenIds[i]; require(_exists(tokenId), "2"); emit PermanentURI(tokenURI(tokenId),tokenId); unchecked { ++i ;} } } /// @dev changes the royalty receiver, only applicable for new artworks function changeDefaultRoyaltyReceiver(address _address) onlyOperator public { defaultRoyaltyReceiver = _address; } /// @dev merkleroot for presales, only one root at a time function setMerkleRoot(bytes32 merkleroot) onlyOperator public { root = merkleroot; } /// @dev max tokens a whitelisted account can mint function setWhitelistPerAccount(uint256 maximum_per_account) onlyOperator public { WHITELIST_PER_ACCOUNT_LIMIT = maximum_per_account; } /// @dev after day_limit, contract can't burn transferred tokens function setCCDayLimit(uint256 day_limit) onlyOperator public { require(day_limit<=90); DAY_LIMIT = day_limit; } /// @dev multiple disables remote burning for tokens, immediately, triggered manually when payment is cleared function disableMultipleCreditCardBurn(uint256[] memory _tokenIds, uint256 check_len) onlyOperator public { uint256 q1=_tokenIds.length; require(q1==check_len); for (uint i; i < check_len;) { disableCreditCardBurn(_tokenIds[i]); unchecked { ++i ;} } } /// @dev disables remote burning for tokens, immediately, triggered when payment is cleared, contact info@whitecubeless.com to secure your token if purchased via traditional methods function disableCreditCardBurn(uint _tokenId) onlyOperator public { burnDisabled[_tokenId]=true; } /// @dev add multiple artworks function addMultipleArtwork(uint256[] memory _artworkLimits,uint256[] memory _prices,string[] calldata _artworkBaseIpfsURIs,bool[] memory _presales,uint256 len_check) onlyOperator public { uint256 q2=_artworkLimits.length; uint256 q3=_prices.length; uint256 q4=_artworkBaseIpfsURIs.length; uint256 q5=_presales.length; require(q2==len_check,"2"); require(q3==len_check,"3"); require(q4==len_check,"4"); require(q5==len_check,"5"); for (uint i; i < len_check;) { addArtwork( _artworkLimits[i],_prices[i], _artworkBaseIpfsURIs[i],_presales[i]); unchecked { ++i ;} } } /// @dev add artwork , once added cannot be undone function addArtwork(uint256 _artworkLimit,uint256 _price, string calldata _artworkBaseIpfsURI,bool presale) onlyOperator public { uint256 artworkId = nextartworkId; require(artworkCheck[artworkId]==false,"1"); artworks[artworkId].artworkLimit = _artworkLimit; artworks[artworkId].artworkPrice=_price; artworkCheck[artworkId]=true; // artworks[artworkId].royaltyReceiver=defaultRoyaltyReceiver; artworks[artworkId].royaltiesInBP=defaultRoyaltiesInBP; artworks[artworkId].presale=presale; artworks[artworkId].minted=0; artworks[artworkId].locked=false; artworks[artworkId].artworkBaseIpfsURI = _artworkBaseIpfsURI; artworks[artworkId].available_list=new uint[](_artworkLimit); for (uint i; i < _artworkLimit;) { artworks[artworkId].available_list[i]=i+1; unchecked { ++i ;} } emit ArtworkAdded( _artworkBaseIpfsURI, artworkId,_artworkLimit); nextartworkId = nextartworkId+1; } /// @dev locks an artwork for editing, manually triggered after edition is sold out function updateArtworkLock(uint256 _artworkId,bool lock_bool) onlyOperator onlyUnlocked(_artworkId) public { //when locked, nobody can unlock therefore the whole structure is frozen artworks[_artworkId].locked = lock_bool; } /// @dev pauses artwork for minting function updateArtworkPause(uint256 _artworkId,bool pause_bool) onlyOperator public { //when locked, nobody can unlock therefore the whole structure is frozen artworks[_artworkId].paused = pause_bool; } /// @dev multiple IPFS change in case there is a problem with the IPFS supplied in init, cannot be used after locking function updateMultipleArtworkBaseIpfsURI(uint256[] calldata _artworkIds,string[] calldata _artworkBaseIpfsURIs, uint256 check_len) onlyOperator public { uint256 q1=_artworkBaseIpfsURIs.length; uint256 q2=_artworkIds.length; require(q1==check_len,"1"); require(q2==check_len,"2"); for (uint i; i < check_len;) { updateArtworkBaseIpfsURI(_artworkIds[i], _artworkBaseIpfsURIs[i]); unchecked { ++i ;} } } /// @dev IPFS change in case there is a problem with the IPFS supplied in init, cannot be used after locking function updateArtworkBaseIpfsURI(uint256 _artworkId, string calldata _artworkBaseIpfsURI) onlyOperator onlyUnlocked(_artworkId) public { artworks[_artworkId].artworkBaseIpfsURI = _artworkBaseIpfsURI; } /// @dev multiple price change in case there is a problem with the price supplied in init, cannot be used after locking function updateMultipleArtworkPrice(uint256[] calldata _artworkIds,uint256[] calldata _prices, uint256 check_len) onlyOperator public { uint256 q1=_prices.length; uint256 q2=_artworkIds.length; require(q1==check_len,"1"); require(q2==check_len,"2"); for (uint i ; i < check_len; ) { updateArtworkPrice(_artworkIds[i], _prices[i]); unchecked { ++i ;} } } /// @dev price change in case there is a problem with the price supplied in init, cannot be used after locking function updateArtworkPrice(uint256 _artworkId, uint256 _price) onlyOperator onlyUnlocked(_artworkId) public { artworks[_artworkId].artworkPrice = _price; } /// @dev enable presale for an artwork on the fly function updateArtworkPresale(uint256 _artworkId, bool _presaleBool) onlyOperator onlyUnlocked(_artworkId) public { artworks[_artworkId].presale = _presaleBool; } /// @dev multiple change URI extension that comes after ipfs://{CID}/, last resort if there is a sequencing problem after recycling, cannot be done after lock function overrideMultipleTokenIPFSHash(uint256[] calldata _newHashs , uint256[] calldata _tokenIds, uint256 check_len) onlyOperator public { uint256 q1=_newHashs.length; uint256 q2=_tokenIds.length; require(q1==check_len,"1"); require(q2==check_len,"2"); for (uint i ; i < check_len; ) { overrideTokenIPFSHash(_newHashs[i], _tokenIds[i]); unchecked { ++i ;} } } /// @dev change URI extension that comes after ipfs://{CID}/, last resort if there is a sequencing problem after recycling, cannot be done after lock function overrideTokenIPFSHash(uint256 _newHash , uint256 _tokenId) onlyOperator public { //check if artwork is locked require(_exists(_tokenId), "1"); require(!artworks[tokenIdToArtworkId[_tokenId]].locked,"2"); tokenIdToIpfsHash[_tokenId]=_newHash; } /// @dev change available to mint array if there is a problem in sequencing, this applies for future mints function overrideAvailableArray(uint256 _artworkId,uint256[] calldata available_array ) onlyOperator onlyUnlocked(_artworkId) public { // jus tin case if available array mixes up require(available_array.length == artworks[_artworkId].available_list.length,"1"); require(artworkCheck[_artworkId],"2"); for (uint i; i < artworks[_artworkId].available_list.length;) { artworks[_artworkId].available_list[i]=available_array[i]; unchecked { ++i ;} } } /// @dev royalty percentage change for existing artworks function changeArtworkRoyaltiesInBP(uint256 _artworkId,uint256 _royaltiesInBP) onlyOperator onlyUnlocked(_artworkId) public { artworks[_artworkId].royaltiesInBP = _royaltiesInBP; } /// @dev royalty address change for existing artworks function changeArtworkRoyaltyReceiver(uint256 _artworkId,address _royaltyReceiver) onlyOperator onlyUnlocked(_artworkId) public { artworks[_artworkId].royaltyReceiver = _royaltyReceiver; } //𝗠𝗜𝗡𝗧𝗜𝗡𝗚 /** * @dev mints a token for the gallery. * * Requirements: * * - `artwork` should be Unpaused. * - only operator can call * * Functionality: * - can mint reserved tokens * - can mint credit card tokens where gallery can burn in 90 days if the payment is fraudulent * - can mint tokens for other OTC deals */ function galleryMint(address _to, uint256 _artworkId, bool _freeze,uint256 quantity,bool credit_card_sale,bool reserved) onlyOperator onlyUnPaused(_artworkId) external returns (uint256[] memory) { // if the sale is done via credit card, we reserve right to burn for 90days require(artworkCheck[_artworkId],"1"); require(quantity<=MINT_HARD_LIMIT, "3"); require(!artworks[_artworkId].locked , "4"); require(gateKeeperOneAllowMinting , "5"); require(gateKeeperOneAppointed, "6"); require(gateKeeperTwoAllowMinting, "7"); require(gateKeeperTwoAppointed, "8"); if (reserved==false) { require(artworks[_artworkId].minted + quantity <= artworks[_artworkId].artworkLimit, "2"); } if (reserved) { //in the mint we will increment minted // we need to deduct from reserved and minted before hand so that minted will come to the correct quantuty require(artworks[_artworkId].reserved - quantity >= 0, "9"); //make sure it as actually reserved require(artworks[_artworkId].minted - quantity >= 0, "10"); //something wrong } uint[] memory tokenIds = new uint[](quantity); for (uint i ; i < quantity; ) { if (reserved) { artworks[_artworkId].reserved=artworks[_artworkId].reserved-1; // unreserve the minted artworks[_artworkId].minted=artworks[_artworkId].minted-1; // unreserve the minted } uint tokenId=_mintToken(_to, _artworkId,_freeze); tokenIds[i]=tokenId; paidWithCard[tokenId]=credit_card_sale; paidDate[tokenId]=block.timestamp; unchecked { ++i ;} } return tokenIds; } /// @dev reserves a token for future sale function galleryReserve( uint256 _artworkId,uint256 quantity) onlyGalleryReserver external { // can reserve while paused require(artworkCheck[_artworkId],"1"); require(artworks[_artworkId].minted+quantity <= artworks[_artworkId].artworkLimit, "2"); require(quantity<=MINT_HARD_LIMIT, "3"); require(!artworks[_artworkId].locked , "4"); require(gateKeeperOneAllowMinting , "5"); require(gateKeeperOneAppointed, "6"); require(gateKeeperTwoAllowMinting, "7"); require(gateKeeperTwoAppointed, "8"); //add the reserved and minted artworks[_artworkId].minted=artworks[_artworkId].minted+quantity; artworks[_artworkId].reserved=artworks[_artworkId].reserved+quantity; } /// @dev unreserves a token for future sale function galleryUnReserve( uint256 _artworkId,uint256 quantity) onlyGalleryReserver external { // if the sale is done via credit card, we reserve right to burn for 90days // can reserve while paused require(artworkCheck[_artworkId],"1"); require(artworks[_artworkId].minted-quantity >= 0, "2"); require(artworks[_artworkId].reserved-quantity >= 0, "3"); require(quantity<=MINT_HARD_LIMIT, "4"); require(!artworks[_artworkId].locked , "5"); require(gateKeeperOneAllowMinting , "6"); require(gateKeeperOneAppointed, "7"); require(gateKeeperTwoAllowMinting, "8"); require(gateKeeperTwoAppointed, "9"); //sub the reserved and minted artworks[_artworkId].minted=artworks[_artworkId].minted-quantity; artworks[_artworkId].reserved=artworks[_artworkId].reserved-quantity; } /// @dev public mint function where ETH is expected for delivery function publicSaleMint(uint256 _artworkId, bool _freeze, uint256 quantity) public payable onlyAccounts onlyUnPaused(_artworkId) returns (uint256[] memory) { require(artworkCheck[_artworkId],"1"); require(msg.value >= artworks[_artworkId].artworkPrice*quantity, "2"); require(artworks[_artworkId].artworkPrice>0, "3"); require(quantity<=MINT_HARD_LIMIT, "4"); require(artworks[_artworkId].minted+quantity <= artworks[_artworkId].artworkLimit, "5"); require(!artworks[_artworkId].locked , "6"); require(gateKeeperOneAllowMinting, "7"); require(gateKeeperTwoAllowMinting, "8"); require(gateKeeperOneAppointed, "9"); require(gateKeeperTwoAppointed, "10"); require(artworks[_artworkId].presale==false, "11"); uint[] memory tokenIds = new uint[](quantity); for (uint i; i < quantity;) { tokenIds[i]=_mintToken(msg.sender, _artworkId,_freeze); unchecked { ++i ;} } return tokenIds; } /// @dev public presale mint function where ETH and whitelisting is expected for delivery function preSaleMint(uint256 _artworkId, bool _freeze, uint256 quantity, bytes32[] calldata proof) public payable onlyAccounts onlyUnPaused(_artworkId) returns (uint256[] memory) { require(artworkCheck[_artworkId],"1"); require(msg.value >= artworks[_artworkId].artworkPrice * quantity, "2"); require(artworks[_artworkId].artworkPrice>0, "3"); require(quantity<=MINT_HARD_LIMIT, "4"); require(artworks[_artworkId].minted+quantity <= artworks[_artworkId].artworkLimit, "5"); require(!artworks[_artworkId].locked , "6"); require(gateKeeperOneAllowMinting, "7"); require(gateKeeperTwoAllowMinting, "8"); require(gateKeeperOneAppointed, "9"); require(gateKeeperTwoAppointed, "10"); require(artworks[_artworkId].presale==true, "11"); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(proof, root, leaf),"12"); uint256 limit=getWhiteListedLimit(msg.sender); uint256 new_limit=limit + quantity; require(new_limit<=WHITELIST_PER_ACCOUNT_LIMIT,"13"); uint[] memory tokenIds = new uint[](quantity); _setLimit(msg.sender,new_limit); for (uint i ; i < quantity;) { tokenIds[i]=_mintToken(msg.sender, _artworkId,_freeze); unchecked { ++i ;} } return tokenIds; } /// @dev seach for a non 0, unassigned ID and add it as extension, used for recycling the IPFS link function getNextAvailableExtId(uint256 _artworkId) internal returns (bool found,uint256 ext_id) { //loop the avialble //if it is not 0, break and return // if 0 ext_id=0; uint256[] storage avails=artworks[_artworkId].available_list; found=false; for (uint i ; i < avails.length;) { uint256 val=artworks[_artworkId].available_list[i]; if (val!=0) { artworks[_artworkId].available_list[i]=0; ext_id=val; found=true; break; } unchecked { ++i ;} } return (found,ext_id); } /// @dev all mint functions call this function function _mintToken(address _to, uint256 _artworkId, bool _freeze) internal returns (uint256 _tokenId) { artworks[_artworkId].minted = artworks[_artworkId].minted + 1; artworks[_artworkId].count = artworks[_artworkId].count + 1; uint256 tokenIdToBe = (_artworkId * ONE_MILLION) + artworks[_artworkId].count; require(artworks[_artworkId].count<ONE_MILLION,"1"); (bool found_,uint256 ext_id_)=getNextAvailableExtId(_artworkId); require(found_,"2"); _mint(_to, tokenIdToBe); tokenIdToArtworkId[tokenIdToBe] = _artworkId; artworkIdToTokenIds[_artworkId].push(tokenIdToBe); tokenIdToIpfsHash[tokenIdToBe]=ext_id_; emit Mint(_to, tokenIdToBe, _artworkId); if (_freeze) { emit PermanentURI(tokenURI(tokenIdToBe),tokenIdToBe); //freeze it, OpenSea convention } return tokenIdToBe; } /// @dev string concetanation function append(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } /// @dev overrided URI function where URI based on Artwork is returned function tokenURI(uint256 _tokenId) public view onlyValidTokenId(_tokenId) override returns (string memory) { uint256 ipfsHash= tokenIdToIpfsHash[_tokenId]; return append(artworks[tokenIdToArtworkId[_tokenId]].artworkBaseIpfsURI, Strings.toString(ipfsHash)); } //BURNING /// @dev internal burn, deletes URI, reduces supply and sends the token to the 0x0. /// If the token is sold via CC, can remote burn // If token is sold via ETH, only burn if Operator holds the token function burnTokens(uint256[] calldata _tokenIds, uint256 check_len) external onlyOperator { require(gateKeeperOneAllowMinting, "1"); require(gateKeeperTwoAllowMinting, "2"); require(gateKeeperOneAppointed, "3"); require(gateKeeperTwoAppointed, "4"); uint256 q1=_tokenIds.length; require(q1==check_len,"5"); for (uint i ; i < q1;) { if (paidWithCard[_tokenIds[i]]) { _creditCardBurn(_tokenIds[i]); } else { _burnToken(_tokenIds[i],msg.sender); } unchecked { ++i ;} } } /// @dev burn function resets the states function _burnToken(uint256 _tokenId,address msg_sender) internal { require(_exists(_tokenId), "1"); address token_owner = ERC721.ownerOf(_tokenId); require(msg_sender==token_owner ,"2"); uint256 _artworkId=tokenIdToArtworkId[_tokenId]; require(_artworkId!=0,"3"); //get the hash of the token and equate it to a value other than 0 uint256 ipfsHash=tokenIdToIpfsHash[_tokenId]; artworks[_artworkId].minted = artworks[_artworkId].minted - 1; tokenIdToArtworkId[_tokenId] = 0; tokenIdToIpfsHash[_tokenId]=0; artworks[_artworkId].available_list[ipfsHash-1]=ipfsHash; //burned ID is available for recycling isBurned[_tokenId]=true; _burn(_tokenId); emit Burn(_tokenId,_artworkId); } /// @dev burn function that doesn't check ownership function _creditCardBurn(uint256 _tokenId) internal { //function to burn the token if it is bought via credit card // this functionality is only valid for 90 days after mint and will be used a last resort against fraud // Please contact us via info@whitecubeless.com if you to want to disable that earlier, you might be subject to KYC depending on the situation. //Note that this function is only callable if paidWithCard is true. // The only scenerio where this can happen is publicGalleryMint require(_exists(_tokenId), "1"); require(paidWithCard[_tokenId], "2"); require(block.timestamp-paidDate[_tokenId]<=DAY_LIMIT * 86400,"3"); require(burnDisabled[_tokenId]==false,"4"); uint256 ipfsHash=tokenIdToIpfsHash[_tokenId]; uint256 _artworkId=tokenIdToArtworkId[_tokenId]; require(_artworkId!=0,"5"); artworks[_artworkId].minted = artworks[_artworkId].minted-1; tokenIdToArtworkId[_tokenId] = 0; tokenIdToIpfsHash[_tokenId]=0; artworks[_artworkId].available_list[ipfsHash-1]=ipfsHash; //burned ID is available for recycling isBurned[_tokenId]=true; _burn(_tokenId); emit Burn(_tokenId,_artworkId); } //𝗥𝗢𝗬𝗔𝗟𝗧𝗜𝗘𝗦 /// @dev EIP-2981 royalty override function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view override returns (address receiver, uint256 royaltyAmount) { address _royaltiesReceiver = artworks[tokenIdToArtworkId[_tokenId]].royaltyReceiver; uint256 _royaltiesinBPartwork = artworks[tokenIdToArtworkId[_tokenId]].royaltiesInBP; uint256 _royalties = _salePrice*_royaltiesinBPartwork/10000; return (_royaltiesReceiver, _royalties); } /// @notice Informs callers that this contract supports ERC2981 /// this is for future usage, hope marketplaces can see our royalty declarations function supportsInterface(bytes4 interfaceId) public view override(ERC721Enumerable,IERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } //𝗩𝗜𝗘𝗪 𝗙𝗨𝗡𝗖𝗧𝗜𝗢𝗡𝗦 /// @dev gives artwork information function artworkTokenInfo(uint256 _artworkId) view public returns (uint256 minted, uint256 artworkLimit , bool locked,uint256 price,uint256 count,string memory artworkBaseIpfsURI,uint256 reserved) { minted = artworks[_artworkId].minted; //minted includes both reserved and minted reserved = artworks[_artworkId].reserved; //to keep track of reserved, only deduct if reserve minted or unreserved artworkLimit = artworks[_artworkId].artworkLimit; locked=artworks[_artworkId].locked; price=artworks[_artworkId].artworkPrice; count=artworks[_artworkId].count; artworkBaseIpfsURI = artworks[_artworkId].artworkBaseIpfsURI; } /// @dev all tokens, burned ones are shown as 0 in the result function artworkShowAllTokens(uint256 _artworkId) public view returns (uint256[] memory) { uint256[] memory tokens=artworkIdToTokenIds[_artworkId]; uint len=tokens.length; for (uint i ; i < len;) { uint256 val=tokens[i]; if (isBurned[val]) { tokens[i]=0; } unchecked { ++i ;} } return tokens; } /// @dev tokenId to ArtworkID function showArtworkOfToken(uint256 _tokenId) public view returns (uint256) { return tokenIdToArtworkId[_tokenId]; } /// @dev artwork to IPFS CID function showIpfsHash(uint256 _artworkId) public view returns (uint256) { return tokenIdToIpfsHash[_artworkId]; } /// @dev remaining time to remotely burn a credit card token function showCCSecondsRemaining(uint256 _tokenId) public view returns (uint) { return (DAY_LIMIT * 86400)-(block.timestamp-paidDate[_tokenId]); } /// @dev returns if user cna reserve a quantity at the moment function isReservable(uint quantity,uint _artworkId) public view returns (bool) { if ((artworks[_artworkId].minted+quantity <= artworks[_artworkId].artworkLimit) && (artworkCheck[_artworkId])) { return true; } return false; } /// @dev available array display function showAvailableArray(uint256 _artworkId) public view returns (uint256[] memory) { return artworks[_artworkId].available_list; } //RESETTABLE MAPPING /** * @dev A resettable mapping implementation using clever hashing * * * * Functionality: * * - Resets the whitelisted addresses for the next drop. * */ /// @dev how much a whitelisted user minted function getWhiteListedLimit(address whitelistedAddress) public view returns(uint256) { bytes32 key = keccak256(abi.encodePacked(currentMappingVersion, whitelistedAddress)); return whiteListLimits[key]; } /// @dev set the number of mints a whitelisted user called function _setLimit(address whitelistedAddress, uint256 newLimit) internal { bytes32 key = keccak256(abi.encodePacked(currentMappingVersion, whitelistedAddress)); whiteListLimits[key] = newLimit; } /// @dev reset the whitelisted limits function resetWhiteListedMapping() external onlyOperator { currentMappingVersion++; } /// @dev a way to delete entries from the mapping, function recoverGas(uint256 _version, address whitelistedAddress) external onlyOperator { require(_version < currentMappingVersion); bytes32 key = keccak256(abi.encodePacked(_version, whitelistedAddress)); delete(whiteListLimits[key]); } }
See {IERC721-getApproved}./
function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; }
6,085,810
/** *Submitted for verification at Etherscan.io on 2021-11-25 */ // File: @openzeppelin/contracts/utils/EnumerableSet.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/AccessControl.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity >=0.6.0 <0.8.0; // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // File: @openzeppelin/contracts/utils/Pausable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Pausable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // File: eth-contracts/SEFI.sol pragma solidity >=0.6.0 <0.8.0; contract wATOM is Context, AccessControl, ERC20Burnable, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. Grnats `MINTER_ROLE` to the bridge. * * See {ERC20-constructor}. */ constructor(address bridge) public ERC20("Wrapped ATOM", "wATOM") { _setupDecimals(6); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(MINTER_ROLE, bridge); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require( hasRole(PAUSER_ROLE, _msgSender()), "wATOM: must have pauser role to pause" ); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require( hasRole(PAUSER_ROLE, _msgSender()), "wATOM: must have pauser role to unpause" ); _unpause(); } function _transfer( address sender, address recipient, uint256 amount ) internal virtual override { if (hasRole(MINTER_ROLE, sender)) { _mint(recipient, amount); } else if (hasRole(MINTER_ROLE, recipient)) { _burn(sender, amount); } else { super._transfer(sender, recipient, amount); } } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } }
Unpauses all token transfers. See {ERC20Pausable} and {Pausable-_unpause}. Requirements: - the caller must have the `PAUSER_ROLE`./
function unpause() public virtual { require( hasRole(PAUSER_ROLE, _msgSender()), "wATOM: must have pauser role to unpause" ); _unpause(); }
15,012,751
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "../upkeeps/CronUpkeep.sol"; import "../upkeeps/CronUpkeepDelegate.sol"; import "../ConfirmedOwner.sol"; import {Spec, Cron as CronExternal} from "../libraries/external/Cron.sol"; /** * @title The CronUpkeepFactory contract * @notice This contract serves as a delegate for all instances of CronUpkeep. Those contracts * delegate their checkUpkeep calls onto this contract. Utilizing this pattern reduces the size * of the CronUpkeep contracts. */ contract CronUpkeepFactory is ConfirmedOwner { event NewCronUpkeepCreated(address upkeep, address owner); address private immutable s_cronDelegate; uint256 public s_maxJobs = 5; constructor() ConfirmedOwner(msg.sender) { s_cronDelegate = address(new CronUpkeepDelegate()); } /** * @notice Creates a new CronUpkeep contract, with msg.sender as the owner */ function newCronUpkeep() external { newCronUpkeepWithJob(bytes("")); } /** * @notice Creates a new CronUpkeep contract, with msg.sender as the owner, and registers a cron job */ function newCronUpkeepWithJob(bytes memory encodedJob) public { emit NewCronUpkeepCreated(address(new CronUpkeep(msg.sender, s_cronDelegate, s_maxJobs, encodedJob)), msg.sender); } /** * @notice Sets the max job limit on new cron upkeeps */ function setMaxJobs(uint256 maxJobs) external onlyOwner { s_maxJobs = maxJobs; } /** * @notice Gets the address of the delegate contract * @return the address of the delegate contract */ function cronDelegateAddress() external view returns (address) { return s_cronDelegate; } /** * @notice Converts a cron string to a Spec, validates the spec, and encodes the spec. * This should only be called off-chain, as it is gas expensive! * @param cronString the cron string to convert and encode * @return the abi encoding of the Spec struct representing the cron string */ function encodeCronString(string memory cronString) external pure returns (bytes memory) { return CronExternal.toEncodedSpec(cronString); } /** * @notice Converts, validates, and encodes a full cron spec. This payload is then passed to newCronUpkeepWithJob. * @param target the destination contract of a cron job * @param handler the function signature on the target contract to call * @param cronString the cron string to convert and encode * @return the abi encoding of the entire cron job */ function encodeCronJob( address target, bytes memory handler, string memory cronString ) external pure returns (bytes memory) { Spec memory spec = CronExternal.toSpec(cronString); return abi.encode(target, handler, spec); } }
Gets the address of the delegate contract return the address of the delegate contract/
function cronDelegateAddress() external view returns (address) { return s_cronDelegate; }
12,622,365
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** @title Color.sol is a sample of a ERC721 token smart contract * @author Chris Ball * @notice This contract is a simple example of an ERC721 token derived from ERC721Enumerable.sol */ contract Colors is ERC721Enumerable, Ownable { string[] public colors; mapping(string => bool) _colorExists; constructor() ERC721Enumerable() ERC721("Color", "COLORS") public { } /** @notice function is a wrapper for the ERC721 _mint function */ function mint(string memory _color) public onlyOwner { require(!_colorExists[_color], "This color already exists..."); colors.push(_color); uint _id = colors.length - 1; _mint(msg.sender, _id); _colorExists[_color] = true; } }
function is a wrapper for the ERC721 _mint function /
function mint(string memory _color) public onlyOwner { require(!_colorExists[_color], "This color already exists..."); colors.push(_color); uint _id = colors.length - 1; _mint(msg.sender, _id); _colorExists[_color] = true; }
12,851,573
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "@darwinia/contracts-utils/contracts/ECDSA.sol"; import "@darwinia/contracts-utils/contracts/Bitfield.sol"; import "@darwinia/contracts-verify/contracts/MerkleProof.sol"; import "@darwinia/contracts-verify/contracts/KeccakMMR.sol"; import "./ValidatorRegistry.sol"; import "./GuardRegistry.sol"; import "../spec/BeefyCommitmentScheme.sol"; /** * @title A entry contract for the Ethereum-like light client * @author echo * @notice The light client is the trust layer of the bridge * @dev See https://hackmd.kahub.in/Nx9YEaOaTRCswQjVbn4WsQ?view */ contract DarwiniaLightClient is BeefyCommitmentScheme, Bitfield, ValidatorRegistry, GuardRegistry { /* Events */ /** * @notice Notifies an observer that the prover's attempt at initital * verification was successful. * @dev Note that the prover must wait until `n` blocks have been mined * subsequent to the generation of this event before the 2nd tx can be sent * @param prover The address of the calling prover * @param blockNumber The blocknumber in which the initial validation * succeeded * @param id An identifier to provide disambiguation */ event InitialVerificationSuccessful( address prover, uint256 blockNumber, uint256 id ); /** * @notice Notifies an observer that the complete verification process has * finished successfuly and the new commitmentHash will be accepted * @param prover The address of the successful prover * @param id the identifier used */ event FinalVerificationSuccessful( address prover, uint256 id ); event CleanExpiredCommitment(uint256 id); event NewMMRRoot(bytes32 mmrRoot, uint256 blockNumber); /* Types */ /** * The Proof is a collection of proofs used to verify the signatures from the signers signing * each new justification. * @param signatures an array of signatures from the chosen signers * @param positions an array of the positions of the chosen signers * @param signers an array of the address of each signer * @param signerProofs an array of merkle proofs from the chosen validators proving that their addresses * are in the validator set */ struct Proof { bytes[] signatures; uint256[] positions; address[] signers; bytes32[][] signerProofs; } /** * The ValidationData is the set of data used to link each pair of initial and complete verification transactions. * @param senderAddress the sender of the initial transaction * @param commitmentHash the hash of the commitment they are claiming has been signed * @param blockNumber the block number for this commitment * @param validatorClaimsBitfield a bitfield signalling which validators they claim have signed */ struct ValidationData { address payable senderAddress; bytes32 commitmentHash; uint256 blockNumber; uint256[] validatorClaimsBitfield; } struct MessagesProof { MProof chainProof; MProof laneProof; } struct MProof { bytes32 root; uint256 count; bytes32[] proof; } /* State */ uint256 public currentId; bytes32 public latestMMRRoot; bytes32 public latestChainMessagesRoot; uint256 public latestBlockNumber; mapping(uint256 => ValidationData) public validationData; /* Constants */ /** * @dev Block wait period after `newSignatureCommitment` to pick the random block hash */ uint256 public constant BLOCK_WAIT_PERIOD = 12; /** * @dev Block wait period after `newSignatureCommitment` to pick the random block hash * 120000000/2^25 = 3.57 ether is recommended for Ethereum */ uint256 public constant MIN_SUPPORT = 4 ether; /** * @dev A vault to store expired commitment or malicious commitment slashed asset */ address payable public immutable SLASH_VAULT; /** * @notice Deploys the LightClientBridge contract * @param network source chain network name * @param slashVault initial SLASH_VAULT * @param guards initial guards of guard set * @param threshold initial threshold of guard set * @param validatorSetId initial validator set id * @param validatorSetLen length of initial validator set * @param validatorSetRoot initial validator set merkle tree root */ constructor( bytes32 network, address payable slashVault, address[] memory guards, uint256 threshold, uint256 validatorSetId, uint256 validatorSetLen, bytes32 validatorSetRoot ) public GuardRegistry(network, guards, threshold) { SLASH_VAULT = slashVault; _updateValidatorSet(validatorSetId, validatorSetLen, validatorSetRoot); } /* Public Functions */ function getFinalizedChainMessagesRoot() external view returns (bytes32) { return latestChainMessagesRoot; } function getFinalizedBlockNumber() external view returns (uint256) { return latestBlockNumber; } function validatorBitfield(uint256 id) external view returns (uint256[] memory) { return validationData[id].validatorClaimsBitfield; } function requiredNumberOfValidatorSigs() public view returns (uint256) { if (validatorSetLen < 36) { return validatorSetLen * 2 / 3 + 1; } return 25; } function createRandomBitfield(uint256 id) public view returns (uint256[] memory) { ValidationData storage data = validationData[id]; return _createRandomBitfield(data); } function _createRandomBitfield(ValidationData storage data) internal view returns (uint256[] memory) { require(data.blockNumber > 0, "Bridge: invalid id"); return randomNBitsWithPriorCheck( getSeed(data.blockNumber), data.validatorClaimsBitfield, requiredNumberOfValidatorSigs(), validatorSetLen ); } function createInitialBitfield(uint256[] calldata bitsToSet, uint256 length) external pure returns (uint256[] memory) { return createBitfield(bitsToSet, length); } function verify_lane_data_proof( bytes32 lane_hash, uint32 chain_pos, uint32 lane_pos, bytes calldata proof ) external view returns (bool) { return validate_lane_data_match_root(lane_hash, chain_pos, lane_pos, proof); } function validate_lane_data_match_root( bytes32 lane_hash, uint32 chain_pos, uint32 lane_pos, bytes memory proof ) internal view returns (bool) { MessagesProof memory messages_proof = abi.decode(proof, (MessagesProof)); // Validate that the commitment matches the commitment contents require(messages_proof.chainProof.root == latestChainMessagesRoot, "Lane: invalid ChainMessagesRoot"); return validateLaneDataMatchRoot( lane_hash, chain_pos, lane_pos, messages_proof.chainProof, messages_proof.laneProof ); } function validateLaneDataMatchRoot( bytes32 laneHash, uint256 chainPosition, uint256 lanePosition, MProof memory chainProof, MProof memory laneProof ) internal pure returns (bool) { return MerkleProof.verifyMerkleLeafAtPosition( laneProof.root, laneHash, lanePosition, laneProof.count, laneProof.proof ) && MerkleProof.verifyMerkleLeafAtPosition( chainProof.root, laneProof.root, chainPosition, chainProof.count, chainProof.proof ); } /** * @notice Executed by the apps in order to verify commitment * @param beefyMMRLeafHash contains the merkle leaf hash * @param beefyMMRLeafIndex contains the merkle leaf index * @param beefyMMRLeafCount contains the merkle leaf count * @param peaks contains the merkle maintain range peaks * @param siblings contains the merkle maintain range siblings */ function verifyBeefyMerkleLeaf( bytes32 beefyMMRLeafHash, uint256 beefyMMRLeafIndex, uint256 beefyMMRLeafCount, bytes32[] calldata peaks, bytes32[] calldata siblings ) external view returns (bool) { return KeccakMMR.inclusionProof( latestMMRRoot, beefyMMRLeafCount, beefyMMRLeafIndex, beefyMMRLeafHash, peaks, siblings ); } /** * @notice Executed by the prover in order to begin the process of block * acceptance by the light client * @param commitmentHash contains the commitmentHash signed by the validator(s) * @param validatorClaimsBitfield a bitfield containing a membership status of each * validator who has claimed to have signed the commitmentHash * @param validatorSignature the signature of one validator * @param validatorPosition the position of the validator, index starting at 0 * @param validatorAddress the public key of the validator * @param validatorAddressMerkleProof proof required for validation of the public key in the validator merkle tree */ function newSignatureCommitment( bytes32 commitmentHash, uint256[] memory validatorClaimsBitfield, bytes memory validatorSignature, uint256 validatorPosition, address validatorAddress, bytes32[] memory validatorAddressMerkleProof ) public payable returns (uint256) { /** * @dev Check that the bitfield actually contains enough claims to be succesful, ie, > 2/3 */ require( countSetBits(validatorClaimsBitfield) > (validatorSetLen * 2) / 3, "Bridge: Bitfield not enough validators" ); verifySignature( validatorSignature, validatorSetRoot, validatorAddress, validatorSetLen, validatorPosition, validatorAddressMerkleProof, commitmentHash ); /** * @notice Lock up the sender stake as collateral */ require(msg.value == MIN_SUPPORT, "Bridge: Collateral mismatch"); // Accept and save the commitment validationData[currentId] = ValidationData( msg.sender, commitmentHash, block.number, validatorClaimsBitfield ); emit InitialVerificationSuccessful(msg.sender, block.number, currentId); currentId = currentId + 1; return currentId; } /** * @notice Performs the second step in the validation logic * @param id an identifying value generated in the previous transaction * @param commitment contains the full commitment that was used for the commitmentHash * @param validatorProof a struct containing the data needed to verify all validator signatures * @param guardSignatures The signatures of the guards which to double-check the commitmentHash */ function completeSignatureCommitment( uint256 id, Commitment memory commitment, Proof memory validatorProof, bytes[] memory guardSignatures ) public { // only current epoch require(commitment.validatorSetId == validatorSetId, "Bridge: Invalid validator set id"); verifyCommitment(id, commitment, validatorProof, guardSignatures); processPayload(commitment.payload, commitment.blockNumber); /** * @dev We no longer need the data held in state, so delete it for a gas refund */ delete validationData[id]; /** * @notice If relayer do `completeSignatureCommitment` late or failed, `MIN_SUPPORT` will be slashed */ msg.sender.transfer(MIN_SUPPORT); emit FinalVerificationSuccessful(msg.sender, id); } /** * @notice Clean up the expired commitment and slash * @param id the identifier generated by submit commitment */ function cleanExpiredCommitment(uint256 id) public { ValidationData storage data = validationData[id]; require(block.number > data.blockNumber + BLOCK_WAIT_PERIOD + 256, "Bridge: Only expired"); SLASH_VAULT.transfer(MIN_SUPPORT); delete validationData[id]; emit CleanExpiredCommitment(id); } /* Private Functions */ function verifyCommitment( uint256 id, Commitment memory commitment, Proof memory validatorProof, bytes[] memory guardSignatures ) private view { ValidationData storage data = validationData[id]; /** * @dev verify that network is the same as `network` */ require( commitment.payload.network == NETWORK, "Bridge: Commitment is not part of this network" ); /** * @dev verify that sender is the same as in `newSignatureCommitment` */ require( msg.sender == data.senderAddress, "Bridge: Sender address does not match original validation data" ); uint256[] memory randomBitfield = _createRandomBitfield(data); // Encode and hash the commitment bytes32 commitmentHash = hash(commitment); require( commitmentHash == data.commitmentHash, "Bridge: Commitment must match commitment hash" ); verifyValidatorProofSignatures( randomBitfield, validatorProof, requiredNumberOfValidatorSigs(), commitmentHash ); // Guard Registry double-check the commitmentHash checkGuardSignatures(commitmentHash, guardSignatures); } function verifyValidatorProofSignatures( uint256[] memory randomBitfield, Proof memory proof, uint256 requiredNumOfSignatures, bytes32 commitmentHash ) private view { verifyProofSignatures( validatorSetRoot, validatorSetLen, randomBitfield, proof, requiredNumOfSignatures, commitmentHash ); } function verifyProofSignatures( bytes32 root, uint256 width, uint256[] memory bitfield, Proof memory proof, uint256 requiredNumOfSignatures, bytes32 commitmentHash ) private pure { verifyProofLengths(requiredNumOfSignatures, proof); /** * @dev For each randomSignature, do: */ for (uint256 i = 0; i < requiredNumOfSignatures; i++) { uint256 pos = proof.positions[i]; /** * @dev Check if validator in bitfield */ require( isSet(bitfield, pos), "Bridge: signer must be once in bitfield" ); /** * @dev Remove validator from bitfield such that no validator can appear twice in signatures */ clear(bitfield, pos); verifySignature( proof.signatures[i], root, proof.signers[i], width, pos, proof.signerProofs[i], commitmentHash ); } } function verifyProofLengths( uint256 requiredNumOfSignatures, Proof memory proof ) private pure { /** * @dev verify that required number of signatures, positions, public keys and merkle proofs are * submitted */ require( proof.signatures.length == requiredNumOfSignatures, "Bridge: Number of signatures does not match required" ); require( proof.positions.length == requiredNumOfSignatures, "Bridge: Number of validator positions does not match required" ); require( proof.signers.length == requiredNumOfSignatures, "Bridge: Number of validator public keys does not match required" ); require( proof.signerProofs.length == requiredNumOfSignatures, "Bridge: Number of validator public keys does not match required" ); } function verifySignature( bytes memory signature, bytes32 root, address signer, uint256 width, uint256 position, bytes32[] memory addrMerkleProof, bytes32 commitmentHash ) private pure { /** * @dev Check if merkle proof is valid */ require( checkAddrInSet( root, signer, width, position, addrMerkleProof ), "Bridge: signer must be in signer set at correct position" ); /** * @dev Check if signature is correct */ require( ECDSA.recover(commitmentHash, signature) == signer, "Bridge: Invalid Signature" ); } /** * @notice Checks if an address is a member of the merkle tree * @param root the root of the merkle tree * @param addr The address to check * @param pos The position to check, index starting at 0 * @param width the width or number of leaves in the tree * @param proof Merkle proof required for validation of the address * @return Returns true if the address is in the set */ function checkAddrInSet( bytes32 root, address addr, uint256 width, uint256 pos, bytes32[] memory proof ) public pure returns (bool) { bytes32 hashedLeaf = keccak256(abi.encodePacked(addr)); return MerkleProof.verifyMerkleLeafAtPosition( root, hashedLeaf, pos, width, proof ); } /** * @notice Deterministically generates a seed from the block hash at the block number of creation of the validation * @dev Note that `blockhash(blockNum)` will only work for the 256 most recent blocks. If * `completeSignatureCommitment` is called too late, a new call to `newSignatureCommitment` is necessary to reset * validation data's block number * @param blockNumber block number * @return onChainRandNums an array storing the random numbers generated inside this function */ function getSeed(uint256 blockNumber) private view returns (uint256) { /** * @dev verify that block wait period has passed */ require( block.number > blockNumber + BLOCK_WAIT_PERIOD, "Bridge: Block wait period not over" ); require( block.number <= blockNumber + BLOCK_WAIT_PERIOD + 256, "Bridge: Block number has expired" ); uint256 randomSeedBlockNum = blockNumber + BLOCK_WAIT_PERIOD; // @note Create a hash seed from the block number bytes32 randomSeedBlockHash = blockhash(randomSeedBlockNum); return uint256(randomSeedBlockHash); } /** * @notice Perform some operation[s] using the payload * @param payload The payload variable passed in via the initial function * @param blockNumber The blockNumber variable passed in via the initial function */ function processPayload(Payload memory payload, uint256 blockNumber) private { // Check the payload is newer than the latest // Check that payload.leaf.block_number is > last_known_block_number; require(blockNumber > latestBlockNumber, "Bridge: Import old block"); latestMMRRoot = payload.mmr; latestChainMessagesRoot = payload.messageRoot; latestBlockNumber = blockNumber; applyValidatorSetChanges( payload.nextValidatorSet.id, payload.nextValidatorSet.len, payload.nextValidatorSet.root ); emit NewMMRRoot(latestMMRRoot, blockNumber); } /** * @notice Check if the payload includes a new validator set, * and if it does then update the new validator set * @dev This function should call out to the validator registry contract * @param nextValidatorSetId The id of the next validator set * @param nextValidatorSetLen The number of validators in the next validator set * @param nextValidatorSetRoot The merkle root of the merkle tree of the next validators */ function applyValidatorSetChanges( uint64 nextValidatorSetId, uint32 nextValidatorSetLen, bytes32 nextValidatorSetRoot ) private { // TODO: check nextValidatorSet can null or not require(nextValidatorSetId == 0 || nextValidatorSetId == validatorSetId + 1, "Bridge: Invalid next validator set id"); if (nextValidatorSetId == validatorSetId + 1) { _updateValidatorSet( nextValidatorSetId, nextValidatorSetLen, nextValidatorSetRoot ); } } }
Clean up the expired commitment and slash id the identifier generated by submit commitment/
function cleanExpiredCommitment(uint256 id) public { ValidationData storage data = validationData[id]; require(block.number > data.blockNumber + BLOCK_WAIT_PERIOD + 256, "Bridge: Only expired"); SLASH_VAULT.transfer(MIN_SUPPORT); delete validationData[id]; emit CleanExpiredCommitment(id); }
12,792,278
pragma solidity ^0.4.24; /** @title NoFilter */ contract NoFilter { address public owner; /** @dev Constructor function */ constructor() public {owner = msg.sender;} /**A struct holding and uploaded files details */ struct File { address uploaderId; string description; int vote; } /** @dev event emmitted when a user up votes ot down votes a file. Vote count can be used to filter front end results. */ event Vote(address voter, bytes32 indexed ipfsHash, int vote); /** @dev event emmitted when a file is uploaded to ipfs */ event Alert(address indexed uploaderId, bytes32 indexed ipfsHash); /** @dev mapping between ipfs hashes and File struct */ mapping(bytes32 => File) public details; /** * @dev upvotes a file, increasing its vote count, votes are helpful in ranking and filtering on the front end * @param ipfsHash bytes32 * @return details[ipfshash].vote which will be the current vote count */ function upVote(bytes32 ipfsHash) public returns (int) { details[ipfsHash].vote += 1; emit Vote(msg.sender, ipfsHash, details[ipfsHash].vote); return details[ipfsHash].vote; } /** * @dev upvotes a file, decreasing its vote count, votes are helpful in ranking and filtering on the front end * @param ipfsHash bytes32 * @return details[ipfshash].vote which will be the current vote count */ function downVote(bytes32 ipfsHash) public returns (int) { details[ipfsHash].vote -= 1; emit Vote(msg.sender, ipfsHash, details[ipfsHash].vote); return details[ipfsHash].vote; } /** * @dev this is the heart of the contract it saves the data to the chain relating to the uploaded files * @param _uploaderId address of the user * @param _description string description of the file being uploaded */ function upload(address _uploaderId, string _description, bytes32 ipfsHash ) public { int beginningVote = 1; File memory newFile = File(_uploaderId, _description, beginningVote); details[ipfsHash] = newFile; emit Alert(msg.sender, ipfsHash); } /** * @dev this is a safety mechanism reserved for the contract owner. it is intended to be used to downvote a file dramatically. it is suggested to be used in the event inappropriate or illegal files are posted through the site (eg. child pornography, terrorist materials etc..). This function will not destroy a file hosted on ipfs but provides a handy way to filter for such files on a front end. * @param ipfsHash bytes32 * @return details[ipfs[ipfsHash].vote which will return the current vote count */ function delist(bytes32 ipfsHash) public returns (int) { require(msg.sender == owner, "Sender not authorized."); details[ipfsHash].vote -= 1000; emit Vote(msg.sender, ipfsHash, details[ipfsHash].vote); return details[ipfsHash].vote; } /** * @dev returns the details of a uploaded file from the mapping * @param ipfsHash bytes32 * @return details[ipfsHash].uploaderId address, details[ipfsHash].description String, details[ipfsHash].vote int */ function getDetails(bytes32 ipfsHash) public view returns ( address, string, int ) { return (details[ipfsHash].uploaderId, details[ipfsHash].description, details[ipfsHash].vote); } /** * @dev this is the emergency stop function--suicide function only callable by owner. *Use this to disable a contract and then call the update function on NoFilterRegistry.sol with a new * contract address to point the front end at. USE WITH EXTREME CAUTION!!! */ function kill() public { require(msg.sender == owner, "Sender not authorized."); selfdestruct(owner); } /** @dev this is a Fallback function to be used as a catchall if an unrecognized function is called */ function() public payable { } }
returns the details of a uploaded file from the mapping ipfsHash bytes32 return details[ipfsHash].uploaderId address, details[ipfsHash].description String, details[ipfsHash].vote int/
function getDetails(bytes32 ipfsHash) public view returns ( address, string, int ) { return (details[ipfsHash].uploaderId, details[ipfsHash].description, details[ipfsHash].vote); }
6,342,789
./partial_match/1/0xCB334a89e79499b16fAe21f40cD1561fB092245f/sources/LotteryToken.sol
File: contracts\interfaces\ILotteryGame.sol
interface ILotteryGame { function setOracleIpfsHash(string memory _hash) external; function setProvableGasLimit(uint256 _amount) external; function setParticipationFee(uint256 _participationFee) external; function lockTransfer() external; function unlockTransfer() external; function startGame() external payable; function restartProvableQuery() external payable; }
2,869,908
./partial_match/1/0xcecaD69d7D4Ed6D52eFcFA028aF8732F27e08F70/sources/Flipper.sol
Purchase OUSD with USDT amount Amount of OUSD to purchase, in 18 fixed decimals. Potential rounding error is an intentional tradeoff USDT does not return a boolean and reverts, so no need for a require.
function buyOusdWithUsdt(uint256 amount) external { require(amount <= MAXIMUM_PER_TRADE, "Amount too large"); usdt.transferFrom(msg.sender, address(this), amount / 1e12); require(ousd.transfer(msg.sender, amount)); }
2,784,684
./full_match/1/0xed4e21BD620F3C1Fd1853b1C52A9D023C33D83d4/sources/contracts/lib/RedemptionsBase.sol
vEth2 transfer from returns true otherwise reverts
function deposit(uint256 amount) external nonReentrant { if (vEth2Token.transferFrom(msg.sender, address(this), amount)) { _stakeForWithdrawal(msg.sender, amount); } }
3,851,806
// Contracts/SupplyChain.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../emeraldaccesscontrol/MinerRole.sol"; import "../emeraldaccesscontrol/LaboratoryRole.sol"; import "../emeraldaccesscontrol/CustodianRole.sol"; import "../emeraldaccesscontrol/ManufacturerRole.sol"; import "../emeraldaccesscontrol/CustomerRole.sol"; import "./EmeraldStates.sol"; import "./Emerald.sol"; // Define a contract 'Supplychain' contract SupplyChain is Ownable, AccessControl, MinerRole, LaboratoryRole, CustodianRole, ManufacturerRole, CustomerRole{ // Define a variable called 'upc' for Universal Product Code (UPC) uint upc; // Define a variable called 'sku' for Stock Keeping Unit (SKU) uint sku; // Define a public mapping 'emeralds' that maps the UPC to an Emerald. mapping (uint => Emerald) emeralds; // Define a public mapping 'emeraldHistory' that maps the UPC to an array of TxHash, // that track its journey through the supply chain -- to be sent from DApp. mapping (uint => string[]) emeraldsHistory; EmeraldStates.State constant defaultState = EmeraldStates.State.Mined; // Define 17 events with the same 17 state values and accept 'upc' as input argument event Mined(uint upc); event Scaled(uint upc); event PackedForLab(uint upc); event ShipedToLab(uint upc); event LabReceived(uint upc); event Certified(uint upc); event ShippedToStore(uint upc); event StorageReceived(uint upc); event Stored(uint upc); event ForSale(uint upc); event Sold(uint upc); event ShipToManufacture(uint upc); event ManufacturerReceived(uint upc); event Manufactured(uint upc); event PackedForSale(uint upc); event Published(uint upc); event Buyed(uint upc); event ShippedToCustomer(uint upc); event Delivered(uint upc); // Define a modifer that verifies the Caller modifier verifyCaller (address _address) { require(msg.sender == _address); _; } // Define a modifier that checks if the paid amount is sufficient to cover the price modifier paidEnough(uint _price) { require(msg.value >= _price,"Not enought paid amount"); _; } // Define a modifier that checks the price and refunds the remaining balance modifier checkValue(uint _upc) { _; uint _price = emeralds[_upc].GetMarketPrice(); uint amountToReturn = msg.value - _price; msg.sender.transfer(amountToReturn); } // Checks if a emerald is Mined modifier mined(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Mined); _; } //Checks if an emerald was escaled modifier scaled(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Scaled); _; } //Checks if an emerald is packed modifier packedForLab(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.PackedForLab); _; } // Checks if an emerald was shipped to the laboratory modifier shipedToLab(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShipedToLab); _; } // Checks if an emerald was received by the Laboratory modifier labReceived(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.LabReceived); _; } // Checks if an emerald was certified by the laboratory modifier certified(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Certified); _; } // Checks if an emerald was shipped to the storage y the laboratory modifier shippedToStore(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShippedToStore); _; } // Checks if an emerald was received by the custodian service modifier storageReceived(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.StorageReceived); _; } // Checks if an emerald was stored by the custodian modifier stored(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Stored); _; } // Checks if a raw emerald is available for sale modifier forSale(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ForSale); _; } // Checks if a raw emerald was sold modifier sold(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Sold); _; } // Checks if a sold emerald was shipped to the buyer modifier shiptoManufacture(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShipToManufacture); _; } // Checks if an emerald was received by the manufacturer modifier manufacturerReceived(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ManufacturerReceived); _; } // Checks if an emerald was proccesed by the manufacturer modifier manufactured(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Manufactured); _; } // Checks if a cut emerald was packed modifier packedForSale(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.PackedForSale); _; } // Checks if an proccesed emerald is ready for sale modifier published(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Published); _; } // Checks if a proccesed emerald was purshased modifier buyed(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Buyed); _; } // Checks if a cut emerald was shipped to the buyer modifier shippedToCustomer(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShippedToCustomer); _; } // Checks if a cut emerald was received by the customer modifier delivered(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Delivered); _; } // In the constructor set 'owner' to the address that instantiated the contract // and set 'sku' to 1 // and set 'upc' to 1 constructor() { //owner = msg.sender; sku = 1; upc = 1; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } // Define a function 'kill' if required function kill() public onlyOwner{ selfdestruct(msg.sender); } // Define a function 'extractItem' that allows a Miner to mark an emerald as 'Mined' function extractEmerald( uint _sku, uint _upc, address payable _originMinerID, string memory _originMineName, string memory _originMineInformation, string memory _originMineLatitude, string memory _originMineLongitude ) public onlyMiner { //add emerald to emeralds list in the contract Emerald emerald = new Emerald(); emerald.SetExtractionInfo( _sku, _upc, _originMinerID, _originMineName, _originMineInformation, _originMineLatitude, _originMineLongitude ); emerald.SetEmeraldState(EmeraldStates.State.Mined); emeralds[_upc] = emerald; //Increment sku sku = sku + 1; // Emit the appropriate event emit Mined(_upc); } // Define a function 'scaleItem' that allows Miner to mark an item as 'Scaled' function scaleEmerald( uint _upc, string memory _scaleInfo ) public // Call modifier to check if upc has passed previous supply chain stage mined(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { // Update the appropriate fields emeralds[_upc].SetScaleInfo( _scaleInfo ); emeralds[_upc].SetEmeraldState(EmeraldStates.State.Scaled); // Emit the appropriate event emit Scaled(_upc); } //Define a function 'packScaledItem' that allows a Miner to mark an item 'Packed' function packScaledEmerald(uint _upc, address _laboratoryID, address _custodianID) public // Call modifier to check if upc has passed previous supply chain stage scaled(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { // Update the appropriate fields emeralds[_upc].AuthorizeLab(_laboratoryID); emeralds[_upc].AuthorizeCustodian(_custodianID); // Update Emerald state emeralds[_upc].SetEmeraldState(EmeraldStates.State.PackedForLab); // Emit the appropriate event emit PackedForLab(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function shipToLaboratory(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage packedForLab(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShipedToLab); // Emit the appropriate event emit ShipedToLab(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function laboratoryReceived(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shipedToLab(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetLaboratoryID()) onlyLaboratory { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.LabReceived); // Emit the appropriate event emit LabReceived(_upc); } // Define a function 'scaleItem' that allows a Miner to mark an item 'Processed' function certifyEmerald( uint _upc, string memory _certifiedProperties ) public // Call modifier to check if upc has passed previous supply chain stage labReceived(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetLaboratoryID()) onlyLaboratory { // Update the appropriate fields emeralds[_upc].SetCertifiedInfo(_certifiedProperties); emeralds[_upc].SetEmeraldState(EmeraldStates.State.Certified); // Emit the appropriate event emit Certified(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function shipToSecureStore(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage certified(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetLaboratoryID()) onlyLaboratory { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShippedToStore); // Emit the appropriate event emit ShippedToStore(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function SecureStorageReceived(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shippedToStore(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetCustodianID()) onlyCustodian { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.StorageReceived); // Emit the appropriate event emit StorageReceived(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function StoreEmerald(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage storageReceived(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetCustodianID()) onlyCustodian { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.Stored); // Emit the appropriate event emit Stored(_upc); } // Define a function 'registerForSale' that allows a Miner to mark an item 'ForSale' function registerForSale(uint _upc, uint _marketPrice) public // Call modifier to check if upc has passed previous supply chain stage stored(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { //Setup market price emeralds[_upc].SetMarketPrice(_marketPrice); // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ForSale); // Emit the appropriate event emit ForSale(_upc); } // Define a function 'buyItem' that allows the Manufacturer to mark an item 'Sold' function buyFromMiner(uint _upc) public payable // Call modifier to check if upc has passed previous supply chain stage forSale(_upc) // Call modifer to check if buyer has paid enough paidEnough(emeralds[_upc].GetMarketPrice()) // Call modifer to send any excess ether back to buyer checkValue(_upc) onlyManufacturer { // Transfer money to Miner (bool success, ) = emeralds[_upc].getOriginMinerID().call{value: emeralds[_upc].GetMarketPrice()}(""); require(success, "Transfer failed"); // Tranfer emerald ownership emeralds[_upc].SetOwnerID(msg.sender); emeralds[_upc].SetManufacturerID(msg.sender); // Update emerald state emeralds[_upc].SetEmeraldState(EmeraldStates.State.Sold); // Emit the appropriate event emit Sold(_upc); } // Define a function 'shipItem' that allows laboratory confirm that the emerald was shipped function shipToManufacturer(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage sold(_upc) // Call modifier to verify caller of this function onlyCustodian { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShipToManufacture); // Emit the appropriate event emit ShipToManufacture(_upc); } // Define a function 'receiveFromStorage' that allows the manufacturer mark an item 'ManufacturerReceived' function receiveFromStorage(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shiptoManufacture(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields - ownerID, retailerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.ManufacturerReceived); // Emit the appropriate event emit ManufacturerReceived(_upc); } // Define a function 'manufactureEmerald' that allows the manufacturer to mark an item 'Manufactured' function manufactureEmerald( uint _upc, string memory _manofactureInfo ) public // Call modifier to check if upc has passed previous supply chain stage manufacturerReceived(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields emeralds[_upc].SetManufacturedInfo(_manofactureInfo); // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Manufactured); // Emit the appropriate event emit Manufactured(_upc); } // Define a function 'packCutEmerald' that allows the manufacturer to mark an emerald 'PackedForSale' function packCutEmerald(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage manufactured(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.PackedForSale); // Emit the appropriate event emit PackedForSale(upc); } // Define a function 'publishEmerald' that allows the manufacturer to mark an item 'Published' function publishEmerald(uint _upc, uint _marketPrice) public // Call modifier to check if upc has passed previous supply chain stage packedForSale(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { //Setup market price emeralds[_upc].SetMarketPrice(_marketPrice); // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Published); // Emit the appropriate event emit Published(_upc); } // Define a function 'buyFromManufacturer' that allows the manufacturer to mark an item 'Buyed' function buyFromManufacturer(uint _upc) public payable // Call modifier to check if upc has passed previous supply chain stage published(_upc) // Call modifer to check if buyer has paid enough paidEnough(emeralds[_upc].GetMarketPrice()) // Call modifer to send any excess ether back to buyer checkValue(_upc) onlyCustomer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Buyed); // Transfer money to Manufacturer (bool success, ) = emeralds[_upc].getManufacturerID().call{value: emeralds[_upc].GetMarketPrice()}(""); require(success, "Transfer failed"); // Set the customerID value emeralds[_upc].SetCustomerID(msg.sender); // Transfer ownership emeralds[_upc].SetOwnerID(msg.sender); // Emit the appropriate event emit Buyed(_upc); } // Define a function 'shipEmeraldToCustomer' that allows the consumer to mark an item 'ShippedToCustomer' function shipEmeraldToCustomer(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage buyed(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShippedToCustomer); // Emit the appropriate event emit ShippedToCustomer(_upc); } // Define a function 'deliverToCustomer' that allows the consumer to mark an item 'Delivered' function deliverToCustomer(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shippedToCustomer(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyCustomer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Delivered); // Emit the appropriate event emit Delivered(_upc); } // Define a function 'fetchItemBufferOne' that fetches the data function fetchItemBufferOne(uint _upc) public view returns (bytes memory) { return (emeralds[_upc].GetBasicInfo()); } // Define a function 'fetchItemBufferTwo' that fetches the data function fetchItemBufferTwo(uint _upc) public view returns (bytes memory) { return (emeralds[_upc].GetDetailedInfo()); } }
Define a function 'buyItem' that allows the Manufacturer to mark an item 'Sold' Call modifier to check if upc has passed previous supply chain stage Call modifer to check if buyer has paid enough Call modifer to send any excess ether back to buyer Transfer money to Miner Tranfer emerald ownership Update emerald state Emit the appropriate event
function buyFromMiner(uint _upc) public payable forSale(_upc) paidEnough(emeralds[_upc].GetMarketPrice()) checkValue(_upc) onlyManufacturer { require(success, "Transfer failed"); emeralds[_upc].SetOwnerID(msg.sender); emeralds[_upc].SetManufacturerID(msg.sender); emeralds[_upc].SetEmeraldState(EmeraldStates.State.Sold); emit Sold(_upc); }
5,454,282
./full_match/5/0x6295849FCDEA72Ed1cBc1a05C9a808aDad6aA932/sources/project_/contracts/Uniswap/TransferHelper.sol
bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(0x23b872dd, from, to, value) ); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED' ); }
1,878,620
./full_match/4/0x66c88c5A68EF53a5AbE9615E35a4e69342154D7A/sources/lexWrapper.sol
This is safe because ownership is checked against decrement, and sum of all user balances can't exceed 'type(uint256).max'.
function transferFrom(address, address to, uint256 tokenId) public virtual { address owner = ownerOf[tokenId]; require( msg.sender == owner || msg.sender == getApproved[tokenId] || isApprovedForAll[owner][msg.sender], "NOT_APPROVED" ); unchecked { balanceOf[owner]--; balanceOf[to]++; } delete getApproved[tokenId]; ownerOf[tokenId] = to; emit Transfer(owner, to, tokenId); }
12,302,242
/** *Submitted for verification at Etherscan.io on 2021-09-28 */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; return msg.data; } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(now > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function balanceOf(address owner) external view returns (uint); } interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } contract MultiTransferSwap is Ownable { using SafeMath for uint256; address private factory; address private WETH; modifier ensure(uint _deadline) { require(_deadline >= block.timestamp, 'EXPIRED'); _; } constructor() public { factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; } receive() external payable { } function _swap(uint[] memory _amounts, address[] memory _path, address _to) internal virtual { for (uint i; i < _path.length - 1; i++) { (address input, address output) = (_path[i], _path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); uint amountOut = _amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < _path.length - 2 ? UniswapV2Library.pairFor(factory, output, _path[i + 2]) : _to; IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function multiSwapETHForExactTokens(uint times, uint amountOut, address[] calldata path, address to) external payable returns (uint[] memory amounts) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); for (uint i; i < times; i++){ amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value.div(times), 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } // refund dust eth, if any if (msg.value > amounts[0].mul(times)) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0].mul(times)); } }
fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); }
2,296,169
// contracts/Messages.sol // SPDX-License-Identifier: Apache 2 pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract Migrator is ERC20 { IERC20 public fromAsset; IERC20 public toAsset; uint public fromDecimals; uint public toDecimals; constructor ( address _fromAsset, address _toAsset ) // LP shares track the underlying toToken amount ERC20("Token Migration Pool", "Migrator-LP") { fromAsset = IERC20(_fromAsset); toAsset = IERC20(_toAsset); fromDecimals = ERC20(_fromAsset).decimals(); toDecimals = ERC20(_toAsset).decimals(); } // _amount denominated in toAsset function add(uint _amount) external { // deposit toAsset SafeERC20.safeTransferFrom(toAsset, msg.sender, address(this), _amount); // mint LP shares _mint(msg.sender, _amount); } // _amount denominated in LP shares function remove(uint _amount) external { // burn LP shares _burn(msg.sender, _amount); // send out toAsset SafeERC20.safeTransfer(toAsset, msg.sender, _amount); } // _amount denominated in LP shares function claim(uint _amount) external { // burn LP shares _burn(msg.sender, _amount); // send out fromAsset SafeERC20.safeTransfer(fromAsset, msg.sender, adjustDecimals(toDecimals, fromDecimals, _amount)); } // _amount denominated in fromToken function migrate(uint _amount) external { // deposit fromAsset SafeERC20.safeTransferFrom(fromAsset, msg.sender, address(this), _amount); // send out toAsset SafeERC20.safeTransfer(toAsset, msg.sender, adjustDecimals(fromDecimals, toDecimals, _amount)); } function adjustDecimals(uint _fromDecimals, uint _toDecimals, uint _amount) internal pure returns (uint) { if (_fromDecimals > _toDecimals){ _amount /= 10 ** (_fromDecimals - _toDecimals); } else if (_fromDecimals < _toDecimals) { _amount *= 10 ** (_toDecimals - _fromDecimals); } return _amount; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
_amount denominated in fromToken deposit fromAsset send out toAsset
function migrate(uint _amount) external { SafeERC20.safeTransferFrom(fromAsset, msg.sender, address(this), _amount); SafeERC20.safeTransfer(toAsset, msg.sender, adjustDecimals(fromDecimals, toDecimals, _amount)); }
1,283,303
/** *Submitted for verification at Etherscan.io on 2021-05-18 */ // File: contracts/lib/Types.sol /* Copyright 2020 DODO ZOO. SPDX-License-Identifier: Apache-2.0 */ pragma solidity 0.6.9; pragma experimental ABIEncoderV2; library Types { enum RStatus {ONE, ABOVE_ONE, BELOW_ONE} } // File: contracts/intf/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function name() external view returns (string memory); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); } // File: contracts/lib/InitializableOwnable.sol /** * @title Ownable * @author DODO Breeder * * @notice Ownership related functions */ contract InitializableOwnable { address public _OWNER_; address public _NEW_OWNER_; // ============ Events ============ event OwnershipTransferPrepared(address indexed previousOwner, address indexed newOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // ============ Modifiers ============ modifier onlyOwner() { require(msg.sender == _OWNER_, "NOT_OWNER"); _; } // ============ Functions ============ function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0), "INVALID_OWNER"); emit OwnershipTransferPrepared(_OWNER_, newOwner); _NEW_OWNER_ = newOwner; } function claimOwnership() external { require(msg.sender == _NEW_OWNER_, "INVALID_CLAIM"); emit OwnershipTransferred(_OWNER_, _NEW_OWNER_); _OWNER_ = _NEW_OWNER_; _NEW_OWNER_ = address(0); } } // File: contracts/lib/SafeMath.sol /** * @title SafeMath * @author DODO Breeder * * @notice Math operations with safety checks that revert on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "MUL_ERROR"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "DIVIDING_ERROR"); return a / b; } function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { uint256 quotient = div(a, b); uint256 remainder = a - quotient * b; if (remainder > 0) { return quotient + 1; } else { return quotient; } } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SUB_ERROR"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "ADD_ERROR"); return c; } function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = x / 2 + 1; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } // File: contracts/lib/DecimalMath.sol /** * @title DecimalMath * @author DODO Breeder * * @notice Functions for fixed point number with 18 decimals */ library DecimalMath { using SafeMath for uint256; uint256 constant ONE = 10**18; function mul(uint256 target, uint256 d) internal pure returns (uint256) { return target.mul(d) / ONE; } function mulCeil(uint256 target, uint256 d) internal pure returns (uint256) { return target.mul(d).divCeil(ONE); } function divFloor(uint256 target, uint256 d) internal pure returns (uint256) { return target.mul(ONE).div(d); } function divCeil(uint256 target, uint256 d) internal pure returns (uint256) { return target.mul(ONE).divCeil(d); } } // File: contracts/lib/ReentrancyGuard.sol /** * @title ReentrancyGuard * @author DODO Breeder * * @notice Protect functions from Reentrancy Attack */ contract ReentrancyGuard { // https://solidity.readthedocs.io/en/latest/control-structures.html?highlight=zero-state#scoping-and-declarations // zero-state of _ENTERED_ is false bool private _ENTERED_; modifier preventReentrant() { require(!_ENTERED_, "REENTRANT"); _ENTERED_ = true; _; _ENTERED_ = false; } } // File: contracts/intf/IOracle.sol interface IOracle { function getPrice() external view returns (uint256); } // File: contracts/intf/IDODOLpToken.sol interface IDODOLpToken { function mint(address user, uint256 value) external; function burn(address user, uint256 value) external; function balanceOf(address owner) external view returns (uint256); function totalSupply() external view returns (uint256); } // File: contracts/impl/Storage.sol /** * @title Storage * @author DODO Breeder * * @notice Local Variables */ contract Storage is InitializableOwnable, ReentrancyGuard { using SafeMath for uint256; // ============ Variables for Control ============ bool internal _INITIALIZED_; bool public _CLOSED_; bool public _DEPOSIT_QUOTE_ALLOWED_; bool public _DEPOSIT_BASE_ALLOWED_; bool public _TRADE_ALLOWED_; uint256 public _GAS_PRICE_LIMIT_; // ============ Advanced Controls ============ bool public _BUYING_ALLOWED_; bool public _SELLING_ALLOWED_; uint256 public _BASE_BALANCE_LIMIT_; uint256 public _QUOTE_BALANCE_LIMIT_; // ============ Core Address ============ address public _SUPERVISOR_; // could freeze system in emergency address public _MAINTAINER_; // collect maintainer fee to buy food for DODO address public _BASE_TOKEN_; address public _QUOTE_TOKEN_; address public _ORACLE_; // ============ Variables for PMM Algorithm ============ uint256 public _LP_FEE_RATE_; uint256 public _MT_FEE_RATE_; uint256 public _K_; Types.RStatus public _R_STATUS_; uint256 public _TARGET_BASE_TOKEN_AMOUNT_; uint256 public _TARGET_QUOTE_TOKEN_AMOUNT_; uint256 public _BASE_BALANCE_; uint256 public _QUOTE_BALANCE_; address public _BASE_CAPITAL_TOKEN_; address public _QUOTE_CAPITAL_TOKEN_; // ============ Variables for Final Settlement ============ uint256 public _BASE_CAPITAL_RECEIVE_QUOTE_; uint256 public _QUOTE_CAPITAL_RECEIVE_BASE_; mapping(address => bool) public _CLAIMED_; // ============ Modifiers ============ modifier onlySupervisorOrOwner() { require(msg.sender == _SUPERVISOR_ || msg.sender == _OWNER_, "NOT_SUPERVISOR_OR_OWNER"); _; } modifier notClosed() { require(!_CLOSED_, "DODO_CLOSED"); _; } // ============ Helper Functions ============ function _checkDODOParameters() internal view returns (uint256) { require(_K_ < DecimalMath.ONE, "K>=1"); require(_K_ > 0, "K=0"); require(_LP_FEE_RATE_.add(_MT_FEE_RATE_) < DecimalMath.ONE, "FEE_RATE>=1"); } function getOraclePrice() public view returns (uint256) { return IOracle(_ORACLE_).getPrice(); } function getBaseCapitalBalanceOf(address lp) public view returns (uint256) { return IDODOLpToken(_BASE_CAPITAL_TOKEN_).balanceOf(lp); } function getTotalBaseCapital() public view returns (uint256) { return IDODOLpToken(_BASE_CAPITAL_TOKEN_).totalSupply(); } function getQuoteCapitalBalanceOf(address lp) public view returns (uint256) { return IDODOLpToken(_QUOTE_CAPITAL_TOKEN_).balanceOf(lp); } function getTotalQuoteCapital() public view returns (uint256) { return IDODOLpToken(_QUOTE_CAPITAL_TOKEN_).totalSupply(); } // ============ Version Control ============ function version() external pure returns (uint256) { return 101; // 1.0.1 } } // File: contracts/intf/IDODOCallee.sol interface IDODOCallee { function dodoCall( bool isBuyBaseToken, uint256 baseAmount, uint256 quoteAmount, bytes calldata data ) external; } // File: contracts/lib/DODOMath.sol /** * @title DODOMath * @author DODO Breeder * * @notice Functions for complex calculating. Including ONE Integration and TWO Quadratic solutions */ library DODOMath { using SafeMath for uint256; /* Integrate dodo curve fron V1 to V2 require V0>=V1>=V2>0 res = (1-k)i(V1-V2)+ikV0*V0(1/V2-1/V1) let V1-V2=delta res = i*delta*(1-k+k(V0^2/V1/V2)) */ function _GeneralIntegrate( uint256 V0, uint256 V1, uint256 V2, uint256 i, uint256 k ) internal pure returns (uint256) { uint256 fairAmount = DecimalMath.mul(i, V1.sub(V2)); // i*delta uint256 V0V0V1V2 = DecimalMath.divCeil(V0.mul(V0).div(V1), V2); uint256 penalty = DecimalMath.mul(k, V0V0V1V2); // k(V0^2/V1/V2) return DecimalMath.mul(fairAmount, DecimalMath.ONE.sub(k).add(penalty)); } /* The same with integration expression above, we have: i*deltaB = (Q2-Q1)*(1-k+kQ0^2/Q1/Q2) Given Q1 and deltaB, solve Q2 This is a quadratic function and the standard version is aQ2^2 + bQ2 + c = 0, where a=1-k -b=(1-k)Q1-kQ0^2/Q1+i*deltaB c=-kQ0^2 and Q2=(-b+sqrt(b^2+4(1-k)kQ0^2))/2(1-k) note: another root is negative, abondan if deltaBSig=true, then Q2>Q1 if deltaBSig=false, then Q2<Q1 */ function _SolveQuadraticFunctionForTrade( uint256 Q0, uint256 Q1, uint256 ideltaB, bool deltaBSig, uint256 k ) internal pure returns (uint256) { // calculate -b value and sig // -b = (1-k)Q1-kQ0^2/Q1+i*deltaB uint256 kQ02Q1 = DecimalMath.mul(k, Q0).mul(Q0).div(Q1); // kQ0^2/Q1 uint256 b = DecimalMath.mul(DecimalMath.ONE.sub(k), Q1); // (1-k)Q1 bool minusbSig = true; if (deltaBSig) { b = b.add(ideltaB); // (1-k)Q1+i*deltaB } else { kQ02Q1 = kQ02Q1.add(ideltaB); // i*deltaB+kQ0^2/Q1 } if (b >= kQ02Q1) { b = b.sub(kQ02Q1); minusbSig = true; } else { b = kQ02Q1.sub(b); minusbSig = false; } // calculate sqrt uint256 squareRoot = DecimalMath.mul( DecimalMath.ONE.sub(k).mul(4), DecimalMath.mul(k, Q0).mul(Q0) ); // 4(1-k)kQ0^2 squareRoot = b.mul(b).add(squareRoot).sqrt(); // sqrt(b*b+4(1-k)kQ0*Q0) // final res uint256 denominator = DecimalMath.ONE.sub(k).mul(2); // 2(1-k) uint256 numerator; if (minusbSig) { numerator = b.add(squareRoot); } else { numerator = squareRoot.sub(b); } if (deltaBSig) { return DecimalMath.divFloor(numerator, denominator); } else { return DecimalMath.divCeil(numerator, denominator); } } /* Start from the integration function i*deltaB = (Q2-Q1)*(1-k+kQ0^2/Q1/Q2) Assume Q2=Q0, Given Q1 and deltaB, solve Q0 let fairAmount = i*deltaB */ function _SolveQuadraticFunctionForTarget( uint256 V1, uint256 k, uint256 fairAmount ) internal pure returns (uint256 V0) { // V0 = V1+V1*(sqrt-1)/2k uint256 sqrt = DecimalMath.divCeil(DecimalMath.mul(k, fairAmount).mul(4), V1); sqrt = sqrt.add(DecimalMath.ONE).mul(DecimalMath.ONE).sqrt(); uint256 premium = DecimalMath.divCeil(sqrt.sub(DecimalMath.ONE), k.mul(2)); // V0 is greater than or equal to V1 according to the solution return DecimalMath.mul(V1, DecimalMath.ONE.add(premium)); } } // File: contracts/impl/Pricing.sol /** * @title Pricing * @author DODO Breeder * * @notice DODO Pricing model */ contract Pricing is Storage { using SafeMath for uint256; // ============ R = 1 cases ============ function _ROneSellBaseToken(uint256 amount, uint256 targetQuoteTokenAmount) internal view returns (uint256 receiveQuoteToken) { uint256 i = getOraclePrice(); uint256 Q2 = DODOMath._SolveQuadraticFunctionForTrade( targetQuoteTokenAmount, targetQuoteTokenAmount, DecimalMath.mul(i, amount), false, _K_ ); // in theory Q2 <= targetQuoteTokenAmount // however when amount is close to 0, precision problems may cause Q2 > targetQuoteTokenAmount return targetQuoteTokenAmount.sub(Q2); } function _ROneBuyBaseToken(uint256 amount, uint256 targetBaseTokenAmount) internal view returns (uint256 payQuoteToken) { require(amount < targetBaseTokenAmount, "DODO_BASE_BALANCE_NOT_ENOUGH"); uint256 B2 = targetBaseTokenAmount.sub(amount); payQuoteToken = _RAboveIntegrate(targetBaseTokenAmount, targetBaseTokenAmount, B2); return payQuoteToken; } // ============ R < 1 cases ============ function _RBelowSellBaseToken( uint256 amount, uint256 quoteBalance, uint256 targetQuoteAmount ) internal view returns (uint256 receieQuoteToken) { uint256 i = getOraclePrice(); uint256 Q2 = DODOMath._SolveQuadraticFunctionForTrade( targetQuoteAmount, quoteBalance, DecimalMath.mul(i, amount), false, _K_ ); return quoteBalance.sub(Q2); } function _RBelowBuyBaseToken( uint256 amount, uint256 quoteBalance, uint256 targetQuoteAmount ) internal view returns (uint256 payQuoteToken) { // Here we don't require amount less than some value // Because it is limited at upper function // See Trader.queryBuyBaseToken uint256 i = getOraclePrice(); uint256 Q2 = DODOMath._SolveQuadraticFunctionForTrade( targetQuoteAmount, quoteBalance, DecimalMath.mulCeil(i, amount), true, _K_ ); return Q2.sub(quoteBalance); } function _RBelowBackToOne() internal view returns (uint256 payQuoteToken) { // important: carefully design the system to make sure spareBase always greater than or equal to 0 uint256 spareBase = _BASE_BALANCE_.sub(_TARGET_BASE_TOKEN_AMOUNT_); uint256 price = getOraclePrice(); uint256 fairAmount = DecimalMath.mul(spareBase, price); uint256 newTargetQuote = DODOMath._SolveQuadraticFunctionForTarget( _QUOTE_BALANCE_, _K_, fairAmount ); return newTargetQuote.sub(_QUOTE_BALANCE_); } // ============ R > 1 cases ============ function _RAboveBuyBaseToken( uint256 amount, uint256 baseBalance, uint256 targetBaseAmount ) internal view returns (uint256 payQuoteToken) { require(amount < baseBalance, "DODO_BASE_BALANCE_NOT_ENOUGH"); uint256 B2 = baseBalance.sub(amount); return _RAboveIntegrate(targetBaseAmount, baseBalance, B2); } function _RAboveSellBaseToken( uint256 amount, uint256 baseBalance, uint256 targetBaseAmount ) internal view returns (uint256 receiveQuoteToken) { // here we don't require B1 <= targetBaseAmount // Because it is limited at upper function // See Trader.querySellBaseToken uint256 B1 = baseBalance.add(amount); return _RAboveIntegrate(targetBaseAmount, B1, baseBalance); } function _RAboveBackToOne() internal view returns (uint256 payBaseToken) { // important: carefully design the system to make sure spareBase always greater than or equal to 0 uint256 spareQuote = _QUOTE_BALANCE_.sub(_TARGET_QUOTE_TOKEN_AMOUNT_); uint256 price = getOraclePrice(); uint256 fairAmount = DecimalMath.divFloor(spareQuote, price); uint256 newTargetBase = DODOMath._SolveQuadraticFunctionForTarget( _BASE_BALANCE_, _K_, fairAmount ); return newTargetBase.sub(_BASE_BALANCE_); } // ============ Helper functions ============ function getExpectedTarget() public view returns (uint256 baseTarget, uint256 quoteTarget) { uint256 Q = _QUOTE_BALANCE_; uint256 B = _BASE_BALANCE_; if (_R_STATUS_ == Types.RStatus.ONE) { return (_TARGET_BASE_TOKEN_AMOUNT_, _TARGET_QUOTE_TOKEN_AMOUNT_); } else if (_R_STATUS_ == Types.RStatus.BELOW_ONE) { uint256 payQuoteToken = _RBelowBackToOne(); return (_TARGET_BASE_TOKEN_AMOUNT_, Q.add(payQuoteToken)); } else if (_R_STATUS_ == Types.RStatus.ABOVE_ONE) { uint256 payBaseToken = _RAboveBackToOne(); return (B.add(payBaseToken), _TARGET_QUOTE_TOKEN_AMOUNT_); } } function getMidPrice() public view returns (uint256 midPrice) { (uint256 baseTarget, uint256 quoteTarget) = getExpectedTarget(); if (_R_STATUS_ == Types.RStatus.BELOW_ONE) { uint256 R = DecimalMath.divFloor( quoteTarget.mul(quoteTarget).div(_QUOTE_BALANCE_), _QUOTE_BALANCE_ ); R = DecimalMath.ONE.sub(_K_).add(DecimalMath.mul(_K_, R)); return DecimalMath.divFloor(getOraclePrice(), R); } else { uint256 R = DecimalMath.divFloor( baseTarget.mul(baseTarget).div(_BASE_BALANCE_), _BASE_BALANCE_ ); R = DecimalMath.ONE.sub(_K_).add(DecimalMath.mul(_K_, R)); return DecimalMath.mul(getOraclePrice(), R); } } function _RAboveIntegrate( uint256 B0, uint256 B1, uint256 B2 ) internal view returns (uint256) { uint256 i = getOraclePrice(); return DODOMath._GeneralIntegrate(B0, B1, B2, i, _K_); } // function _RBelowIntegrate( // uint256 Q0, // uint256 Q1, // uint256 Q2 // ) internal view returns (uint256) { // uint256 i = getOraclePrice(); // i = DecimalMath.divFloor(DecimalMath.ONE, i); // 1/i // return DODOMath._GeneralIntegrate(Q0, Q1, Q2, i, _K_); // } } // File: contracts/lib/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/impl/Settlement.sol /** * @title Settlement * @author DODO Breeder * * @notice Functions for assets settlement */ contract Settlement is Storage { using SafeMath for uint256; using SafeERC20 for IERC20; // ============ Events ============ event Donate(uint256 amount, bool isBaseToken); event ClaimAssets(address indexed user, uint256 baseTokenAmount, uint256 quoteTokenAmount); // ============ Assets IN/OUT Functions ============ function _baseTokenTransferIn(address from, uint256 amount) internal { require(_BASE_BALANCE_.add(amount) <= _BASE_BALANCE_LIMIT_, "BASE_BALANCE_LIMIT_EXCEEDED"); IERC20(_BASE_TOKEN_).safeTransferFrom(from, address(this), amount); _BASE_BALANCE_ = _BASE_BALANCE_.add(amount); } function _quoteTokenTransferIn(address from, uint256 amount) internal { require( _QUOTE_BALANCE_.add(amount) <= _QUOTE_BALANCE_LIMIT_, "QUOTE_BALANCE_LIMIT_EXCEEDED" ); IERC20(_QUOTE_TOKEN_).safeTransferFrom(from, address(this), amount); _QUOTE_BALANCE_ = _QUOTE_BALANCE_.add(amount); } function _baseTokenTransferOut(address to, uint256 amount) internal { IERC20(_BASE_TOKEN_).safeTransfer(to, amount); _BASE_BALANCE_ = _BASE_BALANCE_.sub(amount); } function _quoteTokenTransferOut(address to, uint256 amount) internal { IERC20(_QUOTE_TOKEN_).safeTransfer(to, amount); _QUOTE_BALANCE_ = _QUOTE_BALANCE_.sub(amount); } // ============ Donate to Liquidity Pool Functions ============ function _donateBaseToken(uint256 amount) internal { _TARGET_BASE_TOKEN_AMOUNT_ = _TARGET_BASE_TOKEN_AMOUNT_.add(amount); emit Donate(amount, true); } function _donateQuoteToken(uint256 amount) internal { _TARGET_QUOTE_TOKEN_AMOUNT_ = _TARGET_QUOTE_TOKEN_AMOUNT_.add(amount); emit Donate(amount, false); } function donateBaseToken(uint256 amount) external preventReentrant { _baseTokenTransferIn(msg.sender, amount); _donateBaseToken(amount); } function donateQuoteToken(uint256 amount) external preventReentrant { _quoteTokenTransferIn(msg.sender, amount); _donateQuoteToken(amount); } // ============ Final Settlement Functions ============ // last step to shut down dodo function finalSettlement() external onlyOwner notClosed { _CLOSED_ = true; _DEPOSIT_QUOTE_ALLOWED_ = false; _DEPOSIT_BASE_ALLOWED_ = false; _TRADE_ALLOWED_ = false; uint256 totalBaseCapital = getTotalBaseCapital(); uint256 totalQuoteCapital = getTotalQuoteCapital(); if (_QUOTE_BALANCE_ > _TARGET_QUOTE_TOKEN_AMOUNT_) { uint256 spareQuote = _QUOTE_BALANCE_.sub(_TARGET_QUOTE_TOKEN_AMOUNT_); _BASE_CAPITAL_RECEIVE_QUOTE_ = DecimalMath.divFloor(spareQuote, totalBaseCapital); } else { _TARGET_QUOTE_TOKEN_AMOUNT_ = _QUOTE_BALANCE_; } if (_BASE_BALANCE_ > _TARGET_BASE_TOKEN_AMOUNT_) { uint256 spareBase = _BASE_BALANCE_.sub(_TARGET_BASE_TOKEN_AMOUNT_); _QUOTE_CAPITAL_RECEIVE_BASE_ = DecimalMath.divFloor(spareBase, totalQuoteCapital); } else { _TARGET_BASE_TOKEN_AMOUNT_ = _BASE_BALANCE_; } _R_STATUS_ = Types.RStatus.ONE; } // claim remaining assets after final settlement function claimAssets() external preventReentrant { require(_CLOSED_, "DODO_NOT_CLOSED"); require(!_CLAIMED_[msg.sender], "ALREADY_CLAIMED"); _CLAIMED_[msg.sender] = true; uint256 quoteCapital = getQuoteCapitalBalanceOf(msg.sender); uint256 baseCapital = getBaseCapitalBalanceOf(msg.sender); uint256 quoteAmount = 0; if (quoteCapital > 0) { quoteAmount = _TARGET_QUOTE_TOKEN_AMOUNT_.mul(quoteCapital).div(getTotalQuoteCapital()); } uint256 baseAmount = 0; if (baseCapital > 0) { baseAmount = _TARGET_BASE_TOKEN_AMOUNT_.mul(baseCapital).div(getTotalBaseCapital()); } _TARGET_QUOTE_TOKEN_AMOUNT_ = _TARGET_QUOTE_TOKEN_AMOUNT_.sub(quoteAmount); _TARGET_BASE_TOKEN_AMOUNT_ = _TARGET_BASE_TOKEN_AMOUNT_.sub(baseAmount); quoteAmount = quoteAmount.add(DecimalMath.mul(baseCapital, _BASE_CAPITAL_RECEIVE_QUOTE_)); baseAmount = baseAmount.add(DecimalMath.mul(quoteCapital, _QUOTE_CAPITAL_RECEIVE_BASE_)); _baseTokenTransferOut(msg.sender, baseAmount); _quoteTokenTransferOut(msg.sender, quoteAmount); IDODOLpToken(_BASE_CAPITAL_TOKEN_).burn(msg.sender, baseCapital); IDODOLpToken(_QUOTE_CAPITAL_TOKEN_).burn(msg.sender, quoteCapital); emit ClaimAssets(msg.sender, baseAmount, quoteAmount); return; } // in case someone transfer to contract directly function retrieve(address token, uint256 amount) external onlyOwner { if (token == _BASE_TOKEN_) { require( IERC20(_BASE_TOKEN_).balanceOf(address(this)) >= _BASE_BALANCE_.add(amount), "DODO_BASE_BALANCE_NOT_ENOUGH" ); } if (token == _QUOTE_TOKEN_) { require( IERC20(_QUOTE_TOKEN_).balanceOf(address(this)) >= _QUOTE_BALANCE_.add(amount), "DODO_QUOTE_BALANCE_NOT_ENOUGH" ); } IERC20(token).safeTransfer(msg.sender, amount); } } // File: contracts/impl/Trader.sol /** * @title Trader * @author DODO Breeder * * @notice Functions for trader operations */ contract Trader is Storage, Pricing, Settlement { using SafeMath for uint256; // ============ Events ============ event SellBaseToken(address indexed seller, uint256 payBase, uint256 receiveQuote); event BuyBaseToken(address indexed buyer, uint256 receiveBase, uint256 payQuote); event ChargeMaintainerFee(address indexed maintainer, bool isBaseToken, uint256 amount); // ============ Modifiers ============ modifier tradeAllowed() { require(_TRADE_ALLOWED_, "TRADE_NOT_ALLOWED"); _; } modifier buyingAllowed() { require(_BUYING_ALLOWED_, "BUYING_NOT_ALLOWED"); _; } modifier sellingAllowed() { require(_SELLING_ALLOWED_, "SELLING_NOT_ALLOWED"); _; } modifier gasPriceLimit() { require(tx.gasprice <= _GAS_PRICE_LIMIT_, "GAS_PRICE_EXCEED"); _; } // ============ Trade Functions ============ function sellBaseToken( uint256 amount, uint256 minReceiveQuote, bytes calldata data ) external tradeAllowed sellingAllowed gasPriceLimit preventReentrant returns (uint256) { // query price ( uint256 receiveQuote, uint256 lpFeeQuote, uint256 mtFeeQuote, Types.RStatus newRStatus, uint256 newQuoteTarget, uint256 newBaseTarget ) = _querySellBaseToken(amount); require(receiveQuote >= minReceiveQuote, "SELL_BASE_RECEIVE_NOT_ENOUGH"); // settle assets _quoteTokenTransferOut(msg.sender, receiveQuote); if (data.length > 0) { IDODOCallee(msg.sender).dodoCall(false, amount, receiveQuote, data); } _baseTokenTransferIn(msg.sender, amount); if (mtFeeQuote != 0) { _quoteTokenTransferOut(_MAINTAINER_, mtFeeQuote); emit ChargeMaintainerFee(_MAINTAINER_, false, mtFeeQuote); } // update TARGET if (_TARGET_QUOTE_TOKEN_AMOUNT_ != newQuoteTarget) { _TARGET_QUOTE_TOKEN_AMOUNT_ = newQuoteTarget; } if (_TARGET_BASE_TOKEN_AMOUNT_ != newBaseTarget) { _TARGET_BASE_TOKEN_AMOUNT_ = newBaseTarget; } if (_R_STATUS_ != newRStatus) { _R_STATUS_ = newRStatus; } _donateQuoteToken(lpFeeQuote); emit SellBaseToken(msg.sender, amount, receiveQuote); return receiveQuote; } function buyBaseToken( uint256 amount, uint256 maxPayQuote, bytes calldata data ) external tradeAllowed buyingAllowed gasPriceLimit preventReentrant returns (uint256) { // query price ( uint256 payQuote, uint256 lpFeeBase, uint256 mtFeeBase, Types.RStatus newRStatus, uint256 newQuoteTarget, uint256 newBaseTarget ) = _queryBuyBaseToken(amount); require(payQuote <= maxPayQuote, "BUY_BASE_COST_TOO_MUCH"); // settle assets _baseTokenTransferOut(msg.sender, amount); if (data.length > 0) { IDODOCallee(msg.sender).dodoCall(true, amount, payQuote, data); } _quoteTokenTransferIn(msg.sender, payQuote); if (mtFeeBase != 0) { _baseTokenTransferOut(_MAINTAINER_, mtFeeBase); emit ChargeMaintainerFee(_MAINTAINER_, true, mtFeeBase); } // update TARGET if (_TARGET_QUOTE_TOKEN_AMOUNT_ != newQuoteTarget) { _TARGET_QUOTE_TOKEN_AMOUNT_ = newQuoteTarget; } if (_TARGET_BASE_TOKEN_AMOUNT_ != newBaseTarget) { _TARGET_BASE_TOKEN_AMOUNT_ = newBaseTarget; } if (_R_STATUS_ != newRStatus) { _R_STATUS_ = newRStatus; } _donateBaseToken(lpFeeBase); emit BuyBaseToken(msg.sender, amount, payQuote); return payQuote; } // ============ Query Functions ============ function querySellBaseToken(uint256 amount) external view returns (uint256 receiveQuote) { (receiveQuote, , , , , ) = _querySellBaseToken(amount); return receiveQuote; } function queryBuyBaseToken(uint256 amount) external view returns (uint256 payQuote) { (payQuote, , , , , ) = _queryBuyBaseToken(amount); return payQuote; } function _querySellBaseToken(uint256 amount) internal view returns ( uint256 receiveQuote, uint256 lpFeeQuote, uint256 mtFeeQuote, Types.RStatus newRStatus, uint256 newQuoteTarget, uint256 newBaseTarget ) { (newBaseTarget, newQuoteTarget) = getExpectedTarget(); uint256 sellBaseAmount = amount; if (_R_STATUS_ == Types.RStatus.ONE) { // case 1: R=1 // R falls below one receiveQuote = _ROneSellBaseToken(sellBaseAmount, newQuoteTarget); newRStatus = Types.RStatus.BELOW_ONE; } else if (_R_STATUS_ == Types.RStatus.ABOVE_ONE) { uint256 backToOnePayBase = newBaseTarget.sub(_BASE_BALANCE_); uint256 backToOneReceiveQuote = _QUOTE_BALANCE_.sub(newQuoteTarget); // case 2: R>1 // complex case, R status depends on trading amount if (sellBaseAmount < backToOnePayBase) { // case 2.1: R status do not change receiveQuote = _RAboveSellBaseToken(sellBaseAmount, _BASE_BALANCE_, newBaseTarget); newRStatus = Types.RStatus.ABOVE_ONE; if (receiveQuote > backToOneReceiveQuote) { // [Important corner case!] may enter this branch when some precision problem happens. And consequently contribute to negative spare quote amount // to make sure spare quote>=0, mannually set receiveQuote=backToOneReceiveQuote receiveQuote = backToOneReceiveQuote; } } else if (sellBaseAmount == backToOnePayBase) { // case 2.2: R status changes to ONE receiveQuote = backToOneReceiveQuote; newRStatus = Types.RStatus.ONE; } else { // case 2.3: R status changes to BELOW_ONE receiveQuote = backToOneReceiveQuote.add( _ROneSellBaseToken(sellBaseAmount.sub(backToOnePayBase), newQuoteTarget) ); newRStatus = Types.RStatus.BELOW_ONE; } } else { // _R_STATUS_ == Types.RStatus.BELOW_ONE // case 3: R<1 receiveQuote = _RBelowSellBaseToken(sellBaseAmount, _QUOTE_BALANCE_, newQuoteTarget); newRStatus = Types.RStatus.BELOW_ONE; } // count fees lpFeeQuote = DecimalMath.mul(receiveQuote, _LP_FEE_RATE_); mtFeeQuote = DecimalMath.mul(receiveQuote, _MT_FEE_RATE_); receiveQuote = receiveQuote.sub(lpFeeQuote).sub(mtFeeQuote); return (receiveQuote, lpFeeQuote, mtFeeQuote, newRStatus, newQuoteTarget, newBaseTarget); } function _queryBuyBaseToken(uint256 amount) internal view returns ( uint256 payQuote, uint256 lpFeeBase, uint256 mtFeeBase, Types.RStatus newRStatus, uint256 newQuoteTarget, uint256 newBaseTarget ) { (newBaseTarget, newQuoteTarget) = getExpectedTarget(); // charge fee from user receive amount lpFeeBase = DecimalMath.mul(amount, _LP_FEE_RATE_); mtFeeBase = DecimalMath.mul(amount, _MT_FEE_RATE_); uint256 buyBaseAmount = amount.add(lpFeeBase).add(mtFeeBase); if (_R_STATUS_ == Types.RStatus.ONE) { // case 1: R=1 payQuote = _ROneBuyBaseToken(buyBaseAmount, newBaseTarget); newRStatus = Types.RStatus.ABOVE_ONE; } else if (_R_STATUS_ == Types.RStatus.ABOVE_ONE) { // case 2: R>1 payQuote = _RAboveBuyBaseToken(buyBaseAmount, _BASE_BALANCE_, newBaseTarget); newRStatus = Types.RStatus.ABOVE_ONE; } else if (_R_STATUS_ == Types.RStatus.BELOW_ONE) { uint256 backToOnePayQuote = newQuoteTarget.sub(_QUOTE_BALANCE_); uint256 backToOneReceiveBase = _BASE_BALANCE_.sub(newBaseTarget); // case 3: R<1 // complex case, R status may change if (buyBaseAmount < backToOneReceiveBase) { // case 3.1: R status do not change // no need to check payQuote because spare base token must be greater than zero payQuote = _RBelowBuyBaseToken(buyBaseAmount, _QUOTE_BALANCE_, newQuoteTarget); newRStatus = Types.RStatus.BELOW_ONE; } else if (buyBaseAmount == backToOneReceiveBase) { // case 3.2: R status changes to ONE payQuote = backToOnePayQuote; newRStatus = Types.RStatus.ONE; } else { // case 3.3: R status changes to ABOVE_ONE payQuote = backToOnePayQuote.add( _ROneBuyBaseToken(buyBaseAmount.sub(backToOneReceiveBase), newBaseTarget) ); newRStatus = Types.RStatus.ABOVE_ONE; } } return (payQuote, lpFeeBase, mtFeeBase, newRStatus, newQuoteTarget, newBaseTarget); } } // File: contracts/impl/LiquidityProvider.sol /** * @title LiquidityProvider * @author DODO Breeder * * @notice Functions for liquidity provider operations */ contract LiquidityProvider is Storage, Pricing, Settlement { using SafeMath for uint256; // ============ Events ============ event Deposit( address indexed payer, address indexed receiver, bool isBaseToken, uint256 amount, uint256 lpTokenAmount ); event Withdraw( address indexed payer, address indexed receiver, bool isBaseToken, uint256 amount, uint256 lpTokenAmount ); event ChargePenalty(address indexed payer, bool isBaseToken, uint256 amount); // ============ Modifiers ============ modifier depositQuoteAllowed() { require(_DEPOSIT_QUOTE_ALLOWED_, "DEPOSIT_QUOTE_NOT_ALLOWED"); _; } modifier depositBaseAllowed() { require(_DEPOSIT_BASE_ALLOWED_, "DEPOSIT_BASE_NOT_ALLOWED"); _; } modifier dodoNotClosed() { require(!_CLOSED_, "DODO_CLOSED"); _; } // ============ Routine Functions ============ function withdrawBase(uint256 amount) external returns (uint256) { return withdrawBaseTo(msg.sender, amount); } function depositBase(uint256 amount) external returns (uint256) { return depositBaseTo(msg.sender, amount); } function withdrawQuote(uint256 amount) external returns (uint256) { return withdrawQuoteTo(msg.sender, amount); } function depositQuote(uint256 amount) external returns (uint256) { return depositQuoteTo(msg.sender, amount); } function withdrawAllBase() external returns (uint256) { return withdrawAllBaseTo(msg.sender); } function withdrawAllQuote() external returns (uint256) { return withdrawAllQuoteTo(msg.sender); } // ============ Deposit Functions ============ function depositQuoteTo(address to, uint256 amount) public preventReentrant depositQuoteAllowed returns (uint256) { (, uint256 quoteTarget) = getExpectedTarget(); uint256 totalQuoteCapital = getTotalQuoteCapital(); uint256 capital = amount; if (totalQuoteCapital == 0) { // give remaining quote token to lp as a gift capital = amount.add(quoteTarget); } else if (quoteTarget > 0) { capital = amount.mul(totalQuoteCapital).div(quoteTarget); } // settlement _quoteTokenTransferIn(msg.sender, amount); _mintQuoteCapital(to, capital); _TARGET_QUOTE_TOKEN_AMOUNT_ = _TARGET_QUOTE_TOKEN_AMOUNT_.add(amount); emit Deposit(msg.sender, to, false, amount, capital); return capital; } function depositBaseTo(address to, uint256 amount) public preventReentrant depositBaseAllowed returns (uint256) { (uint256 baseTarget, ) = getExpectedTarget(); uint256 totalBaseCapital = getTotalBaseCapital(); uint256 capital = amount; if (totalBaseCapital == 0) { // give remaining base token to lp as a gift capital = amount.add(baseTarget); } else if (baseTarget > 0) { capital = amount.mul(totalBaseCapital).div(baseTarget); } // settlement _baseTokenTransferIn(msg.sender, amount); _mintBaseCapital(to, capital); _TARGET_BASE_TOKEN_AMOUNT_ = _TARGET_BASE_TOKEN_AMOUNT_.add(amount); emit Deposit(msg.sender, to, true, amount, capital); return capital; } // ============ Withdraw Functions ============ function withdrawQuoteTo(address to, uint256 amount) public preventReentrant dodoNotClosed returns (uint256) { // calculate capital (, uint256 quoteTarget) = getExpectedTarget(); uint256 totalQuoteCapital = getTotalQuoteCapital(); require(totalQuoteCapital > 0, "NO_QUOTE_LP"); uint256 requireQuoteCapital = amount.mul(totalQuoteCapital).divCeil(quoteTarget); require( requireQuoteCapital <= getQuoteCapitalBalanceOf(msg.sender), "LP_QUOTE_CAPITAL_BALANCE_NOT_ENOUGH" ); // handle penalty, penalty may exceed amount uint256 penalty = getWithdrawQuotePenalty(amount); require(penalty < amount, "PENALTY_EXCEED"); // settlement _TARGET_QUOTE_TOKEN_AMOUNT_ = _TARGET_QUOTE_TOKEN_AMOUNT_.sub(amount); _burnQuoteCapital(msg.sender, requireQuoteCapital); _quoteTokenTransferOut(to, amount.sub(penalty)); _donateQuoteToken(penalty); emit Withdraw(msg.sender, to, false, amount.sub(penalty), requireQuoteCapital); emit ChargePenalty(msg.sender, false, penalty); return amount.sub(penalty); } function withdrawBaseTo(address to, uint256 amount) public preventReentrant dodoNotClosed returns (uint256) { // calculate capital (uint256 baseTarget, ) = getExpectedTarget(); uint256 totalBaseCapital = getTotalBaseCapital(); require(totalBaseCapital > 0, "NO_BASE_LP"); uint256 requireBaseCapital = amount.mul(totalBaseCapital).divCeil(baseTarget); require( requireBaseCapital <= getBaseCapitalBalanceOf(msg.sender), "LP_BASE_CAPITAL_BALANCE_NOT_ENOUGH" ); // handle penalty, penalty may exceed amount uint256 penalty = getWithdrawBasePenalty(amount); require(penalty <= amount, "PENALTY_EXCEED"); // settlement _TARGET_BASE_TOKEN_AMOUNT_ = _TARGET_BASE_TOKEN_AMOUNT_.sub(amount); _burnBaseCapital(msg.sender, requireBaseCapital); _baseTokenTransferOut(to, amount.sub(penalty)); _donateBaseToken(penalty); emit Withdraw(msg.sender, to, true, amount.sub(penalty), requireBaseCapital); emit ChargePenalty(msg.sender, true, penalty); return amount.sub(penalty); } // ============ Withdraw all Functions ============ function withdrawAllQuoteTo(address to) public preventReentrant dodoNotClosed returns (uint256) { uint256 withdrawAmount = getLpQuoteBalance(msg.sender); uint256 capital = getQuoteCapitalBalanceOf(msg.sender); // handle penalty, penalty may exceed amount uint256 penalty = getWithdrawQuotePenalty(withdrawAmount); require(penalty <= withdrawAmount, "PENALTY_EXCEED"); // settlement _TARGET_QUOTE_TOKEN_AMOUNT_ = _TARGET_QUOTE_TOKEN_AMOUNT_.sub(withdrawAmount); _burnQuoteCapital(msg.sender, capital); _quoteTokenTransferOut(to, withdrawAmount.sub(penalty)); _donateQuoteToken(penalty); emit Withdraw(msg.sender, to, false, withdrawAmount, capital); emit ChargePenalty(msg.sender, false, penalty); return withdrawAmount.sub(penalty); } function withdrawAllBaseTo(address to) public preventReentrant dodoNotClosed returns (uint256) { uint256 withdrawAmount = getLpBaseBalance(msg.sender); uint256 capital = getBaseCapitalBalanceOf(msg.sender); // handle penalty, penalty may exceed amount uint256 penalty = getWithdrawBasePenalty(withdrawAmount); require(penalty <= withdrawAmount, "PENALTY_EXCEED"); // settlement _TARGET_BASE_TOKEN_AMOUNT_ = _TARGET_BASE_TOKEN_AMOUNT_.sub(withdrawAmount); _burnBaseCapital(msg.sender, capital); _baseTokenTransferOut(to, withdrawAmount.sub(penalty)); _donateBaseToken(penalty); emit Withdraw(msg.sender, to, true, withdrawAmount, capital); emit ChargePenalty(msg.sender, true, penalty); return withdrawAmount.sub(penalty); } // ============ Helper Functions ============ function _mintBaseCapital(address user, uint256 amount) internal { IDODOLpToken(_BASE_CAPITAL_TOKEN_).mint(user, amount); } function _mintQuoteCapital(address user, uint256 amount) internal { IDODOLpToken(_QUOTE_CAPITAL_TOKEN_).mint(user, amount); } function _burnBaseCapital(address user, uint256 amount) internal { IDODOLpToken(_BASE_CAPITAL_TOKEN_).burn(user, amount); } function _burnQuoteCapital(address user, uint256 amount) internal { IDODOLpToken(_QUOTE_CAPITAL_TOKEN_).burn(user, amount); } // ============ Getter Functions ============ function getLpBaseBalance(address lp) public view returns (uint256 lpBalance) { uint256 totalBaseCapital = getTotalBaseCapital(); (uint256 baseTarget, ) = getExpectedTarget(); if (totalBaseCapital == 0) { return 0; } lpBalance = getBaseCapitalBalanceOf(lp).mul(baseTarget).div(totalBaseCapital); return lpBalance; } function getLpQuoteBalance(address lp) public view returns (uint256 lpBalance) { uint256 totalQuoteCapital = getTotalQuoteCapital(); (, uint256 quoteTarget) = getExpectedTarget(); if (totalQuoteCapital == 0) { return 0; } lpBalance = getQuoteCapitalBalanceOf(lp).mul(quoteTarget).div(totalQuoteCapital); return lpBalance; } function getWithdrawQuotePenalty(uint256 amount) public view returns (uint256 penalty) { require(amount <= _QUOTE_BALANCE_, "DODO_QUOTE_BALANCE_NOT_ENOUGH"); if (_R_STATUS_ == Types.RStatus.BELOW_ONE) { uint256 spareBase = _BASE_BALANCE_.sub(_TARGET_BASE_TOKEN_AMOUNT_); uint256 price = getOraclePrice(); uint256 fairAmount = DecimalMath.mul(spareBase, price); uint256 targetQuote = DODOMath._SolveQuadraticFunctionForTarget( _QUOTE_BALANCE_, _K_, fairAmount ); // if amount = _QUOTE_BALANCE_, div error uint256 targetQuoteWithWithdraw = DODOMath._SolveQuadraticFunctionForTarget( _QUOTE_BALANCE_.sub(amount), _K_, fairAmount ); return targetQuote.sub(targetQuoteWithWithdraw.add(amount)); } else { return 0; } } function getWithdrawBasePenalty(uint256 amount) public view returns (uint256 penalty) { require(amount <= _BASE_BALANCE_, "DODO_BASE_BALANCE_NOT_ENOUGH"); if (_R_STATUS_ == Types.RStatus.ABOVE_ONE) { uint256 spareQuote = _QUOTE_BALANCE_.sub(_TARGET_QUOTE_TOKEN_AMOUNT_); uint256 price = getOraclePrice(); uint256 fairAmount = DecimalMath.divFloor(spareQuote, price); uint256 targetBase = DODOMath._SolveQuadraticFunctionForTarget( _BASE_BALANCE_, _K_, fairAmount ); // if amount = _BASE_BALANCE_, div error uint256 targetBaseWithWithdraw = DODOMath._SolveQuadraticFunctionForTarget( _BASE_BALANCE_.sub(amount), _K_, fairAmount ); return targetBase.sub(targetBaseWithWithdraw.add(amount)); } else { return 0; } } } // File: contracts/impl/Admin.sol /** * @title Admin * @author DODO Breeder * * @notice Functions for admin operations */ contract Admin is Storage { // ============ Events ============ event UpdateGasPriceLimit(uint256 oldGasPriceLimit, uint256 newGasPriceLimit); event UpdateLiquidityProviderFeeRate( uint256 oldLiquidityProviderFeeRate, uint256 newLiquidityProviderFeeRate ); event UpdateMaintainerFeeRate(uint256 oldMaintainerFeeRate, uint256 newMaintainerFeeRate); event UpdateK(uint256 oldK, uint256 newK); // ============ Params Setting Functions ============ function setOracle(address newOracle) external onlyOwner { _ORACLE_ = newOracle; } function setSupervisor(address newSupervisor) external onlyOwner { _SUPERVISOR_ = newSupervisor; } function setMaintainer(address newMaintainer) external onlyOwner { _MAINTAINER_ = newMaintainer; } function setLiquidityProviderFeeRate(uint256 newLiquidityPorviderFeeRate) external onlyOwner { emit UpdateLiquidityProviderFeeRate(_LP_FEE_RATE_, newLiquidityPorviderFeeRate); _LP_FEE_RATE_ = newLiquidityPorviderFeeRate; _checkDODOParameters(); } function setMaintainerFeeRate(uint256 newMaintainerFeeRate) external onlyOwner { emit UpdateMaintainerFeeRate(_MT_FEE_RATE_, newMaintainerFeeRate); _MT_FEE_RATE_ = newMaintainerFeeRate; _checkDODOParameters(); } function setK(uint256 newK) external onlyOwner { emit UpdateK(_K_, newK); _K_ = newK; _checkDODOParameters(); } function setGasPriceLimit(uint256 newGasPriceLimit) external onlySupervisorOrOwner { emit UpdateGasPriceLimit(_GAS_PRICE_LIMIT_, newGasPriceLimit); _GAS_PRICE_LIMIT_ = newGasPriceLimit; } // ============ System Control Functions ============ function disableTrading() external onlySupervisorOrOwner { _TRADE_ALLOWED_ = false; } function enableTrading() external onlyOwner notClosed { _TRADE_ALLOWED_ = true; } function disableQuoteDeposit() external onlySupervisorOrOwner { _DEPOSIT_QUOTE_ALLOWED_ = false; } function enableQuoteDeposit() external onlyOwner notClosed { _DEPOSIT_QUOTE_ALLOWED_ = true; } function disableBaseDeposit() external onlySupervisorOrOwner { _DEPOSIT_BASE_ALLOWED_ = false; } function enableBaseDeposit() external onlyOwner notClosed { _DEPOSIT_BASE_ALLOWED_ = true; } // ============ Advanced Control Functions ============ function disableBuying() external onlySupervisorOrOwner { _BUYING_ALLOWED_ = false; } function enableBuying() external onlyOwner notClosed { _BUYING_ALLOWED_ = true; } function disableSelling() external onlySupervisorOrOwner { _SELLING_ALLOWED_ = false; } function enableSelling() external onlyOwner notClosed { _SELLING_ALLOWED_ = true; } function setBaseBalanceLimit(uint256 newBaseBalanceLimit) external onlyOwner notClosed { _BASE_BALANCE_LIMIT_ = newBaseBalanceLimit; } function setQuoteBalanceLimit(uint256 newQuoteBalanceLimit) external onlyOwner notClosed { _QUOTE_BALANCE_LIMIT_ = newQuoteBalanceLimit; } } // File: contracts/lib/Ownable.sol /** * @title Ownable * @author DODO Breeder * * @notice Ownership related functions */ contract Ownable { address public _OWNER_; address public _NEW_OWNER_; // ============ Events ============ event OwnershipTransferPrepared(address indexed previousOwner, address indexed newOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // ============ Modifiers ============ modifier onlyOwner() { require(msg.sender == _OWNER_, "NOT_OWNER"); _; } // ============ Functions ============ constructor() internal { _OWNER_ = msg.sender; emit OwnershipTransferred(address(0), _OWNER_); } function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0), "INVALID_OWNER"); emit OwnershipTransferPrepared(_OWNER_, newOwner); _NEW_OWNER_ = newOwner; } function claimOwnership() external { require(msg.sender == _NEW_OWNER_, "INVALID_CLAIM"); emit OwnershipTransferred(_OWNER_, _NEW_OWNER_); _OWNER_ = _NEW_OWNER_; _NEW_OWNER_ = address(0); } } // File: contracts/impl/DODOLpToken.sol /** * @title DODOLpToken * @author DODO Breeder * * @notice Tokenize liquidity pool assets. An ordinary ERC20 contract with mint and burn functions */ contract DODOLpToken is Ownable { using SafeMath for uint256; string public symbol = "DLP"; address public originToken; uint256 public totalSupply; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; // ============ Events ============ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); event Mint(address indexed user, uint256 value); event Burn(address indexed user, uint256 value); // ============ Functions ============ constructor(address _originToken) public { originToken = _originToken; } function name() public view returns (string memory) { string memory lpTokenSuffix = "_DODO_LP_TOKEN_"; return string(abi.encodePacked(IERC20(originToken).name(), lpTokenSuffix)); } function decimals() public view returns (uint8) { return IERC20(originToken).decimals(); } /** * @dev transfer token for a specified address * @param to The address to transfer to. * @param amount The amount to be transferred. */ function transfer(address to, uint256 amount) public returns (bool) { require(amount <= balances[msg.sender], "BALANCE_NOT_ENOUGH"); balances[msg.sender] = balances[msg.sender].sub(amount); balances[to] = balances[to].add(amount); emit Transfer(msg.sender, to, amount); return true; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the the balance of. * @return balance An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) external view returns (uint256 balance) { return balances[owner]; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param amount uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 amount ) public returns (bool) { require(amount <= balances[from], "BALANCE_NOT_ENOUGH"); require(amount <= allowed[from][msg.sender], "ALLOWANCE_NOT_ENOUGH"); balances[from] = balances[from].sub(amount); balances[to] = balances[to].add(amount); allowed[from][msg.sender] = allowed[from][msg.sender].sub(amount); emit Transfer(from, to, amount); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param spender The address which will spend the funds. * @param amount The amount of tokens to be spent. */ function approve(address spender, uint256 amount) public returns (bool) { allowed[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return allowed[owner][spender]; } function mint(address user, uint256 value) external onlyOwner { balances[user] = balances[user].add(value); totalSupply = totalSupply.add(value); emit Mint(user, value); emit Transfer(address(0), user, value); } function burn(address user, uint256 value) external onlyOwner { balances[user] = balances[user].sub(value); totalSupply = totalSupply.sub(value); emit Burn(user, value); emit Transfer(user, address(0), value); } } // File: contracts/dodo.sol /** * @title DODO * @author DODO Breeder * * @notice Entrance for users */ contract DODO is Admin, Trader, LiquidityProvider { function init( address owner, address supervisor, address maintainer, address baseToken, address quoteToken, address oracle, uint256 lpFeeRate, uint256 mtFeeRate, uint256 k, uint256 gasPriceLimit ) external { require(!_INITIALIZED_, "DODO_INITIALIZED"); _INITIALIZED_ = true; // constructor _OWNER_ = owner; emit OwnershipTransferred(address(0), _OWNER_); _SUPERVISOR_ = supervisor; _MAINTAINER_ = maintainer; _BASE_TOKEN_ = baseToken; _QUOTE_TOKEN_ = quoteToken; _ORACLE_ = oracle; _DEPOSIT_BASE_ALLOWED_ = false; _DEPOSIT_QUOTE_ALLOWED_ = false; _TRADE_ALLOWED_ = false; _GAS_PRICE_LIMIT_ = gasPriceLimit; // Advanced controls are disabled by default _BUYING_ALLOWED_ = true; _SELLING_ALLOWED_ = true; uint256 MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; _BASE_BALANCE_LIMIT_ = MAX_INT; _QUOTE_BALANCE_LIMIT_ = MAX_INT; _LP_FEE_RATE_ = lpFeeRate; _MT_FEE_RATE_ = mtFeeRate; _K_ = k; _R_STATUS_ = Types.RStatus.ONE; _BASE_CAPITAL_TOKEN_ = address(new DODOLpToken(_BASE_TOKEN_)); _QUOTE_CAPITAL_TOKEN_ = address(new DODOLpToken(_QUOTE_TOKEN_)); _checkDODOParameters(); } }
last step to shut down dodo
function finalSettlement() external onlyOwner notClosed { _CLOSED_ = true; _DEPOSIT_QUOTE_ALLOWED_ = false; _DEPOSIT_BASE_ALLOWED_ = false; _TRADE_ALLOWED_ = false; uint256 totalBaseCapital = getTotalBaseCapital(); uint256 totalQuoteCapital = getTotalQuoteCapital(); if (_QUOTE_BALANCE_ > _TARGET_QUOTE_TOKEN_AMOUNT_) { uint256 spareQuote = _QUOTE_BALANCE_.sub(_TARGET_QUOTE_TOKEN_AMOUNT_); _BASE_CAPITAL_RECEIVE_QUOTE_ = DecimalMath.divFloor(spareQuote, totalBaseCapital); _TARGET_QUOTE_TOKEN_AMOUNT_ = _QUOTE_BALANCE_; } if (_BASE_BALANCE_ > _TARGET_BASE_TOKEN_AMOUNT_) { uint256 spareBase = _BASE_BALANCE_.sub(_TARGET_BASE_TOKEN_AMOUNT_); _QUOTE_CAPITAL_RECEIVE_BASE_ = DecimalMath.divFloor(spareBase, totalQuoteCapital); _TARGET_BASE_TOKEN_AMOUNT_ = _BASE_BALANCE_; } _R_STATUS_ = Types.RStatus.ONE; }
2,176,721
./full_match/7700/0x4f07f0a2AE51ac40fb5FbdDaC242B5D22Cc0C992/sources/contracts/Plebness.sol
@inheritdoc IPlebness
function getSpreadForJacketAssets() external view override returns (uint256) { return jacketSpreadFactor; }
4,649,794
// SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.8.0; import {AddressIsContract} from "@animoca/ethereum-contracts-core/contracts/utils/types/AddressIsContract.sol"; import {IERC165} from "@animoca/ethereum-contracts-core/contracts/introspection/IERC165.sol"; import {IERC721} from "./interfaces/IERC721.sol"; import {IERC721Events} from "./interfaces/IERC721Events.sol"; import {IERC721Receiver} from "./interfaces/IERC721Receiver.sol"; import {ManagedIdentity} from "@animoca/ethereum-contracts-core/contracts/metatx/ManagedIdentity.sol"; /** * @title ERC721 Non Fungible Token Contract, simple implementation. */ contract ERC721Simple is ManagedIdentity, IERC165, IERC721, IERC721Events { using AddressIsContract for address; bytes4 internal constant _ERC721_RECEIVED = type(IERC721Receiver).interfaceId; uint256 internal constant _APPROVAL_BIT_TOKEN_OWNER_ = 1 << 160; /* owner => operator => approved */ mapping(address => mapping(address => bool)) internal _operators; /* NFT ID => owner */ mapping(uint256 => uint256) internal _owners; /* owner => NFT balance */ mapping(address => uint256) internal _nftBalances; /* NFT ID => operator */ mapping(uint256 => address) internal _nftApprovals; //======================================================= ERC165 ========================================================// /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId || interfaceId == type(IERC721).interfaceId; } //======================================================= ERC721 ========================================================// /// @inheritdoc IERC721 function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: zero address"); return _nftBalances[owner]; } /// @inheritdoc IERC721 function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = address(uint160(_owners[tokenId])); require(owner != address(0), "ERC721: non-existing NFT"); return owner; } /// @inheritdoc IERC721 function approve(address to, uint256 tokenId) public virtual override { uint256 owner = _owners[tokenId]; require(owner != 0, "ERC721: non-existing NFT"); address ownerAddress = address(uint160(owner)); require(to != ownerAddress, "ERC721: self-approval"); require(_isOperatable(ownerAddress, _msgSender()), "ERC721: non-approved sender"); if (to == address(0)) { if (owner & _APPROVAL_BIT_TOKEN_OWNER_ != 0) { // remove the approval bit if it is present _owners[tokenId] = uint256(ownerAddress); } } else { uint256 ownerWithApprovalBit = owner | _APPROVAL_BIT_TOKEN_OWNER_; if (owner != ownerWithApprovalBit) { // add the approval bit if it is not present _owners[tokenId] = ownerWithApprovalBit; } _nftApprovals[tokenId] = to; } emit Approval(ownerAddress, to, tokenId); } /// @inheritdoc IERC721 function getApproved(uint256 tokenId) public view virtual override returns (address) { uint256 owner = _owners[tokenId]; require(address(uint160(owner)) != address(0), "ERC721: non-existing NFT"); if (owner & _APPROVAL_BIT_TOKEN_OWNER_ != 0) { return _nftApprovals[tokenId]; } else { return address(0); } } /// @inheritdoc IERC721 function setApprovalForAll(address operator, bool approved) public virtual override { address sender = _msgSender(); require(operator != sender, "ERC721: self-approval"); _operators[sender][operator] = approved; emit ApprovalForAll(sender, operator, approved); } /// @inheritdoc IERC721 function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operators[owner][operator]; } /// @inheritdoc IERC721 function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transferFrom( from, to, tokenId, "", /* safe */ false ); } /// @inheritdoc IERC721 function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { _transferFrom( from, to, tokenId, "", /* safe */ true ); } /// @inheritdoc IERC721 function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public virtual override { _transferFrom( from, to, tokenId, data, /* safe */ true ); } //============================================ High-level Internal Functions ============================================// function _transferFrom( address from, address to, uint256 tokenId, bytes memory data, bool safe ) internal virtual { require(to != address(0), "ERC721: transfer to zero"); address sender = _msgSender(); bool operatable = _isOperatable(from, sender); uint256 owner = _owners[tokenId]; require(from == address(uint160(owner)), "ERC721: non-owned NFT"); if (!operatable) { require((owner & _APPROVAL_BIT_TOKEN_OWNER_ != 0) && _msgSender() == _nftApprovals[tokenId], "ERC721: non-approved sender"); } _owners[tokenId] = uint256(uint160(to)); if (from != to) { // cannot underflow as balance is verified through ownership --_nftBalances[from]; // cannot overflow as supply cannot overflow ++_nftBalances[to]; } emit Transfer(from, to, tokenId); if (safe && to.isContract()) { require(IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) == _ERC721_RECEIVED, "ERC721: transfer refused"); } } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to zero"); require(_owners[tokenId] == 0, "ERC721: existing NFT"); _owners[tokenId] = uint256(uint160(to)); // cannot overflow due to the cost of minting individual tokens ++_nftBalances[to]; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = address(uint160(_owners[tokenId])); require(owner != address(0), "ERC721: non-existing NFT"); _owners[tokenId] = 0; // cannot underflow as balance is verified through NFT ownership --_nftBalances[owner]; emit Transfer(owner, address(0), tokenId); } //============================================== Internal Helper Functions ==============================================// /** * Returns whether `sender` is authorised to make a transfer on behalf of `from`. * @param from The address to check operatibility upon. * @param sender The sender address. * @return True if sender is `from` or an operator for `from`, false otherwise. */ function _isOperatable(address from, address sender) internal view returns (bool) { return (from == sender) || _operators[from][sender]; } }
@inheritdoc IERC721
function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: zero address"); return _nftBalances[owner]; }
6,348,185