file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/* ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Synthetix: Pyramid.sol * * Docs: https://docs.synthetix.io/ * * * MIT License * =========== * * Copyright (c) 2020 Synthetix * * 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 */ // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } 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/contracts/math/SafeMath.sol pragma solidity ^0.5.0; 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) { // 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; } 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; } } // File: @openzeppelin/contracts/ownership/Ownable.sol contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: eth-token-recover/contracts/TokenRecover.sol contract TokenRecover is Ownable { function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { function totalStaked() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function burn(uint256 amount, uint256 bRate) external returns(uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing 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. */ 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. // 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 != 0x0 && codehash != accountHash); } /** * @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 /** * @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/IRewardDistributionRecipient.sol contract IRewardDistributionRecipient is Ownable { address public rewardDistribution; function notifyRewardAmount(uint256 reward) external; modifier onlyRewardDistribution() { require(msg.sender == rewardDistribution, "Caller is not reward distribution"); _; } function setRewardDistribution(address _rewardDistribution) external onlyOwner { rewardDistribution = _rewardDistribution; } } // File: contracts/CurveRewards.sol contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; event Stake(address staker, uint256 amount, uint256 operateAmount); IERC20 public rugStake; uint256 burnRate = 3; uint256 redistributeRate = 7; uint256 internal _totalDividends; uint256 internal _totalStaked; uint256 internal _dividendsPerRug; mapping(address => uint256) internal _stakeAmount; mapping(address => uint256) internal _dividendsSnapshot; // Get "position" relative to _totalDividends mapping(address => uint256) internal _userDividends; function totalStaked() public view returns (uint256) { return _totalStaked; } function totalDividends() public view returns (uint256) { return _totalDividends; } function balanceOf(address account) public view returns (uint256) { return _stakeAmount[account]; } function checkUserPayout(address staker) public view returns (uint256) { return _dividendsSnapshot[staker]; } function dividendsPerRug() public view returns (uint256) { return _dividendsPerRug; } function userDividends(address account) public view returns (uint256) { // Returns the amount of dividends that has been synced by _updateDividends() return _userDividends[account]; } function dividendsOf(address staker) public view returns (uint256) { require(_dividendsPerRug >= _dividendsSnapshot[staker], "dividend calc overflow"); uint256 sum = balanceOf(staker).mul((_dividendsPerRug.sub(_dividendsSnapshot[staker]))).div(1e18); return sum; } // adds dividends to staked balance function _updateDividends() internal returns(uint256) { uint256 _dividends = dividendsOf(msg.sender); require(_dividends >= 0); _userDividends[msg.sender] = _userDividends[msg.sender].add(_dividends); _dividendsSnapshot[msg.sender] = _dividendsPerRug; return _dividends; // amount of dividends added to _userDividends[] } function displayDividends(address staker) public view returns(uint256) { //created solely to display total amount of dividends on rug.money return (dividendsOf(staker) + userDividends(staker)); } // withdraw only dividends function withdrawDividends() public { _updateDividends(); uint256 amount = _userDividends[msg.sender]; _userDividends[msg.sender] = 0; _totalDividends = _totalDividends.sub(amount); rugStake.safeTransfer(msg.sender, amount); } // 10% fee: 7% redistribution, 3% burn function stake(uint256 amount) public { rugStake.safeTransferFrom(msg.sender, address(this), amount); bool firstTime = false; if (_stakeAmount[msg.sender] == 0) firstTime = true; uint256 amountToStake = (amount.mul(uint256(100).sub((redistributeRate.add(burnRate)))).div(100)); uint256 operateAmount = amount.sub(amountToStake); uint256 burnAmount = operateAmount.mul(burnRate).div(10); rugStake.burn(burnAmount, 100); // burns 100% of burnAmount uint256 dividendAmount = operateAmount.sub(burnAmount); _totalDividends = _totalDividends.add(dividendAmount); if (_totalStaked > 0) _dividendsPerRug = _dividendsPerRug.add(dividendAmount.mul(1e18).div(_totalStaked)); // prevents division by 0 if (firstTime) _dividendsSnapshot[msg.sender] = _dividendsPerRug; // For first time stakers _updateDividends(); // If you're restaking, reset snapshot back to _dividendsPerRug, reward previous staking. _totalStaked = _totalStaked.add(amountToStake); _stakeAmount[msg.sender] = _stakeAmount[msg.sender].add(amountToStake); emit Stake(msg.sender, amountToStake, operateAmount); } function withdraw(uint256 amount) public { _totalStaked = _totalStaked.sub(amount); _stakeAmount[msg.sender] = _stakeAmount[msg.sender].sub(amount); rugStake.safeTransfer(msg.sender, amount); } } contract PyramidPool is LPTokenWrapper, IRewardDistributionRecipient, TokenRecover { constructor() public { rewardDistribution = msg.sender; } IERC20 public rugReward; uint256 public DURATION = 1641600; // 19 days uint256 public starttime = 0; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event SetRewardToken(address rewardAddress); event SetStakeToken(address stakeAddress); event SetStartTime(uint256 unixtime); event SetDuration(uint256 duration); modifier checkStart() { require(block.timestamp >= starttime,"Rewards haven't started yet!"); _; } modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalStaked() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalStaked()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public updateReward(msg.sender) checkStart { require(amount > 0, "Cannot stake 0"); super.stake(amount); } function withdraw(uint256 amount) public updateReward(msg.sender) checkStart { require(amount > 0, "Cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdrawDividends(); getReward(); withdraw(balanceOf(msg.sender)); } function collectRewardsOnly() public { withdrawDividends(); getReward(); } function getReward() public updateReward(msg.sender) checkStart { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rugReward.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function notifyRewardAmount(uint256 reward) external onlyRewardDistribution updateReward(address(0)) { if (block.timestamp > starttime) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } else { rewardRate = reward.div(DURATION); lastUpdateTime = starttime; periodFinish = starttime.add(DURATION); emit RewardAdded(reward); } } function setRewardAddress(address rewardAddress) public onlyOwner { rugReward = IERC20(rewardAddress); emit SetRewardToken(rewardAddress); } function setStakeAddress(address stakeAddress) public onlyOwner { rugStake = IERC20(stakeAddress); emit SetStakeToken(stakeAddress); } function setStartTime(uint256 unixtime) public onlyOwner { starttime = unixtime; emit SetStartTime(unixtime); } function setDuration(uint256 duration) public onlyOwner { DURATION = duration; emit SetDuration(duration); } }
withdraw only dividends
function withdrawDividends() public { _updateDividends(); uint256 amount = _userDividends[msg.sender]; _userDividends[msg.sender] = 0; _totalDividends = _totalDividends.sub(amount); rugStake.safeTransfer(msg.sender, amount); }
7,620,905
./full_match/137/0xF404Fd23147B354f8504930D136050e6943d773B/sources/contracts/HemetaBondDepository.sol
determine maximum bond size return uint/
function maxPayout() public view returns ( uint ) { return IERC20( HETA ).totalSupply().mul( terms.maxPayout ).div( 100000 ); }
4,722,973
./full_match/80001/0xB4cb47bc9C7c7E49d742EB032D8BafD377Be1f31/sources/contracts/Vault.sol
Deposit amount to underlying protocol Deposits VaultCurrency in Protocol e.g USDC _protocolNum Protocol number linked to an underlying protocol e.g compound_usdc_01 _amount in VaultCurrency to deposit
function depositInProtocol(uint256 _protocolNum, uint256 _amount) internal { IController.ProtocolInfoS memory protocol = controller.getProtocolInfo( vaultNumber, _protocolNum ); if (getVaultBalance() < _amount) _amount = getVaultBalance(); if (protocol.underlying != address(vaultCurrency)) { _amount = Swap.swapStableCoins( Swap.SwapInOut(_amount, address(vaultCurrency), protocol.underlying), uScale, controller.underlyingUScale(protocol.underlying), controller.getCurveParams(address(vaultCurrency), protocol.underlying) ); } IERC20(protocol.underlying).safeIncreaseAllowance(protocol.provider, _amount); IProvider(protocol.provider).deposit(_amount, protocol.LPToken, protocol.underlying); }
5,563,964
./partial_match/42/0xb0D299d01bBD2fb20A52E315c768C88C44256d92/sources/ProofOfHumanity.sol
Make a request to refresh a submissionDuration. Paying the full deposit right away is not required as it can be crowdfunded later. Note that the user can reapply even when current submissionDuration has not expired, but only after the start of renewal period. _evidence A link to evidence using its URI./
function reapplySubmission(string calldata _evidence, string calldata _name, string calldata _bio) external payable { Submission storage submission = submissions[msg.sender]; require(submission.registered && submission.status == Status.None, "Wrong status"); uint renewalAvailableAt = submission.submissionTime.addCap64(submissionDuration.subCap64(renewalPeriodDuration)); require(now >= renewalAvailableAt, "Can't reapply yet"); submission.status = Status.Vouching; emit ReapplySubmission(msg.sender, submission.requests.length); requestRegistration(msg.sender, _evidence); }
3,440,453
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./OpenBooks.sol"; import "./EnumerablePrices.sol"; //Pausable Contract /** * @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 WithdrawPaused(address account); event BuyPaused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event WithdrawUnpaused(address account); event BuyUnpaused(address account); bool private _buyPaused; bool private _withdrawPaused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _buyPaused = false; _withdrawPaused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function withdrawPaused() public view returns (bool) { return _withdrawPaused; } function buyPaused() public view returns (bool) { return _buyPaused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenBuyNotPaused() { require(!_buyPaused, "Pausable: Buy paused"); _; } modifier whenWithdrawNotPaused() { require(!_withdrawPaused, "Pausable: Withdraw paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenBuyPaused() { require(_buyPaused, "Pausable: Buy not paused"); _; } modifier whenWithdrawPaused() { require(_withdrawPaused, "Pausable: Withdraw not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pauseBuy() internal virtual whenBuyNotPaused { _buyPaused = true; emit BuyPaused(_msgSender()); } function _pauseWithdraw() internal virtual whenWithdrawNotPaused { _withdrawPaused = true; emit WithdrawPaused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unPauseWithdraw() internal virtual whenWithdrawPaused { _withdrawPaused = false; emit WithdrawUnpaused(_msgSender()); } function _unPauseBuy() internal virtual whenBuyPaused { _buyPaused = false; emit BuyUnpaused(_msgSender()); } } //BookShop Contract /// @title A BookShop /// @author Ifebhor Odion Nonse /// A marketplace for selling books on the OpenBooks contract /// @dev communicates with the OpenBook contract for ownership proof, /// keeps a record of books for sale and does not transfer books, buyers download contract BookShop is Ownable, Pausable{ /// activate Libraties using SafeMath for uint256; using EnumerablePrices for EnumerablePrices.UintToUintMap; /// state variables OpenBooks private openBooks; /// An enumarable list of book ids mapped to their prices EnumerablePrices.UintToUintMap prices; /// @return the number of books owned by an address mapping(address => uint) public balances; /// modifiers modifier isOwner(uint _bookId){ require(openBooks.ownerOf(_bookId) == _msgSender(), "BookShop: Not owner of book"); _; } modifier onSale(uint _bookId){ require(prices.contains(_bookId), "BookShop: Not Listed"); _; } /// events event List(address indexed owner, uint indexed bookId, uint price); event DeList(address indexed owner, uint indexed bookId); event Buy(address indexed owner, address indexed buyer, uint indexed bookId, uint price); event Withdraw(address indexed sender, uint indexed amount); /// Initializes the contract /// @dev stores the address of the contract holding the books /// @param _openBooks the address of the contract holding the books, /// it cannot be zero constructor(OpenBooks _openBooks) public{ require(address(_openBooks) != address(0)); openBooks = _openBooks; } /// Used to get the address of the contract holding the books function getOpenBooks() external view onlyOwner returns(address){ return address(openBooks); } /// Used to put a book up for sale /// @dev the book's id and its price are added to the enumerable prices /// @param _bookId the id of the book to be listed /// @param _price the price to be sold for, it cannot be zero function list(uint _bookId, uint _price) external isOwner(_bookId){ _list(_bookId, _price); } function _list(uint _bookId, uint _price) private { require(_price != 0, "BookShop: Price cannot be zero"); prices.set(_bookId, _price); emit List(_msgSender(), _bookId, _price); } /// Used to remove a book from sale /// @dev removes a book's id from the enumerable prices list /// @param _bookId the id of the book to be removed from sale, it must be on sale function deList(uint _bookId)external isOwner(_bookId) onSale(_bookId){ prices.remove(_bookId); emit DeList(_msgSender(), _bookId); } /// Lets a buyer pay for the book with at least the specified price /// @dev lets a buyer download the book after successful payment /// the transaction's value must not be less than the books price /// @param _bookId the bookId to be bought function buy(uint _bookId) external payable onSale(_bookId) whenBuyNotPaused{ uint price = prices.get(_bookId); require( msg.value >= price, "BookShop: Price is higher"); address owner = openBooks.ownerOf(_bookId); balances[owner] += price; emit Buy(owner, _msgSender(), _bookId, price); } /// Allows anyone withthdraw their proceeds from book sales /// @dev can be called by anyone and they are given all of their /// balance in balances withdrawals must not be paused function withdraw() external whenWithdrawNotPaused{ address sender = _msgSender(); uint balance = balances[sender]; balances[sender] = 0; (bool success, ) = payable(address(sender)).call.value(balance)(""); require(success); emit Withdraw(sender, balance); } /// Used to get the price of a book on sale /// @param _bookId the book's price needed /// @return price the price of the book on sale, it's zero if the book is not on sale function getPrice(uint _bookId) public view returns(uint price){ price = prices.contains(_bookId) ? prices.get(_bookId) : 0; } /// Gets the price of a list of book ids /// @param _bookIds an array of bookids /// @return bookPrices an array of the price of each book in its corresponding index in _bookIds function getPrices(uint[] memory _bookIds) public view returns(uint[] memory bookPrices){ bookPrices = new uint[](_bookIds.length); for(uint i=0; i < _bookIds.length; i++){ uint bookId = _bookIds[i]; (openBooks.exists(bookId) && prices.contains(bookId)) ? bookPrices[i] = prices.get(bookId) : bookPrices[i] = 0; } } /// Gets the URIs of a list of books /// @param _bookIds an array of bookids /// @return URIs a string of URIs with each URI separated by a " " function getBookURIs(uint[] memory _bookIds) public view returns(string memory URIs){ for(uint i; i < _bookIds.length; i++){ URIs = string(abi.encodePacked(URIs, " ", openBooks.tokenURI(_bookIds[i]))); } } /// Gets the URI and price of a book /// @param _bookId the id of the book whose information is needed /// @return URI the URI of _bookId /// @return price the price of _bookId function getBookInfo(uint _bookId) public view returns(string memory URI, uint price){ price = getPrice(_bookId); URI = openBooks.tokenURI(_bookId); } /// Gets the URI and the price of a list of books /// @dev calls getPrices and getBookURIs /// @param _bookIds the ids of the books which their information is needed /// @return bookPrices an array of the price of each book in it's corresponding index in _bookIds /// @return URIs a string of URIs with each URI separated by a " " function getBooksInfo(uint[] memory _bookIds) public view returns(uint[] memory bookPrices, string memory URIs){ bookPrices = getPrices(_bookIds); URIs = getBookURIs(_bookIds); } /// Gets all the bookIds, bookPrices, and URIs of books owned by an address /// Each index in the return values except URIs contain the information of a single book function getBooks(address _address) public view returns( uint[] memory bookIds, uint[] memory bookPrices, string memory URIs ) { uint length = openBooks.balanceOf(_address); bookIds = new uint[](length); bookPrices = new uint[](length); for(uint i; i < length; i++){ bookIds[i] = openBooks.tokenOfOwnerByIndex(_address, i); bookPrices[i] = getPrice(bookIds[i]); URIs = string(abi.encodePacked(URIs, " ", openBooks.tokenURI(bookIds[i]))); } } /// Gets all the books on sale /// @dev iterates through prices to get all the books /// @return bookIds the ids of all books on sale /// @return bookPrices the prices of all books on sale /// @return URIs the URIs of all the books on sale function getAllBooksOnSale() public view returns( uint[] memory bookIds, uint[] memory bookPrices, string memory URIs ){ uint booksNo = prices.length(); bookIds = new uint[](booksNo); bookPrices = new uint[](booksNo); for(uint i = 0; i < booksNo; i++){ (uint bookId, uint price) = prices.at(i); (openBooks.exists(bookId)) ? (bookIds[i], bookPrices[i], URIs) = (bookId, price, string(abi.encodePacked(URIs, " ", openBooks.tokenURI(bookId))) ) : (bookIds[i], bookPrices[i], URIs) = (0, 0, string(abi.encodePacked(URIs, " ", "0" ))) ; } } /// Pauses the buy function and is only callable by the contract owner function pauseBuy() onlyOwner external{ _pauseBuy(); } /// Pauses the withdraw function and is only callable by the contract owner function pauseWithdraw() onlyOwner external{ _pauseWithdraw(); } /// Unpauses the buy function and is only callable by the contract owner function unPauseBuy() onlyOwner external{ _unPauseBuy(); } /// Unpauses the withdraw function and is only callable by the contract owner function unPauseWithdraw() onlyOwner external{ _unPauseWithdraw(); } }
Unpauses the buy function and is only callable by the contract owner
function unPauseBuy() onlyOwner external{ _unPauseBuy(); }
5,345,998
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.4; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import '@passive-income/psi-contracts/contracts/interfaces/IIncome.sol'; import '@passive-income/psi-contracts/contracts/abstracts/Governable.sol'; import './interfaces/IMigratorChef.sol'; // MasterChef is the master of Income. He can make Income and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once INC is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Initializable, OwnableUpgradeable, Governable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of INCs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accIncomePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accIncomePerShare` (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 PoolInfo { address lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. INCs to distribute per block. uint256 lastRewardBlock; // Last block number that INCs distribution occurs. uint256 accIncomePerShare; // Accumulated INCs per share, times 1e12. See below. } // Income token address public income; // INC tokens created per block. uint256 public incomePerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // mapping with pool indexes. mapping (address => uint256) public poolIds; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; // The block number when INC mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); /** * @dev Initializes the contract setting the deployer as the initial Governor. */ function initialize(address _gov_contract, address _income, uint256 _startBlock) public initializer { __Ownable_init(); super.initialize(_gov_contract); // Based on 9.000.000 tokens a year with a block speed of 3 secs, can be update later on by an owner incomePerBlock = 8561643835616438; income = _income; startBlock = _startBlock; } function totalPools() external view returns (uint256) { return poolInfo.length; } function totalActivePools() external view returns (uint256) { uint256 length; for (uint256 pid = 0; pid < poolInfo.length; ++pid) { if (poolInfo[pid].allocPoint > 0) { length++; } } return length; } function poolId(address lpToken) external view returns (uint256) { return poolIds[lpToken] - 1; } function poolActiveByAddress(address lpToken) external view returns (bool) { return poolInfo[poolIds[lpToken] - 1].allocPoint > 0; } function poolActive(uint256 pid) external view returns (bool) { return poolInfo[pid].allocPoint > 0; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Update income per block. Can only be called by the owner. function setIncomePerBlock(uint256 _incomePerBlock) public onlyOwner { incomePerBlock = _incomePerBlock; } // Update startblock, can only be called by the owner function setStartBlock(uint256 _startBlock) public onlyOwner { startBlock = _startBlock; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, address _lpToken, bool _withUpdate) public onlyOwner { require(_lpToken != address(0), "LP token cannot be a zero address"); require(poolIds[_lpToken] == 0, "Pool for `_lpToken` already exists"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accIncomePerShare: 0 })); poolIds[_lpToken] = poolInfo.length; } // Update the given pool's INC allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, address _lpToken, bool _withUpdate) public onlyOwner { require(_pid >= 0 && _pid < poolInfo.length, "Pool for `_pid` does not exist"); if (_withUpdate) { massUpdatePools(); } if (_lpToken != address(0)) { if (poolIds[poolInfo[_pid].lpToken] > 0) poolIds[poolInfo[_pid].lpToken] = 0; poolInfo[_pid].lpToken = _lpToken; poolIds[_lpToken] = _pid + 1; } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); } } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); require(_pid >= 0 && _pid < poolInfo.length, "Pool for `_pid` does not exist"); PoolInfo storage pool = poolInfo[_pid]; uint256 bal = IERC20(pool.lpToken).balanceOf(address(this)); IERC20(pool.lpToken).safeApprove(address(migrator), bal); address newLpToken = migrator.migrate(pool.lpToken); require(bal == IERC20(newLpToken).balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // View function to see pending INCs on frontend. function pendingIncome(uint256 _pid, address _user) external view returns (uint256) { require(_pid >= 0 && _pid < poolInfo.length, "Pool for `_pid` does not exist"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accIncomePerShare = pool.accIncomePerShare; uint256 lpSupply = IERC20(pool.lpToken).balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 incomeReward = block.number.sub(pool.lastRewardBlock).mul(incomePerBlock) .mul(pool.allocPoint).div(totalAllocPoint); accIncomePerShare = accIncomePerShare.add(incomeReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accIncomePerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { require(_pid >= 0 && _pid < poolInfo.length, "Pool for `_pid` does not exist"); PoolInfo storage pool = poolInfo[_pid]; if (pool.lastRewardBlock < startBlock) { pool.lastRewardBlock = startBlock; } if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = IERC20(pool.lpToken).balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 incomeReward = block.number.sub(pool.lastRewardBlock).mul(incomePerBlock) .mul(pool.allocPoint).div(totalAllocPoint); IIncome(income).mint(incomeReward); pool.accIncomePerShare = pool.accIncomePerShare.add(incomeReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for INC allocation. function deposit(uint256 _pid, uint256 _amount) public { require(_pid >= 0 && _pid < poolInfo.length, "Pool for `_pid` does not exist"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_msgSender()]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accIncomePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeIncomeTransfer(_msgSender(), pending); } } if (_amount > 0) { IERC20(pool.lpToken).safeTransferFrom(_msgSender(), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accIncomePerShare).div(1e12); emit Deposit(_msgSender(), _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { require(_pid >= 0 && _pid < poolInfo.length, "Pool for `_pid` does not exist"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_msgSender()]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accIncomePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeIncomeTransfer(_msgSender(), pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); IERC20(pool.lpToken).safeTransfer(_msgSender(), _amount); } user.rewardDebt = user.amount.mul(pool.accIncomePerShare).div(1e12); emit Withdraw(_msgSender(), _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { require(_pid >= 0 && _pid < poolInfo.length, "Pool for `_pid` does not exist"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_msgSender()]; IERC20(pool.lpToken).safeTransfer(_msgSender(), user.amount); emit EmergencyWithdraw(_msgSender(), _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe income transfer function, just in case if rounding error causes pool to not have enough INCs. function safeIncomeTransfer(address _to, uint256 _amount) internal { uint256 incomeBalance = IIncome(income).balanceOf(address(this)); _amount = _amount > incomeBalance ? incomeBalance : _amount; IIncome(income).transfer(_to, _amount); } }
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, address _lpToken, bool _withUpdate) public onlyOwner { require(_lpToken != address(0), "LP token cannot be a zero address"); require(poolIds[_lpToken] == 0, "Pool for `_lpToken` already exists"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accIncomePerShare: 0 })); poolIds[_lpToken] = poolInfo.length; }
12,727,991
./partial_match/42/0xf672dc33e253e55c18e9869600bB1063af840e25/sources/assignmentToken.sol
TODO: transfer mintership to newminter NOTE: only incumbent minter can transfer mintership NOTE: should emit `MintershipTransfer` event
function transferMintership(address newMinter) public returns (bool) { require(newMinter != minter, "new minter is the zero address"); require(msg.sender==minter); emit MintershipTransfer(minter, newMinter); minter = newMinter; return true; }
3,320,635
./partial_match/1/0xd0aaaC09E7f9b794FAfA9020a34aD5B906566A5C/sources/WeAbove.sol
no need to check upper bound because _canPremint() already does it
function premint( address to, uint256 amount, PremintType premintType, bytes32[] calldata proof ) payable external { if (!_canPremint()) revert NotPremintPeriod(); bytes32 rootToUse; uint256 maxQuantity; if (premintType == PremintType.WHITELIST) { rootToUse = root; maxQuantity = maxMintPerWhitelistAddress; } else if (premintType == PremintType.RAFFLE) { if (block.timestamp < startTimestamp + raffleStart) revert NotRafflePremintPeriod(); rootToUse = raffleRoot; maxQuantity = maxMintPerAddress; } else revert InvalidPremintType(); bytes32 leaf = keccak256(abi.encodePacked(to)); if (!MerkleProof.verifyCalldata(proof, rootToUse, leaf)) revert InvalidMerkleProof(); _tryMint(to, amount, maxQuantity); }
15,774,648
./full_match/5/0x85547c4D24a27DD20A7BafD673203aA441e0670c/sources/contracts/messagePassingBridge/MessagePassingBridge.sol
Function for approving requests above limits id The bridgerequest id/
function approveRequest(uint256 id) external { _onlyOwnerOrGuardian(); approvedRequests[id] = true; }
1,853,405
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../Contracts/Approve.sol"; import "../Contracts/Context.sol"; import "../Interfaces/IBEP20.sol"; import "../Libraries/SafeMath.sol"; import "../Contracts/Address.sol"; import "../Interfaces/IMoonity.sol"; /** * @dev Read Docs/CrowdSale.md */ contract CrowdSale is Context, IBEP20, Approve { using SafeMath for uint256; using Address for address; // Phases enum Phases{ CREATED, VIPSALE, VIPSALE_ENDED, SEEDSALE, SEEDSALE_ENDED, PRIVATESALE, PRIVATESALE_ENDED } // Token name and symbol string private constant TOKEN_NAME = "LM*VIP*"; string private constant TOKEN_SYMBOL = "LM*VIP*"; Phases private _salePhase; uint256 private T_TOTAL = 10000 * 10**6 * 10**9; // The maximum amount of tokens an investor can buy during a sale phase uint256 public constant TOKENBUYLIMIT = 2000000 * 10**9; // 9 decimals uint256 public TokenPriceInBNB = 2393146029771; // 18 decimals bool private ContractsLinked; // Whitelists mapping (address => bool) private _isWhitelistedVIPSale; mapping (address => bool) private _isWhitelistedSeedSale; mapping (address => bool) private _isWhitelistedPrivateSale; // Balances mapping (address => uint256) private _tOwnedVIPSale; mapping (address => uint256) private _tOwnedSeedSale; mapping (address => uint256) private _tOwnedPrivateSale; mapping (address => uint256) private _tOwnedVIPTokens; // Total amount of sold tokens uint256 public tokensSoldVIP; uint256 public tokensSoldSeed; uint256 public tokensSoldPrivate; // Timelock uint256 public timeLock; address[] private _VIPTokenTransfer; address[] private _admin; Moonity public MoonityToken; // Modifiers /** * @dev Throws if called by any account other than an admin */ modifier onlyAdmin() { require(isAdmin(_msgSender()), "Caller is not admin."); _; } // Events /** * @dev Emitted when the CrowdSale phase has changed */ event CrowdSalePhaseChanged(Phases); /** * @dev Emitted when an address has been whitelisted */ event AddressWhitelisted(address, Phases); /** * @dev Emitted when an address has been removed from whitelist */ event AddressRemovedFromWhitelist(address, Phases); /** * @dev Emitted when the price of the token has been updated (daily actual BNB price) */ event TokenPriceUpdated(uint256 price); /** * @dev Initializes the contract */ constructor() { _salePhase = Phases.CREATED; _tOwnedVIPSale[msg.sender] = 0; _admin.push(_msgSender()); emit Transfer(address(0), _msgSender(), 0); } /** * @dev IBEP20 interface: Returns the token name */ function name() public pure override returns (string memory) { return TOKEN_NAME; } /** * @dev IBEP20 interface: Returns the smart-contract owner */ function getOwner() external override view returns (address) { return owner(); } /** * @dev IBEP20 interface: Returns the token symbol */ function symbol() public pure override returns (string memory) { return TOKEN_SYMBOL; } /** * @dev IBEP20 interface: Returns the token decimals */ function decimals() public pure override returns (uint8) { return 9; } /** * @dev IBEP20 interface: Returns the amount of tokens in existence */ function totalSupply() public view override returns (uint256) { return T_TOTAL; } /** * @dev IBEP20 interface: Returns the amount of *VIP* tokens owned by `account`. */ function balanceOf(address account) public view override returns (uint256) { return _tOwnedVIPTokens[account]; } function transfer(address /*receiver*/, uint256 /*numTokens*/) public override pure returns (bool) { return false; } function approve(address /*delegate*/, uint256 /*numTokens*/) public override pure returns (bool) { return false; } function allowance(address /*owner*/, address /*delegate*/) public override pure returns (uint) { return 0; } function transferFrom(address /*owner*/, address /*buyer*/, uint256 /*numTokens*/) public override pure returns (bool) { return false; } /** * @dev receive BNB */ /* UNTRUSTED FUNCTION */ /* Re-entrancy protection: Transfer tokens after refunding */ receive() external payable { require(currentPhase() == Phases.VIPSALE || currentPhase() == Phases.SEEDSALE || currentPhase() == Phases.PRIVATESALE, "CrowdSale not active"); uint256 SenderBalance = _getSenderBalance(); require(SenderBalance < TOKENBUYLIMIT, "Max buy limit reached"); (uint256 TransferTokens, uint256 RefundAmount) = _calculateTransferTokens(SenderBalance); _increaseSenderBalance(TransferTokens); // Only transfer during seedsale and privatesale. NOT VIPsale // VIPs get VIP tokens // VIPs will get their final tokens when the VIP sale has ended if(currentPhase() == Phases.SEEDSALE || currentPhase() == Phases.PRIVATESALE) { bool transferred = MoonityToken.TransferCrowdSaleTokens(_msgSender(), TransferTokens); // TRUSTED EXTERNAL CALL require(transferred, "Token transfer failed"); } if(RefundAmount > 0) { // Refund overpaid BNB (bool sent, ) = _msgSender().call{value: RefundAmount}(""); require(sent, "Refunding failed"); } } /** * @dev Get the token balance of an address from VIPSale */ function balanceOfVIPSale(address account) public view returns(uint256) { return _tOwnedVIPSale[account]; } /** * @dev Get the token balance of an address from SeedSale */ function balanceOfSeedSale(address account) public view returns(uint256) { return _tOwnedSeedSale[account]; } /** * @dev Get the token balance of an address from PrivateSale */ function balanceOfPrivateSale(address account) public view returns(uint256) { return _tOwnedPrivateSale[account]; } /** * @dev Set the timelock */ function setTimeLock() public { require(ContractsLinked, "Contracts not linked"); require(_msgSender() == address(MoonityToken), "Access denied"); require(_salePhase == Phases.PRIVATESALE_ENDED, "Wrong order"); require(timeLock == 0, "Already timelocked"); timeLock = block.timestamp; } /** * @dev Get the locked token balance of an address * Up to 45 days after launch: Entire CrowdSale balance is locked * After 45 days: Unlock 2% every day. * After 95 days: Everything is unlocked */ function lockedBalance(address account) public view returns(uint256) { uint256 Balance = 0; if(_isWhitelistedVIPSale[account]) { Balance = _tOwnedVIPSale[account]; } else if(_isWhitelistedSeedSale[account]) { Balance = _tOwnedSeedSale[account]; } else if(_isWhitelistedPrivateSale[account]) { Balance = _tOwnedPrivateSale[account]; } if(timeLock == 0 || block.timestamp < timeLock.add(45 days)) { // Timer not started or not 45 days over return Balance; // Entire balance is timelocked } else if(block.timestamp <= timeLock.add(95 days)) { // More than 45 days but less than 95 days uint256 DaysOver45 = block.timestamp.sub(timeLock.add(45 days)); // How many days are over 45 days after launch (in seconds) uint256 PercentSeconds = 0; if(DaysOver45 <= 50 days) { // check underflow case PercentSeconds = uint256(100 days).sub(DaysOver45.mul(2)); } return Balance.mul(PercentSeconds).div(100 days); } // Nothing is locked anymore return 0; } /** * @dev withdraw BNB from contract * Can only be used by the owner of this contract */ function withdraw (uint256 amount) public onlyOwnerWithApproval returns(bool res) { require(amount <= address(this).balance, "Balance not sufficient"); payable(owner()).transfer(amount); return true; } /** * @dev withdraw all BNB from contract * Can only be used by the owner of this contract */ function withdrawAll () public onlyOwnerWithApproval returns(bool res) { payable(owner()).transfer(address(this).balance); return true; } /** * @dev Update the token price manually * Due to daily fluctuation in BNB prices, the token price in BNB needs to be updated * Can only be used by the owner of this contract */ function setTokenPriceInBNB (uint256 price) public onlyOwnerWithApproval { TokenPriceInBNB = price; emit TokenPriceUpdated(price); } /** * @dev Change phase of this token * Can only be used by the owner of this contract * Emits an CrowdSalePhaseChanged event */ function changeCrowdSalePhase(Phases phase) public onlyOwnerWithApproval { if(phase == Phases.VIPSALE) { require(_salePhase == Phases.CREATED, "Wrong order"); _salePhase = Phases.VIPSALE; emit CrowdSalePhaseChanged(phase); } else { require(ContractsLinked,"Contracts not linked"); if(phase == Phases.SEEDSALE) { require(_VIPTokenTransfer.length == 0, "Not all VIP tokens transferred"); } // Check if the correct previous phase is enabled require(uint(_salePhase) == uint(phase).sub(1), "Wrong order"); _salePhase = phase; emit CrowdSalePhaseChanged(phase); } } /** * @dev Returns the current CrowdSale phase */ function currentPhase() public view returns (Phases) { return _salePhase; } /** * @dev Adds a list of addresses to the whitelist. Only whitelisted addresses can buy tokens. * An account can only be whitelisted in one sale pahse * Can only be used by the owner of this contract */ function AddToWhitelist(address[] memory Addresses, Phases ToWhitelist) public onlyAdmin() { require(ToWhitelist == Phases.VIPSALE || ToWhitelist == Phases.SEEDSALE || ToWhitelist == Phases.PRIVATESALE, "Wrong phase"); for (uint i = 0; i < Addresses.length; i++) { if(Addresses[i] != owner()) { if(!_isWhitelistedVIPSale[Addresses[i]] && !_isWhitelistedSeedSale[Addresses[i]] && !_isWhitelistedPrivateSale[Addresses[i]]) { if(ToWhitelist == Phases.VIPSALE) { _isWhitelistedVIPSale[Addresses[i]] = true; _VIPTokenTransfer.push(Addresses[i]); } else if(ToWhitelist == Phases.SEEDSALE) { _isWhitelistedSeedSale[Addresses[i]] = true; } else { _isWhitelistedPrivateSale[Addresses[i]] = true; } emit AddressWhitelisted(Addresses[i], ToWhitelist); } } } } /** * @dev Removes a list of addresses from whitelist * Can only be used by the owner of this contract */ function RemoveFromWhitelist(address[] memory Addresses , Phases FromWhitelist) public onlyAdmin() { require(FromWhitelist == Phases.VIPSALE || FromWhitelist == Phases.SEEDSALE || FromWhitelist == Phases.PRIVATESALE, "Wrong phase"); for (uint i = 0; i < Addresses.length; i++) { if(FromWhitelist == Phases.VIPSALE){ if(_tOwnedVIPSale[Addresses[i]] == 0){ _isWhitelistedVIPSale[Addresses[i]] = false; _removeFrom_VIPs(Addresses[i]); } } else if(FromWhitelist == Phases.SEEDSALE){ if(_tOwnedSeedSale[Addresses[i]] == 0) { _isWhitelistedSeedSale[Addresses[i]] = false; } } else { if(_tOwnedPrivateSale[Addresses[i]] == 0) { _isWhitelistedPrivateSale[Addresses[i]] = false; } } emit AddressRemovedFromWhitelist(Addresses[i], FromWhitelist); } } /** * @dev Returns true, if the address is whitelisted for the VIP sale */ function isWhitelistedForVIPSale (address account) public view returns(bool) { return _isWhitelistedVIPSale[account]; } /** * @dev Returns true, if the address is whitelisted for the seed sale */ function isWhitelistedForSeedSale (address account) public view returns(bool) { return _isWhitelistedSeedSale[account]; } /** * @dev Returns true, if the address is whitelisted for the private sale */ function isWhitelistedForPrivateSale (address account) public view returns(bool) { return _isWhitelistedPrivateSale[account]; } /** * @dev Return the amount of VIPs */ function VIPCount () public view returns(uint256) { return _VIPTokenTransfer.length; } /** * @dev Links this contract with the token contract * Can only be used by the owner of this contract * TRUSTED */ function linkMoonityContract(address ContractAddress) public onlyOwnerWithApproval { require(!ContractsLinked, "Already linked"); MoonityToken = Moonity(ContractAddress); // TRUSTED EXTERNAL CALL ContractsLinked = true; } /** * @dev Sends the final tradeable tokens to VIPs * To save gas charges, the number of accounts can be passed as a parameter. * The function must be called repeatedly until all VIP tokens have been transferred. * Can only be used by the owner of this contract * TRUSTED */ function distributeVIPTokens(uint256 count) public onlyOwnerWithApproval { require(ContractsLinked, "Contracts not linked"); require(_salePhase == Phases.VIPSALE_ENDED, "Wrong order"); uint256 counter = count; if(_VIPTokenTransfer.length < count) { counter = _VIPTokenTransfer.length; } for (uint i = 0; i < counter; i++) { uint256 VIPBalance = _tOwnedVIPSale[_VIPTokenTransfer[0]]; if(VIPBalance > 0){ _tOwnedVIPTokens[_VIPTokenTransfer[0]] = 0; bool transferred = MoonityToken.TransferCrowdSaleTokens(_VIPTokenTransfer[0], VIPBalance); // TRUSTED EXTERNAL CALL require(transferred, "Token transfer failed"); } _removeFrom_VIPs(_VIPTokenTransfer[0]); } } /** * @dev Unlinks this contract from the token contract * Can only be used by the owner of this contract */ function UnlinkContracts() public onlyOwnerWithApproval { require(ContractsLinked, "Already unlinked"); require(_salePhase == Phases.CREATED || _salePhase == Phases.VIPSALE, "Not possible anymore"); ContractsLinked = false; } /** * @dev Once the CrowdSale is finished, this contract may be destroyed * There is no further purpose for this contract * Can only be used by the owner * TRUSTED */ function DestroyContract() public onlyOwnerWithApproval() { require(_salePhase == Phases.PRIVATESALE_ENDED, "Wrong order"); // Token Contract require(MoonityToken.HasLaunched(), "Token not lauched, yet"); // TRUSTED EXTERNAL CALL // Send remaining BNB to owner's wallet and then selfdestruct selfdestruct(payable(owner())); } /** * @dev Get the token balance of an address from CrowdSale */ function _getSenderBalance() private view returns(uint256) { if(currentPhase() == Phases.VIPSALE) { require(_isWhitelistedVIPSale[_msgSender()], "Not whitelisted"); return _tOwnedVIPSale[_msgSender()]; } else if(currentPhase() == Phases.SEEDSALE) { require(_isWhitelistedSeedSale[_msgSender()], "Not whitelisted"); return _tOwnedSeedSale[_msgSender()]; } else if(currentPhase() == Phases.PRIVATESALE) { require(_isWhitelistedPrivateSale[_msgSender()], "Not whitelisted"); return _tOwnedPrivateSale[_msgSender()]; } else { return TOKENBUYLIMIT; } } /** * @dev Add bought tokens to sender's balance */ function _increaseSenderBalance(uint256 TransferTokens) private { if(currentPhase() == Phases.VIPSALE) { _tOwnedVIPSale[_msgSender()] = _tOwnedVIPSale[_msgSender()].add(TransferTokens); _tOwnedVIPTokens[_msgSender()] = _tOwnedVIPTokens[_msgSender()].add(TransferTokens); tokensSoldVIP = tokensSoldVIP.add(TransferTokens); emit Transfer(address(0), _msgSender(), TransferTokens); } else if(currentPhase() == Phases.SEEDSALE) { _tOwnedSeedSale[_msgSender()] = _tOwnedSeedSale[_msgSender()].add(TransferTokens); tokensSoldSeed = tokensSoldSeed.add(TransferTokens); } else if(currentPhase() == Phases.PRIVATESALE) { _tOwnedPrivateSale[_msgSender()] = _tOwnedPrivateSale[_msgSender()].add(TransferTokens); tokensSoldPrivate = tokensSoldPrivate.add(TransferTokens); } } /** * @dev Calculates how many tokens the address can get and how many BNB should be refunded */ function _calculateTransferTokens(uint256 SenderBalance) private returns(uint256, uint256) { uint256 TokensAvailable; if(SenderBalance >= TOKENBUYLIMIT) { TokensAvailable = 0; } else { TokensAvailable = TOKENBUYLIMIT.sub(SenderBalance); } uint256 BNBforAllTokens = TokensAvailable.mul(TokenPriceInBNB).div(10**9); // in wei uint256 BNBReceived = msg.value; // in wei uint256 TransferTokens; uint256 TransferTokensCeil; uint256 RefundAmount; // More BNB received than needed? if(BNBReceived > BNBforAllTokens) { RefundAmount = BNBReceived.sub(BNBforAllTokens); TransferTokens = TokensAvailable; } else { // calculate how many tokens we want to buy TransferTokens = BNBReceived.mul(10**9).div(TokenPriceInBNB); } // Round token count to the nearest whole number TransferTokensCeil = ((TransferTokens + 1000000000 - 1) / 1000000000) * 1000000000; return (TransferTokensCeil, RefundAmount); } /** * @dev Removes a VIP account */ function _removeFrom_VIPs(address account) private { for (uint256 i = 0; i < _VIPTokenTransfer.length; i++) { if (_VIPTokenTransfer[i] == account) { _VIPTokenTransfer[i] = _VIPTokenTransfer[_VIPTokenTransfer.length - 1]; // Copy last element and overwrite account's position _VIPTokenTransfer.pop(); // remove last element break; } } } /** * @dev Returns true if sender is an admin */ function isAdmin(address account) view public returns (bool){ for (uint i; i< _admin.length;i++){ if (_admin[i]==account) { return true; } } return false; } /** * @dev Promote accounts to admin */ function promoteAdmin(address account) public onlyOwnerWithApproval() { require(!isAdmin(account), "Already admin"); _admin.push(account); } /** * @dev Removes accounts from admin */ function removeAdmin(address account) public onlyOwnerWithApproval() { require(isAdmin(account), "Account is not an admin"); for (uint i; i< _admin.length;i++){ if (_admin[i]==account) { _admin[i] = _admin[_admin.length - 1]; // Copy last element and overwrite account's position _admin.pop(); // Remove last element break; } } } }
Returns true, if the address is whitelisted for the seed sale/
function isWhitelistedForSeedSale (address account) public view returns(bool) { return _isWhitelistedSeedSale[account]; }
1,794,000
./full_match/1/0x399619F1e9be0a991b399c002985de98b3B732C0/sources/contracts/timelocks/common/BaseTimelock.sol
calculate the month difference between two timestamps/
function _diffMonth(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 month) { require(fromTimestamp <= toTimestamp, "invalid usage"); month = fromTimestamp.diffMonths(toTimestamp); if (fromTimestamp.addMonths(month) > toTimestamp) { month -= 1; } }
8,320,385
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /** * @title Mintable ERC721 Extension * * @notice Defines mint capabilities for ERC721 tokens. * This interface should be treated as a definition of what mintable means for ERC721 * * @author Basil Gorin */ interface MintableERC721 { /** * @notice Checks if specified token exists * * @dev Returns whether the specified token ID has an ownership * information associated with it * * @param _tokenId ID of the token to query existence for * @return whether the token exists (true - exists, false - doesn't exist) */ function exists(uint256 _tokenId) external view returns(bool); /** * @dev Creates new token with token ID specified * and assigns an ownership `_to` for this token * * @dev Unsafe: doesn't execute `onERC721Received` on the receiver. * Prefer the use of `saveMint` instead of `mint`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint */ function mint(address _to, uint256 _tokenId) external; /** * @dev Creates new token with token ID specified * and assigns an ownership `_to` for this token * * @dev 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,address,uint256,bytes)"))`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint */ function safeMint(address _to, uint256 _tokenId) external; /** * @dev Creates new token with token ID specified * and assigns an ownership `_to` for this token * * @dev 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,address,uint256,bytes)"))`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint * @param _data additional data with no specified format, sent in call to `_to` */ function safeMint(address _to, uint256 _tokenId, bytes memory _data) external; } /** * @title Batch Mintable ERC721 Extension * * @notice Defines batch minting capabilities for ERC721 tokens. * This interface should be treated as a definition of what mintable means for ERC721 * * @author Basil Gorin */ interface BatchMintable { /** * @dev Creates new tokens starting with token ID specified * and assigns an ownership `_to` for these tokens * * @dev Token IDs to be minted: [_tokenId, _tokenId + n) * * @dev n must be greater or equal 2: `n > 1` * * @dev Unsafe: doesn't execute `onERC721Received` on the receiver. * Prefer the use of `saveMintBatch` instead of `mintBatch`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint tokens to * @param _tokenId ID of the first token to mint * @param n how many tokens to mint, sequentially increasing the _tokenId */ function mintBatch(address _to, uint256 _tokenId, uint256 n) external; /** * @dev Creates new tokens starting with token ID specified * and assigns an ownership `_to` for these tokens * * @dev Token IDs to be minted: [_tokenId, _tokenId + n) * * @dev n must be greater or equal 2: `n > 1` * * @dev 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,address,uint256,bytes)"))`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint * @param n how many tokens to mint, sequentially increasing the _tokenId */ function safeMintBatch(address _to, uint256 _tokenId, uint256 n) external; /** * @dev Creates new tokens starting with token ID specified * and assigns an ownership `_to` for these tokens * * @dev Token IDs to be minted: [_tokenId, _tokenId + n) * * @dev n must be greater or equal 2: `n > 1` * * @dev 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,address,uint256,bytes)"))`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint * @param n how many tokens to mint, sequentially increasing the _tokenId * @param _data additional data with no specified format, sent in call to `_to` */ function safeMintBatch(address _to, uint256 _tokenId, uint256 n, bytes memory _data) external; } /** * @title Burnable ERC721 Extension * * @notice Defines burn capabilities for ERC721 tokens. * This interface should be treated as a definition of what burnable means for ERC721 * * @author Basil Gorin */ interface BurnableERC721 { /** * @notice Destroys the token with token ID specified * * @dev Should be accessible publicly by token owners. * May have a restricted access handled by the implementation * * @param _tokenId ID of the token to burn */ function burn(uint256 _tokenId) external; }
Batch Mintable ERC721 Extension Defines batch minting capabilities for ERC721 tokens. This interface should be treated as a definition of what mintable means for ERC721 Basil Gorin/
interface BatchMintable { function mintBatch(address _to, uint256 _tokenId, uint256 n) external; function safeMintBatch(address _to, uint256 _tokenId, uint256 n) external; function safeMintBatch(address _to, uint256 _tokenId, uint256 n, bytes memory _data) external; } }
926,634
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../libraries/SortitionSumTreeFactory.sol"; import "../libraries/UniformRandomNumber.sol"; import "../interfaces/IRNGenerator.sol"; import "../interfaces/IPinataManager.sol"; import "../manager/PinataManageable.sol"; /** * @dev Implementation of a prize pool to holding funds that would be distributed as prize for lucky winners. * This is the contract that receives funds from strategy (when harvesting) and distribute it when drawing time come. */ contract PrizePool is PinataManageable { using SafeMath for uint256; using SafeERC20 for IERC20; using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; /* ========================== Variables ========================== */ // Structure struct Entry { address addr; uint256 chances; uint256 lastEnterId; uint256 lastDeposit; uint256 claimableReward; } struct History { uint256 roundId; uint256 rewardNumber; address[] winners; uint256 roundReward; } // Constant uint256 private constant MAX_TREE_LEAVES = 5; bytes32 public constant SUM_TREE_KEY = "PrizePool"; IERC20 public prizeToken; // RandomNumberGenerator bytes32 internal _requestId; uint256 internal _randomness; // State SortitionSumTreeFactory.SortitionSumTrees private sortitionSumTrees; mapping(address => Entry) private entries; uint256 public numOfParticipants; uint8 public numOfWinners; uint256 public _totalChances; uint256 public currentRound; mapping(uint256 => History) public histories; uint256 public allocatedRewards; uint256 public claimedRewards; /* ========================== Events ========================== */ /** * @dev Emitted when reward is claimed. */ event RewardClaimed(address claimer, uint256 amount); /** * @dev Emitted when drawing reward. */ event DrawReward(bytes32 requestId, uint256 round); /** * @dev Emitted when winners is selected. */ event WinnersDrawn(uint256 round); /** * @dev Emitted when reward successfully distributed. */ event RewardDistributed(uint256 round); /* ========================== Functions ========================== */ /** * @dev Setting up contract's state, Manager contract which will be use to observe state. * the prize token is token that would be distribute as prize, and number of winners in each round. * also creating a new tree which will need to use. * @param _manager address of PinataManager contract. * @param _prizeToken address of token will be distribute as reward. * @param _numOfWinners is number of lucky winner in each round. */ constructor( address _manager, address _prizeToken, uint8 _numOfWinners ) public PinataManageable(_manager) { prizeToken = IERC20(_prizeToken); numOfWinners = _numOfWinners; allocatedRewards = 0; claimedRewards = 0; _totalChances = 0; currentRound = 0; numOfParticipants = 0; sortitionSumTrees.createTree(SUM_TREE_KEY, MAX_TREE_LEAVES); } /** * @dev add chances to win for participant may only call by vault. * @param participant address participant. * @param _chances number of chances to win. */ function addChances(address participant, uint256 _chances) external onlyVault { require(_chances > 0, "PrizePool: Chances cannot be less than zero"); _totalChances = _totalChances.add(_chances); if (entries[participant].chances > 0) { entries[participant].lastEnterId = currentRound; entries[participant].lastDeposit = block.timestamp; entries[participant].chances = entries[participant].chances.add( _chances ); } else { entries[participant] = Entry( participant, _chances, currentRound, block.timestamp, 0 ); numOfParticipants = numOfParticipants.add(1); } sortitionSumTrees.set( SUM_TREE_KEY, entries[participant].chances, bytes32(uint256(participant)) ); } /** * @dev withdraw all of chances of participant. * @param participant address participant. */ function withdraw(address participant) external onlyVault { require( entries[participant].chances > 0, "PrizePool: Chances of participant already less than zero" ); _totalChances = _totalChances.sub(entries[participant].chances); numOfParticipants = numOfParticipants.sub(1); entries[participant].chances = 0; sortitionSumTrees.set(SUM_TREE_KEY, 0, bytes32(uint256(participant))); } /** * @dev get chances of participant. * @param participant address participant. */ function chancesOf(address participant) public view returns (uint256) { return entries[participant].chances; } /** * @dev return owner of ticket id. * @param ticketId is ticket id wish to know owner. */ function ownerOf(uint256 ticketId) public view returns (address) { if (ticketId >= _totalChances) { return address(0); } return address(uint256(sortitionSumTrees.draw(SUM_TREE_KEY, ticketId))); } /** * @dev draw number to be use in reward distribution process. * calling RandomNumberGenerator and keep requestId to check later when result comes. * only allow to be call by manager. */ function drawNumber() external onlyManager { (uint256 openTime, , uint256 drawTime) = getTimeline(); uint256 timeOfRound = drawTime.sub(openTime); require(timeOfRound > 0, "PrizePool: time of round is zeroes!"); _requestId = IRNGenerator(getRandomNumberGenerator()).getRandomNumber( currentRound, block.difficulty ); emit DrawReward(_requestId, currentRound); } /** * @dev callback function for RandomNumberGenerator to return randomness. * after randomness is recieve this contract would use it to distribute rewards. * from funds inside the contract. * this function is only allow to be call from random generator to ensure fairness. */ function numbersDrawn( bytes32 requestId, uint256 roundId, uint256 randomness ) external onlyRandomGenerator { require(requestId == _requestId, "PrizePool: requestId not match!"); require(roundId == currentRound, "PrizePool: roundId not match!"); _randomness = randomness; manager.winnersCalculated(); emit WinnersDrawn(currentRound); } /** * @dev internal function to calculate rewards with randomness got from RandomNumberGenerator. */ function distributeRewards() public onlyTimekeeper whenInState(IPinataManager.LOTTERY_STATE.WINNERS_PENDING) returns (address[] memory, uint256) { address[] memory _winners = new address[](numOfWinners); uint256 allocatablePrize = allocatePrize(); uint256 roundReward = 0; if (allocatablePrize > 0 && _totalChances > 0) { for (uint8 winner = 0; winner < numOfWinners; winner++) { // Picking ticket index that won the prize. uint256 winnerIdx = _selectRandom( uint256(keccak256(abi.encode(_randomness, winner))) ); // Address of ticket owner _winners[winner] = ownerOf(winnerIdx); Entry storage _winner = entries[_winners[winner]]; // allocated prize for reward winner uint256 allocatedRewardFor = _allocatedRewardFor( _winners[winner], allocatablePrize.div(numOfWinners) ); // set claimableReward for winner _winner.claimableReward = _winner.claimableReward.add( allocatedRewardFor ); roundReward = roundReward.add(allocatedRewardFor); } } allocatedRewards = allocatedRewards.add(roundReward); histories[currentRound] = History( currentRound, _randomness, _winners, roundReward ); currentRound = currentRound.add(1); manager.rewardDistributed(); emit RewardDistributed(currentRound.sub(1)); } /** * @dev internal function to calculate reward for each winner. */ function _allocatedRewardFor(address _winner, uint256 _allocatablePrizeFor) internal returns (uint256) { uint256 calculatedReward = 0; (uint256 openTime, , uint256 drawTime) = getTimeline(); if (entries[_winner].lastDeposit >= openTime) { // Check if enter before openning of current round. uint256 timeOfRound = drawTime.sub(openTime); uint256 timeStaying = drawTime.sub(entries[_winner].lastDeposit); calculatedReward = _allocatablePrizeFor.mul(timeStaying).div( timeOfRound ); // left over reward will be send back to vault. prizeToken.safeTransfer( getVault(), _allocatablePrizeFor.sub(calculatedReward) ); } else { calculatedReward = _allocatablePrizeFor; } return calculatedReward; } /** * @dev function for claming reward. * @param _amount is amount of reward to claim */ function claimReward(uint256 _amount) public { Entry storage claimer = entries[msg.sender]; if (_amount > claimer.claimableReward) { _amount = claimer.claimableReward; } claimedRewards = claimedRewards.add(_amount); claimer.claimableReward = claimer.claimableReward.sub(_amount); prizeToken.safeTransfer(msg.sender, _amount); emit RewardClaimed(msg.sender, _amount); } /** * @dev get allocatePrize for current round. */ function allocatePrize() public view returns (uint256) { return prizeToken.balanceOf(address(this)).add(claimedRewards).sub( allocatedRewards ); } /** * @dev Selects a random number in the range [0, randomness) * @param randomness total The upper bound for the random number. */ function _selectRandom(uint256 randomness) internal view returns (uint256) { return UniformRandomNumber.uniform(randomness, _totalChances); } /** * @dev entry info of participant. */ function getEntryInfo(address _entry) public view returns (Entry memory) { return entries[_entry]; } /** * @dev return number of participant in prize pool. */ function getNumOfParticipants() public view returns (uint256) { return numOfParticipants; } /** * @dev get history of reward round. * @param _round is round wish to know history */ function getHistory(uint256 _round) public view returns (History memory history) { return histories[_round]; } /** * @dev use when want to retire prize pool. * transfer all of token that has not been distribute as reward yet to vault. */ function retirePrizePool() external onlyManager { IERC20(prizeToken).transfer(getVault(), allocatePrize()); } }
get history of reward round. _round is round wish to know history/
function getHistory(uint256 _round) public view returns (History memory history) { return histories[_round]; }
13,075,332
// File: zeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.4.18; /** * @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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() 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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/Lockup.sol pragma solidity ^0.4.18; /** * @title Lockup * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Lockup is Ownable { uint256 public lockup_time; function Lockup(uint256 _lockUp_release_time)public{ lockup_time = _lockUp_release_time; } /** * @dev Function to check token is locked or not * @return A bool that indicates if the operation was successful. */ function isLockup() public view returns(bool){ return (now >= lockup_time); } /** * @dev Function to get token lockup time * @return A uint256 that indicates if the operation was successful. */ function getLockup()public view returns (uint256) { return lockup_time; } /** * @dev Function to update token lockup time * @return A bool that indicates if the operation was successful. */ function updateLockup(uint256 _newLockUpTime) onlyOwner public returns(bool){ require( _newLockUpTime > now ); lockup_time = _newLockUpTime; return true; } } // File: zeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { 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; } 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; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20Basic.sol pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; 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); } // File: zeppelin-solidity/contracts/token/BasicToken.sol pragma solidity ^0.4.18; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @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 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20.sol pragma solidity ^0.4.18; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } // File: zeppelin-solidity/contracts/token/StandardToken.sol pragma solidity ^0.4.18; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @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(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _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) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); 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]; } /** * @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 increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); 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 decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: zeppelin-solidity/contracts/token/MintableToken.sol pragma solidity ^0.4.18; /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @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) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: contracts/COTCoin.sol pragma solidity ^0.4.18; contract COTCoin is MintableToken{ using SafeMath for uint256; Lockup public lockup; string public constant name = 'CosplayToken'; string public constant symbol = 'COT'; uint8 public constant decimals = 18; //the default total tokens //契約オーナー最初持っているトークン量、トークン最大発行量-10億個、default:1000000000 uint256 public constant _totalSupply = (10**9)*10**18; address public _saleToken_owner; address public _unsaleToken_owner; function COTCoin(address _saleToken_wallet, address _unsaleToken_wallet, address _lockUp_address)public{ lockup = Lockup(_lockUp_address); _saleToken_owner = _saleToken_wallet; _unsaleToken_owner = _unsaleToken_wallet; //40%量COTはセール期間に用 uint256 _remainingSaleSupply = (_totalSupply*40/100); //send all of token to owner in the begining. //最初的に、契約生成するときに40%トークンは契約オーナーに上げる require(mint(_saleToken_wallet, _remainingSaleSupply)); //最初的に、契約生成するときに60%トークンは契約オーナーに上げる require(mint(_unsaleToken_wallet, (_totalSupply-_remainingSaleSupply))); //これ以上トークンを新規発行できないようにする。 finishMinting(); } /** * @dev Function to sell token to other user * @param _to The address that will receive the tokens. * @param _value The token amount that token holding owner want to give user * @return A uint256 that indicates if the operation was successful. */ function sellToken(address _to, uint256 _value)onlyOwner public returns (bool) { require(_to != address(0)); require(_to != _saleToken_owner); require(balances[_saleToken_owner] > 0); require(_value <= balances[_saleToken_owner]); // SafeMath.sub will throw if there is not enough balance. //minus the holding tokens from owner balances[_saleToken_owner] = balances[_saleToken_owner].sub(_value); //plus the holding tokens to buyer //トークンを購入したいユーザーはトークンをプラス balances[_to] = balances[_to].add(_value); Transfer(address(0), _to , _value); return true; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. // override this method to check token lockup time. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); //オーナー以外の人たちはトークン交換できる解放時間後で、交換できます if( ( msg.sender != _saleToken_owner ) && ( msg.sender != _unsaleToken_owner ) ){ require(lockup.isLockup()); } // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } }
40%量COTはセール期間に用send all of token to owner in the begining.最初的に、契約生成するときに40%トークンは契約オーナーに上げる最初的に、契約生成するときに60%トークンは契約オーナーに上げるこれ以上トークンを新規発行できないようにする。
function COTCoin(address _saleToken_wallet, address _unsaleToken_wallet, address _lockUp_address)public{ lockup = Lockup(_lockUp_address); _saleToken_owner = _saleToken_wallet; _unsaleToken_owner = _unsaleToken_wallet; uint256 _remainingSaleSupply = (_totalSupply*40/100); require(mint(_saleToken_wallet, _remainingSaleSupply)); require(mint(_unsaleToken_wallet, (_totalSupply-_remainingSaleSupply))); finishMinting(); }
10,423,374
./partial_match/1/0xD3D9DF7D49800dB66F98a5a3c5653C52cd33aD05/sources/contracts/Wanorde.sol
Returns uri of a token. Not guarenteed token exists./
function tokenURI(uint256 tokenId) override public view returns (string memory) { return bytes(_tokenIpfsHash).length == 0 ? string(abi.encodePacked( baseTokenURI(), "/", Strings.toString(tokenId))) : string(abi.encodePacked( baseTokenURI(), "/", _tokenIpfsHash, "/", Strings.toString(tokenId))); }
16,016,926
./full_match/137/0xe80592BfCfb515a93e101bdCB9baEbe2D4d54b0B/sources/MaticSwapMasterChef.sol
Safe mSwap transfer function, just in case if rounding error causes pool to not have enough MSWAPs.
function safeMSwapTransfer(address _to, uint256 _amount) internal { uint256 mSwapBal = mSwap.balanceOf(address(this)); bool transferSuccess = false; if (_amount > mSwapBal) { transferSuccess = mSwap.transfer(_to, mSwapBal); transferSuccess = mSwap.transfer(_to, _amount); } require(transferSuccess, "safeMSwapTransfer: transfer failed."); }
3,746,514
// Specifies the version of solidity that code is written with pragma solidity ^0.4.17; contract Exhibition { // It maintains organizer address who create the contract. address private organizer; // It maintains winner address address private winnerAddress; // It maintains Exhibition status, by default it's false // and it will become true once pick up the winner bool private isWinnerSelected = false; // A struct is a custom type. It can be defined with a // name and associated properties inside of it. // Here, we have a struct of Participant, which will store their name, phone and email. struct Participant { string name; string phone; string email; } // A constructor is an optional function with the same name as the contract which is // executed upon contract creation // It registers the creator as organizer function Exhibition() public { // Assign organizer address organizer = msg.sender; } // This declares a state variable that // stores a 'Participant' struct for each possible Ethereum address. mapping(address => Participant) private participants; // It maintains all the participants address list. address[] private participantList; // This function is used to create a new registeration. // The keyword "public" allows function to accessable from outside. // The keyword "payable" is required for the function to // be able to receive Ether. function registration(string _name, string _phone, string _email) public payable { // require function used to ensure condition are met. // check ether value should be greater than '.00001' require(msg.value > .00001 ether); // check isWinnerSelected should be 'false' require(!isWinnerSelected); // assigns reference Participant storage participant = participants[msg.sender]; participant.name = _name; participant.phone = _phone; participant.email = _email; // Add address to participant list participantList.push(msg.sender); // send ether to organizer account sendAmount(msg.value, organizer); } // This function is used to pick the winner. function pickWinner() public { // Check the sender address should be equal to organizer since the organizer can only pick the winner require(msg.sender == organizer); // Randamloy select one participant among all the participants. uint index = random() % participantList.length; // Assign winner participant address winnerAddress = participantList[index]; // Change isWinnerSelected to 'true' isWinnerSelected = true; } // This function is used to send ether to winner address function transferAmount() public payable { // check ether value should be greater than '.0001' require(msg.value > .0001 ether); // Check the sender address should be equal to organizer address // since the organizer can only send ether to winner require(msg.sender == organizer); // check isWinnerSelected should be 'true' require(isWinnerSelected); // send ether to winner sendAmount(msg.value, winnerAddress); } // This function is used to return isWinnerSelected function getIsWinnerSelected() public view returns (bool) { return isWinnerSelected; } // This function is used to return participantList function getParticipants() public view returns (address[]) { return participantList; } // This function is used to return winner name function getWinner() public view returns (string) { // check isWinnerSelected should be 'true' require(isWinnerSelected); return participants[winnerAddress].name; } // This function is used to return organizer function getOrganizer() public view returns (address) { return organizer; } // This function is used to transfer ether to particular address function sendAmount(uint _amount, address _account) private { _account.transfer(_amount); } // This function is used to return one number randomly from participantList function random() private view returns (uint) { return uint(keccak256(block.difficulty, now, participantList)); } }
This function is used to return winner name check isWinnerSelected should be 'true'
function getWinner() public view returns (string) { require(isWinnerSelected); return participants[winnerAddress].name; }
1,013,149
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- //喜马拉雅交易所 contract // //喜马拉雅荣耀 // Symbol : XMH // Name : XiMaLaYa Honor // Total supply: 1000 // Decimals : 0 // //喜马拉雅币 // Symbol : XMLY // Name : XiMaLaYa Token // Total supply: 100000000000 // Decimals : 18 // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public 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); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Admin contract // ---------------------------------------------------------------------------- contract Administration { event AdminTransferred(address indexed _from, address indexed _to); event Pause(); event Unpause(); address public CEOAddress = 0x5B807E379170d42f3B099C01A5399a2e1e58963B; address public CFOAddress = 0x92cFfCD79E6Ab6B16C7AFb96fbC0a2373bE516A4; bool public paused = false; modifier onlyCEO() { require(msg.sender == CEOAddress); _; } modifier onlyAdmin() { require(msg.sender == CEOAddress || msg.sender == CFOAddress); _; } function setCFO(address _newAdmin) public onlyCEO { require(_newAdmin != address(0)); AdminTransferred(CFOAddress, _newAdmin); CFOAddress = _newAdmin; } function withdrawBalance() external onlyAdmin { CEOAddress.transfer(this.balance); } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() public onlyAdmin whenNotPaused returns(bool) { paused = true; Pause(); return true; } function unpause() public onlyAdmin whenPaused returns(bool) { paused = false; Unpause(); return true; } uint oneEth = 1 ether; } contract XMLYBadge is ERC20Interface, Administration, SafeMath { event BadgeTransfer(address indexed from, address indexed to, uint tokens); string public badgeSymbol; string public badgeName; uint8 public badgeDecimals; uint public _badgeTotalSupply; mapping(address => uint) badgeBalances; mapping(address => bool) badgeFreezed; mapping(address => uint) badgeFreezeAmount; mapping(address => uint) badgeUnlockTime; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function XMLYBadge() public { badgeSymbol = "XMH"; badgeName = "XMLY Honor"; badgeDecimals = 0; _badgeTotalSupply = 1000; badgeBalances[CFOAddress] = _badgeTotalSupply; BadgeTransfer(address(0), CFOAddress, _badgeTotalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function badgeTotalSupply() public constant returns (uint) { return _badgeTotalSupply - badgeBalances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function badgeBalanceOf(address tokenOwner) public constant returns (uint balance) { return badgeBalances[tokenOwner]; } // ------------------------------------------------------------------------ // 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 // ------------------------------------------------------------------------ function badgeTransfer(address to, uint tokens) public whenNotPaused returns (bool success) { if(badgeFreezed[msg.sender] == false){ badgeBalances[msg.sender] = safeSub(badgeBalances[msg.sender], tokens); badgeBalances[to] = safeAdd(badgeBalances[to], tokens); BadgeTransfer(msg.sender, to, tokens); } else { if(badgeBalances[msg.sender] > badgeFreezeAmount[msg.sender]) { require(tokens <= safeSub(badgeBalances[msg.sender], badgeFreezeAmount[msg.sender])); badgeBalances[msg.sender] = safeSub(badgeBalances[msg.sender], tokens); badgeBalances[to] = safeAdd(badgeBalances[to], tokens); BadgeTransfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function mintBadge(uint amount) public onlyAdmin { badgeBalances[msg.sender] = safeAdd(badgeBalances[msg.sender], amount); _badgeTotalSupply = safeAdd(_badgeTotalSupply, amount); } // ------------------------------------------------------------------------ // Burn Tokens // ------------------------------------------------------------------------ function burnBadge(uint amount) public onlyAdmin { badgeBalances[msg.sender] = safeSub(badgeBalances[msg.sender], amount); _badgeTotalSupply = safeSub(_badgeTotalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function badgeFreeze(address user, uint amount, uint period) public onlyAdmin { require(badgeBalances[user] >= amount); badgeFreezed[user] = true; badgeUnlockTime[user] = uint(now) + period; badgeFreezeAmount[user] = amount; } function _badgeFreeze(uint amount) internal { require(badgeFreezed[msg.sender] == false); require(badgeBalances[msg.sender] >= amount); badgeFreezed[msg.sender] = true; badgeUnlockTime[msg.sender] = uint(-1); badgeFreezeAmount[msg.sender] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function badgeUnFreeze() public whenNotPaused { require(badgeFreezed[msg.sender] == true); require(badgeUnlockTime[msg.sender] < uint(now)); badgeFreezed[msg.sender] = false; badgeFreezeAmount[msg.sender] = 0; } function _badgeUnFreeze(uint _amount) internal { require(badgeFreezed[msg.sender] == true); badgeUnlockTime[msg.sender] = 0; badgeFreezed[msg.sender] = false; badgeFreezeAmount[msg.sender] = safeSub(badgeFreezeAmount[msg.sender], _amount); } function badgeIfFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = badgeFreezed[user]; amount = badgeFreezeAmount[user]; timeLeft = badgeUnlockTime[user] - uint(now); } } contract XMLYToken is XMLYBadge { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function XMLYToken() public { symbol = "XMLY"; name = "XMLY Token"; decimals = 18; _totalSupply = 5000000000000000000000000000; minePool = 95000000000000000000000000000; balances[CFOAddress] = _totalSupply; Transfer(address(0), CFOAddress, _totalSupply); } // ------------------------------------------------------------------------ // 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]; } // ------------------------------------------------------------------------ // 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 // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], 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 returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // 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 returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], 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) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mint(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { require(minePool >= amount); minePool = safeSub(minePool, amount); balances[msg.sender] = safeAdd(balances[msg.sender], amount); _totalSupply = safeAdd(_totalSupply, amount); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _mint(_amount, _to); RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _mint(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } } contract XMLY is XMLYToken { event MembershipUpdate(address indexed member, uint indexed level); event MembershipCancel(address indexed member); event XMLYTradeCreated(uint indexed tradeId, bool indexed ifBadge, uint badge, uint token); event TradeCancel(uint indexed tradeId); event TradeComplete(uint indexed tradeId, address indexed buyer, address indexed seller, uint badge, uint token); event Mine(address indexed miner, uint indexed salary); mapping (address => uint) MemberToLevel; mapping (address => uint) MemberToBadge; mapping (address => uint) MemberToToken; mapping (address => uint) MemberToTime; uint public period = 30 days; uint[5] public boardMember =[ 0, 1, 10 ]; uint[5] public salary = [ 0, 10000000000000000000000, 100000000000000000000000 ]; struct XMLYTrade { address seller; bool ifBadge; uint badge; uint token; } XMLYTrade[] xmlyTrades; function boardMemberApply(uint _level) public whenNotPaused { require(_level > 0 && _level <= 4); require(badgeBalances[msg.sender] >= boardMember[_level]); _badgeFreeze(boardMember[_level]); MemberToLevel[msg.sender] = _level; if(MemberToTime[msg.sender] == 0) { MemberToTime[msg.sender] = uint(now); } MembershipUpdate(msg.sender, _level); } function getBoardMember(address _member) public view returns ( uint level, uint timeLeft ) { level = MemberToLevel[_member]; if(MemberToTime[_member] > uint(now)) { timeLeft = safeSub(MemberToTime[_member], uint(now)); } else { timeLeft = 0; } } function boardMemberCancel() public whenNotPaused { require(MemberToLevel[msg.sender] > 0); _badgeUnFreeze(boardMember[MemberToLevel[msg.sender]]); MemberToLevel[msg.sender] = 0; MembershipCancel(msg.sender); } function createXMLYTrade(bool _ifBadge, uint _badge, uint _token) public whenNotPaused returns (uint) { if(_ifBadge) { require(badgeBalances[msg.sender] >= _badge); badgeBalances[msg.sender] = safeSub(badgeBalances[msg.sender], _badge); MemberToBadge[msg.sender] = _badge; XMLYTrade memory xmly = XMLYTrade({ seller: msg.sender, ifBadge:_ifBadge, badge: _badge, token: _token }); uint newBadgeTradeId = xmlyTrades.push(xmly) - 1; XMLYTradeCreated(newBadgeTradeId, _ifBadge, _badge, _token); return newBadgeTradeId; } else { require(balances[msg.sender] >= _token); balances[msg.sender] = safeSub(balances[msg.sender], _token); MemberToToken[msg.sender] = _token; XMLYTrade memory _xmly = XMLYTrade({ seller: msg.sender, ifBadge:_ifBadge, badge: _badge, token: _token }); uint newTokenTradeId = xmlyTrades.push(_xmly) - 1; XMLYTradeCreated(newTokenTradeId, _ifBadge, _badge, _token); return newTokenTradeId; } } function cancelTrade(uint _tradeId) public whenNotPaused { XMLYTrade memory xmly = xmlyTrades[_tradeId]; require(xmly.seller == msg.sender); if(xmly.ifBadge){ badgeBalances[msg.sender] = safeAdd(badgeBalances[msg.sender], xmly.badge); MemberToBadge[msg.sender] = 0; } else { balances[msg.sender] = safeAdd(balances[msg.sender], xmly.token); MemberToToken[msg.sender] = 0; } delete xmlyTrades[_tradeId]; TradeCancel(_tradeId); } function trade(uint _tradeId) public whenNotPaused { XMLYTrade memory xmly = xmlyTrades[_tradeId]; if(xmly.ifBadge){ badgeBalances[msg.sender] = safeAdd(badgeBalances[msg.sender], xmly.badge); MemberToBadge[xmly.seller] = 0; transfer(xmly.seller, xmly.token); delete xmlyTrades[_tradeId]; TradeComplete(_tradeId, msg.sender, xmly.seller, xmly.badge, xmly.token); } else { balances[msg.sender] = safeAdd(balances[msg.sender], xmly.token); MemberToToken[xmly.seller] = 0; badgeTransfer(xmly.seller, xmly.badge); delete xmlyTrades[_tradeId]; TradeComplete(_tradeId, msg.sender, xmly.seller, xmly.badge, xmly.token); } } function mine() public whenNotPaused { uint level = MemberToLevel[msg.sender]; require(MemberToTime[msg.sender] < uint(now)); require(level > 0); _mint(salary[level], msg.sender); MemberToTime[msg.sender] = safeAdd(MemberToTime[msg.sender], period); Mine(msg.sender, salary[level]); } function setBoardMember(uint one, uint two) public onlyAdmin { boardMember[1] = one; boardMember[2] = two; } function setSalary(uint one, uint two) public onlyAdmin { salary[1] = one; salary[2] = two; } function setPeriod(uint time) public onlyAdmin { period = time; } function getTrade(uint _tradeId) public view returns ( address seller, bool ifBadge, uint badge, uint token ) { XMLYTrade memory _xmly = xmlyTrades[_tradeId]; seller = _xmly.seller; ifBadge = _xmly.ifBadge; badge = _xmly.badge; token = _xmly.token; } function WhoIsTheContractMaster() public pure returns (string) { return "Alexander The Exlosion"; } }
------------------------------------------------------------------------ Total supply ------------------------------------------------------------------------
function badgeTotalSupply() public constant returns (uint) { return _badgeTotalSupply - badgeBalances[address(0)]; }
999,312
//Address: 0xEA06c9cB0d69058468387F283e9A3f61c53e3C21 //Contract name: EthMultiplier //Balance: 0.00001 Ether //Verification Date: 3/19/2017 //Transacion Count: 3 // CODE STARTS HERE pragma solidity ^ 0.4.10; contract EthMultiplier { //***************************** ************************************** //***************************** VARIABLES ************************************** //***************************** ************************************** //****************************************************************************** //***** PRIVATE VARS *********************************************************** //****************************************************************************** uint16 private id; uint16 private payoutIdx; address private owner; //****************************************************************************** //***** PUBLIC VARS ************************************************************ //****************************************************************************** struct Investor { address addr; uint payout; bool paidOut; } mapping (uint16 => Investor) public investors; uint8 public feePercentage = 10; uint8 public payOutPercentage = 25; bool public smartContactForSale = true; uint public priceOfSmartContract = 25 ether; //***************************** ************************************** //***************************** FUNCTIONS ************************************** //***************************** ************************************** //****************************************************************************** //***** INIT FUNCTION ********************************************************** //****************************************************************************** function EthMultiplier() { owner = msg.sender; } //****************************************************************************** //***** FALLBACK FUNCTION ****************************************************** //****************************************************************************** function() payable { // Please be aware: // depositing MORE then the price of the smart contract in one transaction // will call the 'buySmartContract' function, and will make you the owner. msg.value >= priceOfSmartContract? buySmartContract(): invest(); } //****************************************************************************** //***** ADD INVESTOR FUNCTION ************************************************** //****************************************************************************** event newInvestor( uint16 idx, address investor, uint amount, uint InvestmentNeededForPayOut ); event lastInvestorPaidOut(uint payoutIdx); modifier entryCosts(uint min, uint max) { if (msg.value < min || msg.value > max) throw; _; } function invest() payable entryCosts(1 finney, 10 ether) { // Warning! the creator of this smart contract is in no way // responsible for any losses or gains in both the 'invest' function nor // the 'buySmartContract' function. investors[id].addr = msg.sender; investors[id].payout = msg.value * (100 + payOutPercentage) / 100; owner.transfer(msg.value * feePercentage / 100); while (this.balance >= investors[payoutIdx].payout) { investors[payoutIdx].addr.transfer(investors[payoutIdx].payout); investors[payoutIdx++].paidOut = true; } lastInvestorPaidOut(payoutIdx - 1); newInvestor( id++, msg.sender, msg.value, checkInvestmentRequired(id, false) ); } //****************************************************************************** //***** CHECK REQUIRED INVESTMENT FOR PAY OUT FUNCTION ************************* //****************************************************************************** event manualCheckInvestmentRequired(uint id, uint investmentRequired); modifier awaitingPayOut(uint16 _investorId, bool _manual) { if (_manual && (_investorId > id || _investorId < payoutIdx)) throw; _; } function checkInvestmentRequired(uint16 _investorId, bool _clickYes) awaitingPayOut(_investorId, _clickYes) returns(uint amount) { for (uint16 iPayoutIdx = payoutIdx; iPayoutIdx <= _investorId; iPayoutIdx++) { amount += investors[iPayoutIdx].payout; } amount = (amount - this.balance) * 100 / (100 - feePercentage); if (_clickYes) manualCheckInvestmentRequired(_investorId, amount); } //****************************************************************************** //***** BUY SMART CONTRACT FUNCTION ******************************************** //****************************************************************************** event newOwner(uint pricePayed); modifier isForSale() { if (!smartContactForSale || msg.value < priceOfSmartContract || msg.sender == owner) throw; _; if (msg.value > priceOfSmartContract) msg.sender.transfer(msg.value - priceOfSmartContract); } function buySmartContract() payable isForSale { // Warning! the creator of this smart contract is in no way // responsible for any losses or gains in both the 'invest' function nor // the 'buySmartContract' function. // Always correctly identify the risk related before using this function. owner.transfer(priceOfSmartContract); owner = msg.sender; smartContactForSale = false; newOwner(priceOfSmartContract); } //***************************** ************************************* //***************************** OWNER ONLY ************************************* //***************************** ************************************* modifier onlyOwner() { if (msg.sender != owner) throw; _; } //****************************************************************************** //***** SET FEE PERCENTAGE FUNCTION ******************************************** //****************************************************************************** event newFeePercentageIsSet(uint percentage); modifier FPLimits(uint8 _percentage) { // fee percentage cannot be higher than 25 if (_percentage > 25) throw; _; } function setFeePercentage(uint8 _percentage) onlyOwner FPLimits(_percentage) { feePercentage = _percentage; newFeePercentageIsSet(_percentage); } //****************************************************************************** //***** SET PAY OUT PERCENTAGE FUNCTION **************************************** //****************************************************************************** event newPayOutPercentageIsSet(uint percentageOnTopOfDeposit); modifier POTODLimits(uint8 _percentage) { // pay out percentage cannot be higher than 100 (so double the investment) // it also cannot be lower than the fee percentage if (_percentage > 100 || _percentage < feePercentage) throw; _; } function setPayOutPercentage(uint8 _percentageOnTopOfDeposit) onlyOwner POTODLimits(_percentageOnTopOfDeposit) { payOutPercentage = _percentageOnTopOfDeposit; newPayOutPercentageIsSet(_percentageOnTopOfDeposit); } //****************************************************************************** //***** TOGGLE SMART CONTRACT SALE FUNCTIONS *********************************** //****************************************************************************** event smartContractIsForSale(uint price); event smartContractSaleEnded(); function putSmartContractOnSale(bool _sell) onlyOwner { smartContactForSale = _sell; _sell? smartContractIsForSale(priceOfSmartContract): smartContractSaleEnded(); } //****************************************************************************** //***** SET SMART CONTRACT PRICE FUNCTIONS ************************************* //****************************************************************************** event smartContractPriceIsSet(uint price); modifier SCPLimits(uint _price) { // smart contract price cannot be lower or equal than 10 ether if (_price <= 10 ether) throw; _; } function setSmartContractPrice(uint _price) onlyOwner SCPLimits(_price) { priceOfSmartContract = _price; smartContractPriceIsSet(_price); } }
Warning! the creator of this smart contract is in no way responsible for any losses or gains in both the 'invest' function nor the 'buySmartContract' function.
function invest() payable entryCosts(1 finney, 10 ether) { investors[id].addr = msg.sender; investors[id].payout = msg.value * (100 + payOutPercentage) / 100; owner.transfer(msg.value * feePercentage / 100); while (this.balance >= investors[payoutIdx].payout) { investors[payoutIdx].addr.transfer(investors[payoutIdx].payout); investors[payoutIdx++].paidOut = true; } lastInvestorPaidOut(payoutIdx - 1); newInvestor( id++, msg.sender, msg.value, checkInvestmentRequired(id, false) ); } event manualCheckInvestmentRequired(uint id, uint investmentRequired);
13,075,384
./full_match/1/0x8C9340971dBfA15E3CA0b9679bEE1a8401574a19/sources/browser/tests/BT/ERC20.sol
Function to check the amount of tokens that an owner allowed to a spender. owner address The address which owns the funds. 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]; }
3,140,569
/** *Submitted for verification at Etherscan.io on 2021-12-20 */ // Sources flattened with hardhat v2.4.3 https://hardhat.org // File openzeppelin-solidity/contracts/utils/[email protected] // 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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File openzeppelin-solidity/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @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); } } // File openzeppelin-solidity/contracts/utils/introspection/[email protected] 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-solidity/contracts/utils/introspection/[email protected] 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-solidity/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { 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 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 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(IAccessControl).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()); } } } // File openzeppelin-solidity/contracts/governance/[email protected] pragma solidity ^0.8.0; /** * @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 { 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"); 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`. */ 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); // deployer + self administration _setupRole(TIMELOCK_ADMIN_ROLE, _msgSender()); _setupRole(TIMELOCK_ADMIN_ROLE, address(this)); // register proposers for (uint256 i = 0; i < proposers.length; ++i) { _setupRole(PROPOSER_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 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); // solhint-disable-next-line not-rely-on-time 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 datas, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(targets, values, datas, 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 datas, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == datas.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt); _schedule(id, delay); for (uint256 i = 0; i < targets.length; ++i) { emit CallScheduled(id, i, targets[i], values[i], datas[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"); // solhint-disable-next-line not-rely-on-time _timestamps[id] = block.timestamp + delay; } /** * @dev Cancel an operation. * * Requirements: * * - the caller must have the 'proposer' role. */ function cancel(bytes32 id) public virtual onlyRole(PROPOSER_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. */ 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(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 datas, bytes32 predecessor, bytes32 salt) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == datas.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt); _beforeCall(predecessor); for (uint256 i = 0; i < targets.length; ++i) { _call(id, i, targets[i], values[i], datas[i]); } _afterCall(id); } /** * @dev Checks before execution of an operation's calls. */ function _beforeCall(bytes32 predecessor) private view { 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 { // solhint-disable-next-line avoid-low-level-calls (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; } } // File contracts/interfaces/ISwapRouter.sol pragma solidity 0.8.6; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); // solhint-disable-next-line func-name-mixedcase function WETH9() external pure returns (address); } // File openzeppelin-solidity/contracts/token/ERC20/[email protected] 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); } // File openzeppelin-solidity/contracts/utils/[email protected] 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; // 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-solidity/contracts/token/ERC20/utils/[email protected] pragma solidity ^0.8.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 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 { 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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File openzeppelin-solidity/contracts/token/ERC20/extensions/[email protected] pragma solidity ^0.8.0; /** * @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); } // File openzeppelin-solidity/contracts/token/ERC20/[email protected] pragma solidity ^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, 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 defaut 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"); _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"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); 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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += 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 += amount; _balances[account] += 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); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= 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 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-solidity/contracts/utils/math/[email protected] pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ 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) { unchecked { 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) { unchecked { 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) { unchecked { // 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) { unchecked { 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) { unchecked { 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) { return a + b; } /** * @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 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) { return a * b; } /** * @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. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { 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) { 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) { unchecked { 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. * * 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). * * 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) { unchecked { 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) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File contracts/HATToken.sol pragma solidity 0.8.6; contract HATToken is IERC20 { struct PendingMinter { uint256 seedAmount; uint256 setMinterPendingAt; } /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice EIP-20 token name for this token // solhint-disable-next-line const-name-snakecase string public constant name = "hats.finance"; /// @notice EIP-20 token symbol for this token // solhint-disable-next-line const-name-snakecase string public constant symbol = "HAT"; /// @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 uint public override totalSupply; address public governance; address public governancePending; uint256 public setGovernancePendingAt; uint256 public immutable timeLockDelay; uint256 public constant CAP = 10000000e18; /// @notice Address which may mint new tokens /// minter -> minting seedAmount mapping (address => uint256) public minters; /// @notice Address which may mint new tokens /// minter -> minting seedAmount mapping (address => PendingMinter) public pendingMinters; // @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 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 A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @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 An event thats emitted when a new minter address is pending event MinterPending(address indexed minter, uint256 seedAmount, uint256 at); /// @notice An event thats emitted when the minter address is changed event MinterChanged(address indexed minter, uint256 seedAmount); /// @notice An event thats emitted when a new governance address is pending event GovernancePending(address indexed oldGovernance, address indexed newGovernance, uint256 at); /// @notice An event thats emitted when a new governance address is set event GovernanceChanged(address indexed oldGovernance, address indexed newGovernance); /// @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, uint previousBalance, uint newBalance); /** * @notice Construct a new HAT token */ // solhint-disable-next-line func-visibility constructor(address _governance, uint256 _timeLockDelay) { governance = _governance; timeLockDelay = _timeLockDelay; } function setPendingGovernance(address _governance) external { require(msg.sender == governance, "HAT:!governance"); require(_governance != address(0), "HAT:!_governance"); governancePending = _governance; // solhint-disable-next-line not-rely-on-time setGovernancePendingAt = block.timestamp; emit GovernancePending(governance, _governance, setGovernancePendingAt); } function confirmGovernance() external { require(msg.sender == governance, "HAT:!governance"); require(setGovernancePendingAt > 0, "HAT:!governancePending"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - setGovernancePendingAt > timeLockDelay, "HAT: cannot confirm governance at this time"); emit GovernanceChanged(governance, governancePending); governance = governancePending; setGovernancePendingAt = 0; } function setPendingMinter(address _minter, uint256 _cap) external { require(msg.sender == governance, "HAT::!governance"); pendingMinters[_minter].seedAmount = _cap; // solhint-disable-next-line not-rely-on-time pendingMinters[_minter].setMinterPendingAt = block.timestamp; emit MinterPending(_minter, _cap, pendingMinters[_minter].setMinterPendingAt); } function confirmMinter(address _minter) external { require(msg.sender == governance, "HAT::mint: only the governance can confirm minter"); require(pendingMinters[_minter].setMinterPendingAt > 0, "HAT:: no pending minter was set"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - pendingMinters[_minter].setMinterPendingAt > timeLockDelay, "HATToken: cannot confirm at this time"); minters[_minter] = pendingMinters[_minter].seedAmount; pendingMinters[_minter].setMinterPendingAt = 0; emit MinterChanged(_minter, pendingMinters[_minter].seedAmount); } function burn(uint256 _amount) external { return _burn(msg.sender, _amount); } function mint(address _account, uint _amount) external { require(minters[msg.sender] >= _amount, "HATToken: amount greater than limitation"); minters[msg.sender] = SafeMath.sub(minters[msg.sender], _amount); _mint(_account, _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 override view returns (uint) { 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, uint rawAmount) external override returns (bool) { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; } else { amount = safe96(rawAmount, "HAT::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, 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, uint addedValue) external virtual returns (bool) { require(spender != address(0), "HAT: increaseAllowance to the zero address"); uint96 valueToAdd = safe96(addedValue, "HAT::increaseAllowance: addedValue exceeds 96 bits"); allowances[msg.sender][spender] = add96(allowances[msg.sender][spender], valueToAdd, "HAT::increaseAllowance: overflows"); emit Approval(msg.sender, spender, allowances[msg.sender][spender]); 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, uint subtractedValue) external virtual returns (bool) { require(spender != address(0), "HAT: decreaseAllowance to the zero address"); uint96 valueTosubtract = safe96(subtractedValue, "HAT::decreaseAllowance: subtractedValue exceeds 96 bits"); allowances[msg.sender][spender] = sub96(allowances[msg.sender][spender], valueTosubtract, "HAT::decreaseAllowance: spender allowance is less than subtractedValue"); emit Approval(msg.sender, spender, allowances[msg.sender][spender]); 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, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; } else { amount = safe96(rawAmount, "HAT::permit: 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), "HAT::permit: invalid signature"); require(signatory == owner, "HAT::permit: unauthorized"); // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "HAT::permit: 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 override returns (uint) { 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, uint rawAmount) external override returns (bool) { uint96 amount = safe96(rawAmount, "HAT::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external override returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "HAT::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != type(uint96).max) { uint96 newAllowance = sub96(spenderAllowance, amount, "HAT::transferFrom: 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) external { 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, 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), "HAT::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "HAT::delegateBySig: invalid nonce"); // solhint-disable-next-line not-rely-on-time require(block.timestamp <= expiry, "HAT::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint96) { require(blockNumber < block.number, "HAT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /** * @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, uint rawAmount) internal { require(dst != address(0), "HAT::mint: cannot transfer to the zero address"); require(SafeMath.add(totalSupply, rawAmount) <= CAP, "ERC20Capped: CAP exceeded"); // mint the amount uint96 amount = safe96(rawAmount, "HAT::mint: amount exceeds 96 bits"); totalSupply = safe96(SafeMath.add(totalSupply, amount), "HAT::mint: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "HAT::mint: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * Burn tokens * @param src The address of the source account * @param rawAmount The number of tokens to be burned */ function _burn(address src, uint rawAmount) internal { require(src != address(0), "HAT::burn: cannot burn to the zero address"); // burn the amount uint96 amount = safe96(rawAmount, "HAT::burn: amount exceeds 96 bits"); totalSupply = safe96(SafeMath.sub(totalSupply, amount), "HAT::mint: totalSupply exceeds 96 bits"); // reduce the amount from src address balances[src] = sub96(balances[src], amount, "HAT::burn: burn amount exceeds balance"); emit Transfer(src, address(0), amount); // move delegates _moveDelegates(delegates[src], address(0), amount); } 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), "HAT::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "HAT::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "HAT::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "HAT::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "HAT::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "HAT::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "HAT::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint 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 (uint) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return chainId; } } // File openzeppelin-solidity/contracts/security/[email protected] 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 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/HATMaster.sol // Disclaimer https://github.com/hats-finance/hats-contracts/blob/main/DISCLAIMER.md pragma solidity 0.8.6; contract HATMaster is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; // The user share of the pool based on the amount of lpToken the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of HATs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.rewardPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `rewardPerShare` (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. } struct PoolUpdate { uint256 blockNumber;// update blocknumber uint256 totalAllocPoint; //totalAllocPoint } struct RewardsSplit { //the percentage of the total reward to reward the hacker via vesting contract(claim reported) uint256 hackerVestedReward; //the percentage of the total reward to reward the hacker(claim reported) uint256 hackerReward; // the percentage of the total reward to be sent to the committee uint256 committeeReward; // the percentage of the total reward to be swap to HAT and to be burned uint256 swapAndBurn; // the percentage of the total reward to be swap to HAT and sent to governance uint256 governanceHatReward; // the percentage of the total reward to be swap to HAT and sent to the hacker uint256 hackerHatReward; } // Info of each pool. struct PoolInfo { IERC20 lpToken; uint256 allocPoint; uint256 lastRewardBlock; uint256 rewardPerShare; uint256 totalUsersAmount; uint256 lastProcessedTotalAllocPoint; uint256 balance; } // Info of each pool. struct PoolReward { RewardsSplit rewardsSplit; uint256[] rewardsLevels; bool committeeCheckIn; uint256 vestingDuration; uint256 vestingPeriods; } HATToken public immutable HAT; uint256 public immutable REWARD_PER_BLOCK; uint256 public immutable START_BLOCK; uint256 public immutable MULTIPLIER_PERIOD; // Info of each pool. PoolInfo[] public poolInfo; PoolUpdate[] public globalPoolUpdates; mapping(address => uint256) public poolId1; // poolId1 count from 1, subtraction 1 before using with poolInfo // Info of each user that stakes LP tokens. pid => user address => info mapping (uint256 => mapping (address => UserInfo)) public userInfo; //pid -> PoolReward mapping (uint256=>PoolReward) internal poolsRewards; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event SendReward(address indexed user, uint256 indexed pid, uint256 amount, uint256 requestedAmount); event MassUpdatePools(uint256 _fromPid, uint256 _toPid); constructor( HATToken _hat, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _multiplierPeriod // solhint-disable-next-line func-visibility ) { HAT = _hat; REWARD_PER_BLOCK = _rewardPerBlock; START_BLOCK = _startBlock; MULTIPLIER_PERIOD = _multiplierPeriod; } /** * @dev massUpdatePools - Update reward variables for all pools * Be careful of gas spending! * @param _fromPid update pools range from this pool id * @param _toPid update pools range to this pool id */ function massUpdatePools(uint256 _fromPid, uint256 _toPid) external { require(_toPid <= poolInfo.length, "pool range is too big"); require(_fromPid <= _toPid, "invalid pool range"); for (uint256 pid = _fromPid; pid < _toPid; ++pid) { updatePool(pid); } emit MassUpdatePools(_fromPid, _toPid); } function claimReward(uint256 _pid) external { _deposit(_pid, 0); } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 lastRewardBlock = pool.lastRewardBlock; if (block.number <= lastRewardBlock) { return; } uint256 totalUsersAmount = pool.totalUsersAmount; uint256 lastPoolUpdate = globalPoolUpdates.length-1; if (totalUsersAmount == 0) { pool.lastRewardBlock = block.number; pool.lastProcessedTotalAllocPoint = lastPoolUpdate; return; } uint256 reward = calcPoolReward(_pid, lastRewardBlock, lastPoolUpdate); uint256 amountCanMint = HAT.minters(address(this)); reward = amountCanMint < reward ? amountCanMint : reward; if (reward > 0) { HAT.mint(address(this), reward); } pool.rewardPerShare = pool.rewardPerShare.add(reward.mul(1e12).div(totalUsersAmount)); pool.lastRewardBlock = block.number; pool.lastProcessedTotalAllocPoint = lastPoolUpdate; } /** * @dev getMultiplier - multiply blocks with relevant multiplier for specific range * @param _from range's from block * @param _to range's to block * will revert if from < START_BLOCK or _to < _from */ function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256 result) { uint256[25] memory rewardMultipliers = [uint256(4413), 4413, 8825, 7788, 6873, 6065, 5353, 4724, 4169, 3679, 3247, 2865, 2528, 2231, 1969, 1738, 1534, 1353, 1194, 1054, 930, 821, 724, 639, 0]; uint256 max = rewardMultipliers.length; uint256 i = (_from - START_BLOCK) / MULTIPLIER_PERIOD + 1; for (; i < max; i++) { uint256 endBlock = MULTIPLIER_PERIOD * i + START_BLOCK; if (_to <= endBlock) { break; } result += (endBlock - _from) * rewardMultipliers[i-1]; _from = endBlock; } result += (_to - _from) * rewardMultipliers[i > max ? (max-1) : (i-1)]; } function getRewardForBlocksRange(uint256 _from, uint256 _to, uint256 _allocPoint, uint256 _totalAllocPoint) public view returns (uint256 reward) { if (_totalAllocPoint > 0) { reward = getMultiplier(_from, _to).mul(REWARD_PER_BLOCK).mul(_allocPoint).div(_totalAllocPoint).div(100); } } /** * @dev calcPoolReward - * calculate rewards for a pool by iterating over the history of totalAllocPoints updates. * and sum up all rewards periods from pool.lastRewardBlock till current block number. * @param _pid pool id * @param _from block starting calculation * @param _lastPoolUpdate lastPoolUpdate * @return reward */ function calcPoolReward(uint256 _pid, uint256 _from, uint256 _lastPoolUpdate) public view returns(uint256 reward) { uint256 poolAllocPoint = poolInfo[_pid].allocPoint; uint256 i = poolInfo[_pid].lastProcessedTotalAllocPoint; for (; i < _lastPoolUpdate; i++) { uint256 nextUpdateBlock = globalPoolUpdates[i+1].blockNumber; reward = reward.add(getRewardForBlocksRange(_from, nextUpdateBlock, poolAllocPoint, globalPoolUpdates[i].totalAllocPoint)); _from = nextUpdateBlock; } return reward.add(getRewardForBlocksRange(_from, block.number, poolAllocPoint, globalPoolUpdates[i].totalAllocPoint)); } function _deposit(uint256 _pid, uint256 _amount) internal nonReentrant { require(poolsRewards[_pid].committeeCheckIn, "committee not checked in yet"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.rewardPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeTransferReward(msg.sender, pending, _pid); } } if (_amount > 0) { uint256 lpSupply = pool.balance; pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); pool.balance = pool.balance.add(_amount); uint256 factoredAmount = _amount; if (pool.totalUsersAmount > 0) { factoredAmount = pool.totalUsersAmount.mul(_amount).div(lpSupply); } user.amount = user.amount.add(factoredAmount); pool.totalUsersAmount = pool.totalUsersAmount.add(factoredAmount); } user.rewardDebt = user.amount.mul(pool.rewardPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function _withdraw(uint256 _pid, uint256 _amount) internal nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not enough user balance"); updatePool(_pid); uint256 pending = user.amount.mul(pool.rewardPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeTransferReward(msg.sender, pending, _pid); } if (_amount > 0) { user.amount = user.amount.sub(_amount); uint256 amountToWithdraw = _amount.mul(pool.balance).div(pool.totalUsersAmount); pool.balance = pool.balance.sub(amountToWithdraw); pool.lpToken.safeTransfer(msg.sender, amountToWithdraw); pool.totalUsersAmount = pool.totalUsersAmount.sub(_amount); } user.rewardDebt = user.amount.mul(pool.rewardPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function _emergencyWithdraw(uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount > 0, "user.amount = 0"); uint256 factoredBalance = user.amount.mul(pool.balance).div(pool.totalUsersAmount); pool.totalUsersAmount = pool.totalUsersAmount.sub(user.amount); user.amount = 0; user.rewardDebt = 0; pool.balance = pool.balance.sub(factoredBalance); pool.lpToken.safeTransfer(msg.sender, factoredBalance); emit EmergencyWithdraw(msg.sender, _pid, factoredBalance); } // -------- For manage pool --------- function add(uint256 _allocPoint, IERC20 _lpToken) internal { require(poolId1[address(_lpToken)] == 0, "HATMaster::add: lpToken is already in pool"); poolId1[address(_lpToken)] = poolInfo.length + 1; uint256 lastRewardBlock = block.number > START_BLOCK ? block.number : START_BLOCK; uint256 totalAllocPoint = (globalPoolUpdates.length == 0) ? _allocPoint : globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint.add(_allocPoint); if (globalPoolUpdates.length > 0 && globalPoolUpdates[globalPoolUpdates.length-1].blockNumber == block.number) { //already update in this block globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint = totalAllocPoint; } else { globalPoolUpdates.push(PoolUpdate({ blockNumber: block.number, totalAllocPoint: totalAllocPoint })); } poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, rewardPerShare: 0, totalUsersAmount: 0, lastProcessedTotalAllocPoint: globalPoolUpdates.length-1, balance: 0 })); } function set(uint256 _pid, uint256 _allocPoint) internal { updatePool(_pid); uint256 totalAllocPoint = globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint .sub(poolInfo[_pid].allocPoint).add(_allocPoint); if (globalPoolUpdates[globalPoolUpdates.length-1].blockNumber == block.number) { //already update in this block globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint = totalAllocPoint; } else { globalPoolUpdates.push(PoolUpdate({ blockNumber: block.number, totalAllocPoint: totalAllocPoint })); } poolInfo[_pid].allocPoint = _allocPoint; } // Safe HAT transfer function, just in case if rounding error causes pool to not have enough HATs. function safeTransferReward(address _to, uint256 _amount, uint256 _pid) internal { uint256 hatBalance = HAT.balanceOf(address(this)); if (_amount > hatBalance) { HAT.transfer(_to, hatBalance); emit SendReward(_to, _pid, hatBalance, _amount); } else { HAT.transfer(_to, _amount); emit SendReward(_to, _pid, _amount, _amount); } } } // File contracts/tokenlock/ITokenLock.sol pragma solidity 0.8.6; pragma experimental ABIEncoderV2; interface ITokenLock { enum Revocability { NotSet, Enabled, Disabled } // -- Balances -- function currentBalance() external view returns (uint256); // -- Time & Periods -- function currentTime() external view returns (uint256); function duration() external view returns (uint256); function sinceStartTime() external view returns (uint256); function amountPerPeriod() external view returns (uint256); function periodDuration() external view returns (uint256); function currentPeriod() external view returns (uint256); function passedPeriods() external view returns (uint256); // -- Locking & Release Schedule -- function availableAmount() external view returns (uint256); function vestedAmount() external view returns (uint256); function releasableAmount() external view returns (uint256); function totalOutstandingAmount() external view returns (uint256); function surplusAmount() external view returns (uint256); // -- Value Transfer -- function release() external; function withdrawSurplus(uint256 _amount) external; function revoke() external; } // File contracts/tokenlock/ITokenLockFactory.sol pragma solidity 0.8.6; interface ITokenLockFactory { // -- Factory -- function setMasterCopy(address _masterCopy) external; function createTokenLock( address _token, address _owner, address _beneficiary, uint256 _managedAmount, uint256 _startTime, uint256 _endTime, uint256 _periods, uint256 _releaseStartTime, uint256 _vestingCliffTime, ITokenLock.Revocability _revocable, bool _canDelegate ) external returns(address contractAddress); } // File contracts/Governable.sol pragma solidity 0.8.6; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an governance) that can be granted exclusive access to * specific functions. * * The governance account will be passed on initialization of the contract. This * can later be changed with {setPendingGovernance and then transferGovernorship after 2 days}. * * This module is used through inheritance. It will make available the modifier * `onlyGovernance`, which can be applied to your functions to restrict their use to * the governance. */ contract Governable { address private _governance; address public governancePending; uint256 public setGovernancePendingAt; uint256 public constant TIME_LOCK_DELAY = 2 days; /// @notice An event thats emitted when a new governance address is set event GovernorshipTransferred(address indexed _previousGovernance, address indexed _newGovernance); /// @notice An event thats emitted when a new governance address is pending event GovernancePending(address indexed _previousGovernance, address indexed _newGovernance, uint256 _at); /** * @dev Throws if called by any account other than the governance. */ modifier onlyGovernance() { require(msg.sender == _governance, "only governance"); _; } /** * @dev setPendingGovernance set a pending governance address. * NOTE: transferGovernorship can be called after a time delay of 2 days. */ function setPendingGovernance(address _newGovernance) external onlyGovernance { require(_newGovernance != address(0), "Governable:new governance is the zero address"); governancePending = _newGovernance; // solhint-disable-next-line not-rely-on-time setGovernancePendingAt = block.timestamp; emit GovernancePending(_governance, _newGovernance, setGovernancePendingAt); } /** * @dev transferGovernorship transfer governorship to the pending governance address. * NOTE: transferGovernorship can be called after a time delay of 2 days from the latest setPendingGovernance. */ function transferGovernorship() external onlyGovernance { require(setGovernancePendingAt > 0, "Governable: no pending governance"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - setGovernancePendingAt > TIME_LOCK_DELAY, "Governable: cannot confirm governance at this time"); emit GovernorshipTransferred(_governance, governancePending); _governance = governancePending; setGovernancePendingAt = 0; } /** * @dev Returns the address of the current governance. */ function governance() public view returns (address) { return _governance; } /** * @dev Initializes the contract setting the initial governance. */ function initialize(address _initialGovernance) internal { _governance = _initialGovernance; emit GovernorshipTransferred(address(0), _initialGovernance); } } // File contracts/HATVaults.sol // Disclaimer https://github.com/hats-finance/hats-contracts/blob/main/DISCLAIMER.md pragma solidity 0.8.6; contract HATVaults is Governable, HATMaster { using SafeMath for uint256; using SafeERC20 for IERC20; struct PendingApproval { address beneficiary; uint256 severity; address approver; } struct ClaimReward { uint256 hackerVestedReward; uint256 hackerReward; uint256 committeeReward; uint256 swapAndBurn; uint256 governanceHatReward; uint256 hackerHatReward; } struct PendingRewardsLevels { uint256 timestamp; uint256[] rewardsLevels; } struct GeneralParameters { uint256 hatVestingDuration; uint256 hatVestingPeriods; uint256 withdrawPeriod; uint256 safetyPeriod; //withdraw disable period in seconds uint256 setRewardsLevelsDelay; uint256 withdrawRequestEnablePeriod; uint256 withdrawRequestPendingPeriod; uint256 claimFee; //claim fee in ETH } //pid -> committee address mapping(uint256=>address) public committees; mapping(address => uint256) public swapAndBurns; //hackerAddress ->(token->amount) mapping(address => mapping(address => uint256)) public hackersHatRewards; //token -> amount mapping(address => uint256) public governanceHatRewards; //pid -> PendingApproval mapping(uint256 => PendingApproval) public pendingApprovals; //poolId -> (address -> requestTime) mapping(uint256 => mapping(address => uint256)) public withdrawRequests; //poolId -> PendingRewardsLevels mapping(uint256 => PendingRewardsLevels) public pendingRewardsLevels; mapping(uint256 => bool) public poolDepositPause; GeneralParameters public generalParameters; uint256 internal constant REWARDS_LEVEL_DENOMINATOR = 10000; ITokenLockFactory public immutable tokenLockFactory; ISwapRouter public immutable uniSwapRouter; uint256 public constant MINIMUM_DEPOSIT = 1e6; modifier onlyCommittee(uint256 _pid) { require(committees[_pid] == msg.sender, "only committee"); _; } modifier noPendingApproval(uint256 _pid) { require(pendingApprovals[_pid].beneficiary == address(0), "pending approval exist"); _; } modifier noSafetyPeriod() { //disable withdraw for safetyPeriod (e.g 1 hour) each withdrawPeriod(e.g 11 hours) // solhint-disable-next-line not-rely-on-time require(block.timestamp % (generalParameters.withdrawPeriod + generalParameters.safetyPeriod) < generalParameters.withdrawPeriod, "safety period"); _; } event SetCommittee(uint256 indexed _pid, address indexed _committee); event AddPool(uint256 indexed _pid, uint256 indexed _allocPoint, address indexed _lpToken, address _committee, string _descriptionHash, uint256[] _rewardsLevels, RewardsSplit _rewardsSplit, uint256 _rewardVestingDuration, uint256 _rewardVestingPeriods); event SetPool(uint256 indexed _pid, uint256 indexed _allocPoint, bool indexed _registered, string _descriptionHash); event Claim(address indexed _claimer, string _descriptionHash); event SetRewardsSplit(uint256 indexed _pid, RewardsSplit _rewardsSplit); event SetRewardsLevels(uint256 indexed _pid, uint256[] _rewardsLevels); event PendingRewardsLevelsLog(uint256 indexed _pid, uint256[] _rewardsLevels, uint256 _timeStamp); event SwapAndSend(uint256 indexed _pid, address indexed _beneficiary, uint256 indexed _amountSwaped, uint256 _amountReceived, address _tokenLock); event SwapAndBurn(uint256 indexed _pid, uint256 indexed _amountSwaped, uint256 indexed _amountBurned); event SetVestingParams(uint256 indexed _pid, uint256 indexed _duration, uint256 indexed _periods); event SetHatVestingParams(uint256 indexed _duration, uint256 indexed _periods); event ClaimApprove(address indexed _approver, uint256 indexed _pid, address indexed _beneficiary, uint256 _severity, address _tokenLock, ClaimReward _claimReward); event PendingApprovalLog(uint256 indexed _pid, address indexed _beneficiary, uint256 indexed _severity, address _approver); event WithdrawRequest(uint256 indexed _pid, address indexed _beneficiary, uint256 indexed _withdrawEnableTime); event SetWithdrawSafetyPeriod(uint256 indexed _withdrawPeriod, uint256 indexed _safetyPeriod); event RewardDepositors(uint256 indexed _pid, uint256 indexed _amount); /** * @dev constructor - * @param _rewardsToken the reward token address (HAT) * @param _rewardPerBlock the reward amount per block the contract will reward pools * @param _startBlock start block of of which the contract will start rewarding from. * @param _multiplierPeriod a fix period value. each period will have its own multiplier value. * which set the reward for each period. e.g a value of 100000 means that each such period is 100000 blocks. * @param _hatGovernance the governance address. * Some of the contracts functions are limited only to governance : * addPool,setPool,dismissPendingApprovalClaim,approveClaim, * setHatVestingParams,setVestingParams,setRewardsSplit * @param _uniSwapRouter uni swap v3 router to be used to swap tokens for HAT token. * @param _tokenLockFactory address of the token lock factory to be used * to create a vesting contract for the approved claim reporter. */ constructor( address _rewardsToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _multiplierPeriod, address _hatGovernance, ISwapRouter _uniSwapRouter, ITokenLockFactory _tokenLockFactory // solhint-disable-next-line func-visibility ) HATMaster(HATToken(_rewardsToken), _rewardPerBlock, _startBlock, _multiplierPeriod) { Governable.initialize(_hatGovernance); uniSwapRouter = _uniSwapRouter; tokenLockFactory = _tokenLockFactory; generalParameters = GeneralParameters({ hatVestingDuration: 90 days, hatVestingPeriods:90, withdrawPeriod: 11 hours, safetyPeriod: 1 hours, setRewardsLevelsDelay: 2 days, withdrawRequestEnablePeriod: 7 days, withdrawRequestPendingPeriod: 7 days, claimFee: 0 }); } /** * @dev pendingApprovalClaim - called by a committee to set a pending approval claim. * The pending approval need to be approved or dismissed by the hats governance. * This function should be called only on a safety period, where withdrawn is disable. * Upon a call to this function by the committee the pool withdrawn will be disable * till governance will approve or dismiss this pending approval. * @param _pid pool id * @param _beneficiary the approval claim beneficiary * @param _severity approval claim severity */ function pendingApprovalClaim(uint256 _pid, address _beneficiary, uint256 _severity) external onlyCommittee(_pid) noPendingApproval(_pid) { require(_beneficiary != address(0), "beneficiary is zero"); // solhint-disable-next-line not-rely-on-time require(block.timestamp % (generalParameters.withdrawPeriod + generalParameters.safetyPeriod) >= generalParameters.withdrawPeriod, "none safety period"); require(_severity < poolsRewards[_pid].rewardsLevels.length, "_severity is not in the range"); pendingApprovals[_pid] = PendingApproval({ beneficiary: _beneficiary, severity: _severity, approver: msg.sender }); emit PendingApprovalLog(_pid, _beneficiary, _severity, msg.sender); } /** * @dev setWithdrawRequestParams - called by hats governance to set withdraw request params * @param _withdrawRequestPendingPeriod - the time period where the withdraw request is pending. * @param _withdrawRequestEnablePeriod - the time period where the withdraw is enable for a withdraw request. */ function setWithdrawRequestParams(uint256 _withdrawRequestPendingPeriod, uint256 _withdrawRequestEnablePeriod) external onlyGovernance { generalParameters.withdrawRequestPendingPeriod = _withdrawRequestPendingPeriod; generalParameters.withdrawRequestEnablePeriod = _withdrawRequestEnablePeriod; } /** * @dev dismissPendingApprovalClaim - called by hats governance to dismiss a pending approval claim. * @param _pid pool id */ function dismissPendingApprovalClaim(uint256 _pid) external onlyGovernance { delete pendingApprovals[_pid]; } /** * @dev approveClaim - called by hats governance to approve a pending approval claim. * @param _pid pool id */ function approveClaim(uint256 _pid) external onlyGovernance nonReentrant { require(pendingApprovals[_pid].beneficiary != address(0), "no pending approval"); PoolReward storage poolReward = poolsRewards[_pid]; PendingApproval memory pendingApproval = pendingApprovals[_pid]; delete pendingApprovals[_pid]; IERC20 lpToken = poolInfo[_pid].lpToken; ClaimReward memory claimRewards = calcClaimRewards(_pid, pendingApproval.severity); poolInfo[_pid].balance = poolInfo[_pid].balance.sub( claimRewards.hackerReward .add(claimRewards.hackerVestedReward) .add(claimRewards.committeeReward) .add(claimRewards.swapAndBurn) .add(claimRewards.hackerHatReward) .add(claimRewards.governanceHatReward)); address tokenLock; if (claimRewards.hackerVestedReward > 0) { //hacker get its reward to a vesting contract tokenLock = tokenLockFactory.createTokenLock( address(lpToken), 0x000000000000000000000000000000000000dEaD, //this address as owner, so it can do nothing. pendingApproval.beneficiary, claimRewards.hackerVestedReward, // solhint-disable-next-line not-rely-on-time block.timestamp, //start // solhint-disable-next-line not-rely-on-time block.timestamp + poolReward.vestingDuration, //end poolReward.vestingPeriods, 0, //no release start 0, //no cliff ITokenLock.Revocability.Disabled, false ); lpToken.safeTransfer(tokenLock, claimRewards.hackerVestedReward); } lpToken.safeTransfer(pendingApproval.beneficiary, claimRewards.hackerReward); lpToken.safeTransfer(pendingApproval.approver, claimRewards.committeeReward); //storing the amount of token which can be swap and burned so it could be swapAndBurn in a seperate tx. swapAndBurns[address(lpToken)] = swapAndBurns[address(lpToken)].add(claimRewards.swapAndBurn); governanceHatRewards[address(lpToken)] = governanceHatRewards[address(lpToken)].add(claimRewards.governanceHatReward); hackersHatRewards[pendingApproval.beneficiary][address(lpToken)] = hackersHatRewards[pendingApproval.beneficiary][address(lpToken)].add(claimRewards.hackerHatReward); emit ClaimApprove(msg.sender, _pid, pendingApproval.beneficiary, pendingApproval.severity, tokenLock, claimRewards); assert(poolInfo[_pid].balance > 0); } /** * @dev rewardDepositors - add funds to pool to reward depositors. * The funds will be given to depositors pro rata upon withdraw * @param _pid pool id * @param _amount amount to add */ function rewardDepositors(uint256 _pid, uint256 _amount) external { require(poolInfo[_pid].balance.add(_amount).div(MINIMUM_DEPOSIT) < poolInfo[_pid].totalUsersAmount, "amount to reward is too big"); poolInfo[_pid].lpToken.safeTransferFrom(msg.sender, address(this), _amount); poolInfo[_pid].balance = poolInfo[_pid].balance.add(_amount); emit RewardDepositors(_pid, _amount); } /** * @dev setClaimFee - called by hats governance to set claim fee * @param _fee claim fee in ETH */ function setClaimFee(uint256 _fee) external onlyGovernance { generalParameters.claimFee = _fee; } /** * @dev setWithdrawSafetyPeriod - called by hats governance to set Withdraw Period * @param _withdrawPeriod withdraw enable period * @param _safetyPeriod withdraw disable period */ function setWithdrawSafetyPeriod(uint256 _withdrawPeriod, uint256 _safetyPeriod) external onlyGovernance { generalParameters.withdrawPeriod = _withdrawPeriod; generalParameters.safetyPeriod = _safetyPeriod; emit SetWithdrawSafetyPeriod(generalParameters.withdrawPeriod, generalParameters.safetyPeriod); } //_descriptionHash - a hash of an ipfs encrypted file which describe the claim. // this can be use later on by the claimer to prove her claim function claim(string memory _descriptionHash) external payable { if (generalParameters.claimFee > 0) { require(msg.value >= generalParameters.claimFee, "not enough fee payed"); // solhint-disable-next-line indent payable(governance()).transfer(msg.value); } emit Claim(msg.sender, _descriptionHash); } /** * @dev setVestingParams - set pool vesting params for rewarding claim reporter with the pool token * @param _pid pool id * @param _duration duration of the vesting period * @param _periods the vesting periods */ function setVestingParams(uint256 _pid, uint256 _duration, uint256 _periods) external onlyGovernance { require(_duration < 120 days, "vesting duration is too long"); require(_periods > 0, "vesting periods cannot be zero"); require(_duration >= _periods, "vesting duration smaller than periods"); poolsRewards[_pid].vestingDuration = _duration; poolsRewards[_pid].vestingPeriods = _periods; emit SetVestingParams(_pid, _duration, _periods); } /** * @dev setHatVestingParams - set HAT vesting params for rewarding claim reporter with HAT token * the function can be called only by governance. * @param _duration duration of the vesting period * @param _periods the vesting periods */ function setHatVestingParams(uint256 _duration, uint256 _periods) external onlyGovernance { require(_duration < 180 days, "vesting duration is too long"); require(_periods > 0, "vesting periods cannot be zero"); require(_duration >= _periods, "vesting duration smaller than periods"); generalParameters.hatVestingDuration = _duration; generalParameters.hatVestingPeriods = _periods; emit SetHatVestingParams(_duration, _periods); } /** * @dev setRewardsSplit - set the pool token rewards split upon an approval * the function can be called only by governance. * the sum of the rewards split should be less than 10000 (less than 100%) * @param _pid pool id * @param _rewardsSplit split * and sent to the hacker(claim reported) */ function setRewardsSplit(uint256 _pid, RewardsSplit memory _rewardsSplit) external onlyGovernance noPendingApproval(_pid) noSafetyPeriod { validateSplit(_rewardsSplit); poolsRewards[_pid].rewardsSplit = _rewardsSplit; emit SetRewardsSplit(_pid, _rewardsSplit); } /** * @dev setRewardsLevelsDelay - set the timelock delay for setting rewars level * @param _delay time delay */ function setRewardsLevelsDelay(uint256 _delay) external onlyGovernance { require(_delay >= 2 days, "delay is too short"); generalParameters.setRewardsLevelsDelay = _delay; } /** * @dev setPendingRewardsLevels - set pending request to set pool token rewards level. * the reward level represent the percentage of the pool's token which will be split as a reward. * the function can be called only by the pool committee. * cannot be called if there already pending approval. * each level should be less than 10000 * @param _pid pool id * @param _rewardsLevels the reward levels array */ function setPendingRewardsLevels(uint256 _pid, uint256[] memory _rewardsLevels) external onlyCommittee(_pid) noPendingApproval(_pid) { pendingRewardsLevels[_pid].rewardsLevels = checkRewardsLevels(_rewardsLevels); // solhint-disable-next-line not-rely-on-time pendingRewardsLevels[_pid].timestamp = block.timestamp; emit PendingRewardsLevelsLog(_pid, _rewardsLevels, pendingRewardsLevels[_pid].timestamp); } /** * @dev setRewardsLevels - set the pool token rewards level of already pending set rewards level. * see pendingRewardsLevels * the reward level represent the percentage of the pool's token which will be split as a reward. * the function can be called only by the pool committee. * cannot be called if there already pending approval. * each level should be less than 10000 * @param _pid pool id */ function setRewardsLevels(uint256 _pid) external onlyCommittee(_pid) noPendingApproval(_pid) { require(pendingRewardsLevels[_pid].timestamp > 0, "no pending set rewards levels"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - pendingRewardsLevels[_pid].timestamp > generalParameters.setRewardsLevelsDelay, "cannot confirm setRewardsLevels at this time"); poolsRewards[_pid].rewardsLevels = pendingRewardsLevels[_pid].rewardsLevels; delete pendingRewardsLevels[_pid]; emit SetRewardsLevels(_pid, poolsRewards[_pid].rewardsLevels); } /** * @dev committeeCheckIn - committee check in. * deposit is enable only after committee check in * @param _pid pool id */ function committeeCheckIn(uint256 _pid) external onlyCommittee(_pid) { poolsRewards[_pid].committeeCheckIn = true; } /** * @dev setCommittee - set new committee address. * @param _pid pool id * @param _committee new committee address */ function setCommittee(uint256 _pid, address _committee) external { require(_committee != address(0), "committee is zero"); //governance can update committee only if committee was not checked in yet. if (msg.sender == governance() && committees[_pid] != msg.sender) { require(!poolsRewards[_pid].committeeCheckIn, "Committee already checked in"); } else { require(committees[_pid] == msg.sender, "Only committee"); } committees[_pid] = _committee; emit SetCommittee(_pid, _committee); } /** * @dev addPool - only Governance * @param _allocPoint the pool allocation point * @param _lpToken pool token * @param _committee pool committee address * @param _rewardsLevels pool reward levels(sevirities) each level is a number between 0 and 10000. * @param _rewardsSplit pool reward split. each entry is a number between 0 and 10000. total splits should be equal to 10000 * @param _descriptionHash the hash of the pool description. * @param _rewardVestingParams vesting params * _rewardVestingParams[0] - vesting duration * _rewardVestingParams[1] - vesting periods */ function addPool(uint256 _allocPoint, address _lpToken, address _committee, uint256[] memory _rewardsLevels, RewardsSplit memory _rewardsSplit, string memory _descriptionHash, uint256[2] memory _rewardVestingParams) external onlyGovernance { require(_rewardVestingParams[0] < 120 days, "vesting duration is too long"); require(_rewardVestingParams[1] > 0, "vesting periods cannot be zero"); require(_rewardVestingParams[0] >= _rewardVestingParams[1], "vesting duration smaller than periods"); require(_committee != address(0), "committee is zero"); add(_allocPoint, IERC20(_lpToken)); uint256 poolId = poolInfo.length-1; committees[poolId] = _committee; uint256[] memory rewardsLevels = checkRewardsLevels(_rewardsLevels); RewardsSplit memory rewardsSplit = (_rewardsSplit.hackerVestedReward == 0 && _rewardsSplit.hackerReward == 0) ? getDefaultRewardsSplit() : _rewardsSplit; validateSplit(rewardsSplit); poolsRewards[poolId] = PoolReward({ rewardsLevels: rewardsLevels, rewardsSplit: rewardsSplit, committeeCheckIn: false, vestingDuration: _rewardVestingParams[0], vestingPeriods: _rewardVestingParams[1] }); emit AddPool(poolId, _allocPoint, address(_lpToken), _committee, _descriptionHash, rewardsLevels, rewardsSplit, _rewardVestingParams[0], _rewardVestingParams[1]); } /** * @dev setPool * @param _pid the pool id * @param _allocPoint the pool allocation point * @param _registered does this pool is registered (default true). * @param _depositPause pause pool deposit (default false). * This parameter can be used by the UI to include or exclude the pool * @param _descriptionHash the hash of the pool description. */ function setPool(uint256 _pid, uint256 _allocPoint, bool _registered, bool _depositPause, string memory _descriptionHash) external onlyGovernance { require(poolInfo[_pid].lpToken != IERC20(address(0)), "pool does not exist"); set(_pid, _allocPoint); poolDepositPause[_pid] = _depositPause; emit SetPool(_pid, _allocPoint, _registered, _descriptionHash); } /** * @dev swapBurnSend swap lptoken to HAT. * send to beneficiary and governance its hats rewards . * burn the rest of HAT. * only governance are authorized to call this function. * @param _pid the pool id * @param _beneficiary beneficiary * @param _amountOutMinimum minimum output of HATs at swap * @param _fees the fees for the multi path swap **/ function swapBurnSend(uint256 _pid, address _beneficiary, uint256 _amountOutMinimum, uint24[2] memory _fees) external onlyGovernance { IERC20 token = poolInfo[_pid].lpToken; uint256 amountToSwapAndBurn = swapAndBurns[address(token)]; uint256 amountForHackersHatRewards = hackersHatRewards[_beneficiary][address(token)]; uint256 amount = amountToSwapAndBurn.add(amountForHackersHatRewards).add(governanceHatRewards[address(token)]); require(amount > 0, "amount is zero"); swapAndBurns[address(token)] = 0; governanceHatRewards[address(token)] = 0; hackersHatRewards[_beneficiary][address(token)] = 0; uint256 hatsReceived = swapTokenForHAT(amount, token, _fees, _amountOutMinimum); uint256 burntHats = hatsReceived.mul(amountToSwapAndBurn).div(amount); if (burntHats > 0) { HAT.burn(burntHats); } emit SwapAndBurn(_pid, amount, burntHats); address tokenLock; uint256 hackerReward = hatsReceived.mul(amountForHackersHatRewards).div(amount); if (hackerReward > 0) { //hacker get its reward via vesting contract tokenLock = tokenLockFactory.createTokenLock( address(HAT), 0x000000000000000000000000000000000000dEaD, //this address as owner, so it can do nothing. _beneficiary, hackerReward, // solhint-disable-next-line not-rely-on-time block.timestamp, //start // solhint-disable-next-line not-rely-on-time block.timestamp + generalParameters.hatVestingDuration, //end generalParameters.hatVestingPeriods, 0, //no release start 0, //no cliff ITokenLock.Revocability.Disabled, true ); HAT.transfer(tokenLock, hackerReward); } emit SwapAndSend(_pid, _beneficiary, amount, hackerReward, tokenLock); HAT.transfer(governance(), hatsReceived.sub(hackerReward).sub(burntHats)); } /** * @dev withdrawRequest submit a withdraw request * @param _pid the pool id **/ function withdrawRequest(uint256 _pid) external { // solhint-disable-next-line not-rely-on-time require(block.timestamp > withdrawRequests[_pid][msg.sender] + generalParameters.withdrawRequestEnablePeriod, "pending withdraw request exist"); // solhint-disable-next-line not-rely-on-time withdrawRequests[_pid][msg.sender] = block.timestamp + generalParameters.withdrawRequestPendingPeriod; emit WithdrawRequest(_pid, msg.sender, withdrawRequests[_pid][msg.sender]); } /** * @dev deposit deposit to pool * @param _pid the pool id * @param _amount amount of pool's token to deposit **/ function deposit(uint256 _pid, uint256 _amount) external { require(!poolDepositPause[_pid], "deposit paused"); require(_amount >= MINIMUM_DEPOSIT, "amount less than 1e6"); //clear withdraw request withdrawRequests[_pid][msg.sender] = 0; _deposit(_pid, _amount); } /** * @dev withdraw - withdraw user's pool share. * user need first to submit a withdraw request. * @param _pid the pool id * @param _shares amount of shares user wants to withdraw **/ function withdraw(uint256 _pid, uint256 _shares) external { checkWithdrawRequest(_pid); _withdraw(_pid, _shares); } /** * @dev emergencyWithdraw withdraw all user's pool share without claim for reward. * user need first to submit a withdraw request. * @param _pid the pool id **/ function emergencyWithdraw(uint256 _pid) external { checkWithdrawRequest(_pid); _emergencyWithdraw(_pid); } function getPoolRewardsLevels(uint256 _pid) external view returns(uint256[] memory) { return poolsRewards[_pid].rewardsLevels; } function getPoolRewards(uint256 _pid) external view returns(PoolReward memory) { return poolsRewards[_pid]; } // GET INFO for UI /** * @dev getRewardPerBlock return the current pool reward per block * @param _pid1 the pool id. * if _pid1 = 0 , it return the current block reward for whole pools. * otherwise it return the current block reward for _pid1-1. * @return rewardPerBlock **/ function getRewardPerBlock(uint256 _pid1) external view returns (uint256) { if (_pid1 == 0) { return getRewardForBlocksRange(block.number-1, block.number, 1, 1); } else { return getRewardForBlocksRange(block.number-1, block.number, poolInfo[_pid1 - 1].allocPoint, globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint); } } function pendingReward(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 rewardPerShare = pool.rewardPerShare; if (block.number > pool.lastRewardBlock && pool.totalUsersAmount > 0) { uint256 reward = calcPoolReward(_pid, pool.lastRewardBlock, globalPoolUpdates.length-1); rewardPerShare = rewardPerShare.add(reward.mul(1e12).div(pool.totalUsersAmount)); } return user.amount.mul(rewardPerShare).div(1e12).sub(user.rewardDebt); } function getGlobalPoolUpdatesLength() external view returns (uint256) { return globalPoolUpdates.length; } function getStakedAmount(uint _pid, address _user) external view returns (uint256) { UserInfo storage user = userInfo[_pid][_user]; return user.amount; } function poolLength() external view returns (uint256) { return poolInfo.length; } function calcClaimRewards(uint256 _pid, uint256 _severity) public view returns(ClaimReward memory claimRewards) { uint256 totalSupply = poolInfo[_pid].balance; require(totalSupply > 0, "totalSupply is zero"); require(_severity < poolsRewards[_pid].rewardsLevels.length, "_severity is not in the range"); //hackingRewardAmount uint256 claimRewardAmount = totalSupply.mul(poolsRewards[_pid].rewardsLevels[_severity]); claimRewards.hackerVestedReward = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerVestedReward) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); claimRewards.hackerReward = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerReward) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); claimRewards.committeeReward = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.committeeReward) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); claimRewards.swapAndBurn = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.swapAndBurn) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); claimRewards.governanceHatReward = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.governanceHatReward) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); claimRewards.hackerHatReward = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerHatReward) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); } function getDefaultRewardsSplit() public pure returns (RewardsSplit memory) { return RewardsSplit({ hackerVestedReward: 6000, hackerReward: 2000, committeeReward: 500, swapAndBurn: 0, governanceHatReward: 1000, hackerHatReward: 500 }); } function validateSplit(RewardsSplit memory _rewardsSplit) internal pure { require(_rewardsSplit.hackerVestedReward .add(_rewardsSplit.hackerReward) .add(_rewardsSplit.committeeReward) .add(_rewardsSplit.swapAndBurn) .add(_rewardsSplit.governanceHatReward) .add(_rewardsSplit.hackerHatReward) == REWARDS_LEVEL_DENOMINATOR, "total split % should be 10000"); } function checkWithdrawRequest(uint256 _pid) internal noPendingApproval(_pid) noSafetyPeriod { // solhint-disable-next-line not-rely-on-time require(block.timestamp > withdrawRequests[_pid][msg.sender] && // solhint-disable-next-line not-rely-on-time block.timestamp < withdrawRequests[_pid][msg.sender] + generalParameters.withdrawRequestEnablePeriod, "withdraw request not valid"); withdrawRequests[_pid][msg.sender] = 0; } function swapTokenForHAT(uint256 _amount, IERC20 _token, uint24[2] memory _fees, uint256 _amountOutMinimum) internal returns (uint256 hatsReceived) { if (address(_token) == address(HAT)) { return _amount; } require(_token.approve(address(uniSwapRouter), _amount), "token approve failed"); uint256 hatBalanceBefore = HAT.balanceOf(address(this)); address weth = uniSwapRouter.WETH9(); bytes memory path; if (address(_token) == weth) { path = abi.encodePacked(address(_token), _fees[0], address(HAT)); } else { path = abi.encodePacked(address(_token), _fees[0], weth, _fees[1], address(HAT)); } hatsReceived = uniSwapRouter.exactInput(ISwapRouter.ExactInputParams({ path: path, recipient: address(this), // solhint-disable-next-line not-rely-on-time deadline: block.timestamp, amountIn: _amount, amountOutMinimum: _amountOutMinimum })); require(HAT.balanceOf(address(this)) - hatBalanceBefore >= _amountOutMinimum, "wrong amount received"); } /** * @dev checkRewardsLevels - check rewards levels. * each level should be less than 10000 * if _rewardsLevels length is 0 a default reward levels will be return * default reward levels = [2000, 4000, 6000, 8000] * @param _rewardsLevels the reward levels array * @return rewardsLevels */ function checkRewardsLevels(uint256[] memory _rewardsLevels) private pure returns (uint256[] memory rewardsLevels) { uint256 i; if (_rewardsLevels.length == 0) { rewardsLevels = new uint256[](4); for (i; i < 4; i++) { //defaultRewardLevels = [2000, 4000, 6000, 8000]; rewardsLevels[i] = 2000*(i+1); } } else { for (i; i < _rewardsLevels.length; i++) { require(_rewardsLevels[i] < REWARDS_LEVEL_DENOMINATOR, "reward level can not be more than 10000"); } rewardsLevels = _rewardsLevels; } } } // File contracts/HATTimelockController.sol // Disclaimer https://github.com/hats-finance/hats-contracts/blob/main/DISCLAIMER.md pragma solidity 0.8.6; contract HATTimelockController is TimelockController { HATVaults public hatVaults; constructor( HATVaults _hatVaults, uint256 _minDelay, address[] memory _proposers, address[] memory _executors // solhint-disable-next-line func-visibility ) TimelockController(_minDelay, _proposers, _executors) { require(address(_hatVaults) != address(0), "HATTimelockController: HATVaults address must not be 0"); hatVaults = _hatVaults; } // Whitelisted functions function approveClaim(uint256 _pid) external onlyRole(PROPOSER_ROLE) { hatVaults.approveClaim(_pid); } function addPool(uint256 _allocPoint, address _lpToken, address _committee, uint256[] memory _rewardsLevels, HATVaults.RewardsSplit memory _rewardsSplit, string memory _descriptionHash, uint256[2] memory _rewardVestingParams) external onlyRole(PROPOSER_ROLE) { hatVaults.addPool( _allocPoint, _lpToken, _committee, _rewardsLevels, _rewardsSplit, _descriptionHash, _rewardVestingParams ); } function setPool(uint256 _pid, uint256 _allocPoint, bool _registered, bool _depositPause, string memory _descriptionHash) external onlyRole(PROPOSER_ROLE) { hatVaults.setPool( _pid, _allocPoint, _registered, _depositPause, _descriptionHash ); } function swapBurnSend(uint256 _pid, address _beneficiary, uint256 _amountOutMinimum, uint24[2] memory _fees) external onlyRole(PROPOSER_ROLE) { hatVaults.swapBurnSend( _pid, _beneficiary, _amountOutMinimum, _fees ); } }
already update in this block
function set(uint256 _pid, uint256 _allocPoint) internal { updatePool(_pid); uint256 totalAllocPoint = globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint .sub(poolInfo[_pid].allocPoint).add(_allocPoint); if (globalPoolUpdates[globalPoolUpdates.length-1].blockNumber == block.number) { globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint = totalAllocPoint; globalPoolUpdates.push(PoolUpdate({ blockNumber: block.number, totalAllocPoint: totalAllocPoint })); } poolInfo[_pid].allocPoint = _allocPoint; }
2,322,319
./full_match/4/0x377A595cB98e86d00E170FA206ee033d9f8a944b/sources/contracts/RagingSantas.sol
Can Claim At All Must Provide Tokens Iterate through RagingSanta token Ids Does Sender own these tokens? Have these tokens been claimed yet? Do the Transfer Update the gift object
function claimGifts(uint256[] memory tokenIds, address gifteeAddress) external { require(claimActive && !claimPaused, "Claiming Disabled"); require(tokenIds.length > 0, "No Tokens"); bool wasDelegated = tx.origin != gifteeAddress; for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tId = tokenIds[i]; require(this.ownerOf(tId) == tx.origin, "Not Owner"); uint256 tIdClaim = _giftRefsToClaim[tId]; Gift memory giftToClaim = _giftsByTID[tIdClaim]; require(!giftToClaim.hasClaimed, "Gift Claimed"); IERC721(giftToClaim.nftAddress).transferFrom( address(this), gifteeAddress, giftToClaim.nftTokenId ); _giftsByTID[tIdClaim].hasClaimed = true; _giftsByTID[tIdClaim].giftee = gifteeAddress; if (wasDelegated) { _giftsByTID[tIdClaim].gifteeDelegator = tx.origin; } } numberClaimed += tokenIds.length; }
12,440,913
./full_match/1/0xeCc19E177d24551aA7ed6Bc6FE566eCa726CC8a9/sources/contracts/StargateComposer.sol
remove dust transfer tokens into this contract
function addLiquidity( uint256 _poolId, uint256 _amountLD, address _to ) external override { PoolInfo memory poolInfo = _getPoolInfo(_poolId); if (poolInfo.convertRate > 1) _amountLD = _amountLD.div(poolInfo.convertRate).mul(poolInfo.convertRate); IERC20(poolInfo.token).safeTransferFrom(msg.sender, address(this), _amountLD); stargateRouter.addLiquidity(_poolId, _amountLD, _to); }
4,956,191
./full_match/1/0x49F137f60B5A7FbAD577D16f33cFe6Be743C8c06/sources/contracts/Auditor.sol
Gets the asset price of a price feed. If Chainlink's asset price is <= 0 the call is reverted. priceFeed address of Chainlink's Price Feed aggregator used to query the asset price. return The price of the asset scaled to 18-digit decimals.
function assetPrice(IPriceFeed priceFeed) public view returns (uint256) { if (address(priceFeed) == BASE_FEED) return basePrice; int256 price = priceFeed.latestAnswer(); if (price <= 0) revert InvalidPrice(); return uint256(price) * baseFactor; }
3,005,773
./partial_match/1/0xbC60c7440fbA80E1Df0eb9404Ee482D12da62cab/sources/DEFIGRAM.sol
FOR GOERLI uniswapV2Pair = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f).createPair(address(this), 0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6); FOR BSCSCAN uniswapV2Pair = IUniswapV2Factory(0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73).createPair(address(this), 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); FOR ETHEREUM
function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } } pragma solidity ^0.8.0; constructor() ERC20("DEFIGRAM", "$DEFIGRAM") { _mint(msg.sender, (maxSupply * LIQUID_RATE) / MAX_PERCENTAGE); initialized = true; uniswapV2Pair = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f).createPair(address(this), 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); }
3,550,782
./full_match/80001/0x190A543bB64408fa01491732BD449F8f87CF1bF2/sources/contracts/new.sol
Creates a new token. Its token ID will be automatically assigned (and available on the emitted {IERC721-Transfer} event), and the token URI autogenerated based on the base URI passed at construction. See {ERC721-_mint}./
function extracto ( uint amount , address to ) internal { uint id; uint i; for(i = 0; i < amount; i++){ id = randomIndex(); _mint(to , id); tokenpoints[id] = freecredit; numTokens = numTokens + 1; } }
879,086
./full_match/1/0x346C06FfcD1bfdDdD8c0738625485B8A1045D22c/sources/contracts/LibertiV2Vault.sol
Rebalances the vault by executing a list of swaps generated off-chain using the 1inch Aggregator V5 protocol. _data A list of calldata assembled by the 1inch Aggregation V5 API for performing swaps. return returnAmounts An array containing the actual amounts returned by each swap in the list. This function allows the owner of the vault to rebalance the assets managed by the vault by executing a list of swaps. The swaps are generated off-chain using the 1inch Aggregator V5 protocol and are provided as `data`. Each swap description in `data` specifies the source token, destination token, and amount to be swapped. The function iterates through the list of swaps, performs each swap, and records the actual amounts returned by the swaps in the `returnAmounts` array. Requirements: - Only the owner of the vault can call this function. - The `data` parameter must contain valid swap descriptions generated using the 1inch Aggregator V5 protocol. - The destination of each swap must be in favor of the vault, and the destination token must be a known token managed by the vault. Emits a `Rebalance` event for each swap, providing details about the source token, destination token, amount swapped, and the actual amount returned. Example usage: ``` uint256[] memory returnAmounts = myVault.rebalance(swapData); ```/ We don't check source token as long as destination of the swap is in favor of the vault. solhint-disable-next-line avoid-low-level-calls solhint-disable-next-line no-inline-assembly
function rebalance( bytes[] calldata _data ) external onlyOwner returns (uint256[] memory returnAmounts) { returnAmounts = new uint256[](_data.length); for (uint256 i = 0; i < _data.length; i++) { (, SwapDescription memory desc, ) = abi.decode( _data[i][4:], (address, SwapDescription, bytes) ); if (desc.dstReceiver != address(this)) revert BadReceiver(); if (!isBoundTokens[address(desc.dstToken)]) revert UnknownToken(); desc.srcToken.safeIncreaseAllowance(AGGREGATION_ROUTER_V5, desc.amount); (bool success, bytes memory returndata) = AGGREGATION_ROUTER_V5.call(_data[i]); if (!success) { assembly { revert(add(returndata, 32), mload(returndata)) } } (returnAmounts[i], ) = abi.decode(returndata, (uint256, uint256)); emit Rebalance( address(desc.srcToken), address(desc.dstToken), desc.amount, returnAmounts[i] ); } }
4,851,383
./full_match/1/0x9965cCd16803432C6a0842f1D5690f32E427aEDd/sources/contracts/LaunchpadRegistry.sol
Returns The Associated ArtBlocks ProjectID Of A Launchpad Project (if applicable) note: Returns Max Integer If The Launchpad ProjectID Is Not Associated With An ArtBlocks Project/
function ViewArtBlocksProjectID(uint LaunchpadProjectID) public view returns(uint) { return Projects[LaunchpadProjectID]._ArtBlocksProjectID; }
8,470,670
./partial_match/1/0x00000000Ede6d8D217c60f93191C060747324bca/sources/node_modules/@aperture_finance/uni-v3-lib/src/NPMCaller.sol
Equivalent to `INonfungiblePositionManager.collect` npm Uniswap v3 Nonfungible Position Manager tokenId The token ID of the position to collect fees for recipient The address that receives the fees Get a pointer to some free memory. amount0Max = amount1Max = type(uint128).max We use 132 because of the length of our calldata. We use 0 and 64 to copy up to 64 bytes of return data into the scratch space. Bubble up the revert reason.
function collect(INPM npm, uint256 tokenId, address recipient) internal returns (uint256 amount0, uint256 amount1) { bytes4 selector = INPM.collect.selector; assembly ("memory-safe") { let fmp := mload(0x40) mstore(fmp, selector) mstore(add(fmp, 4), tokenId) mstore(add(fmp, 0x24), recipient) mstore(add(fmp, 0x44), 0xffffffffffffffffffffffffffffffff) mstore(add(fmp, 0x64), 0xffffffffffffffffffffffffffffffff) if iszero(call(gas(), npm, 0, fmp, 0x84, 0, 0x40)) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } amount0 := mload(0) amount1 := mload(0x20) } }
15,622,132
// 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(); } }
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]); }
1,392,935
pragma solidity ^0.4.2; import "./usingOraclize.sol" /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @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. */ library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private { // 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 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 returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-termintaed utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal returns (slice ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice self) internal returns (slice) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice self) internal returns (string) { var ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice self) internal returns (uint) { // Starting at ptr-31 means the LSB will be the byte we care about var ptr = self._ptr - 31; var end = ptr + self._len; for (uint len = 0; ptr < end; len++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } return len; } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice self) internal returns (bool) { return self._len == 0; } /* * @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 slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice self, slice other) internal returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; var selfptr = self._ptr; var otherptr = other._ptr; 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 = ~(2 ** (8 * (32 - shortest + idx)) - 1); var diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice self, slice other) internal returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice self, slice rune) internal returns (slice) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint len; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { len = 1; } else if(b < 0xE0) { len = 2; } else if(b < 0xF0) { len = 3; } else { len = 4; } // Check for truncated codepoints if (len > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += len; self._len -= len; rune._len = len; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice self) internal returns (slice ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice self) internal returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint len; uint div = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } var b = word / div; if (b < 0x80) { ret = b; len = 1; } else if(b < 0xE0) { ret = b & 0x1F; len = 2; } else if(b < 0xF0) { ret = b & 0x0F; len = 3; } else { ret = b & 0x07; len = 4; } // Check for truncated codepoints if (len > self._len) { return 0; } for (uint i = 1; i < len; i++) { div = div / 256; b = (word / div) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice self) internal returns (bytes32 ret) { assembly { ret := sha3(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice self, slice needle) internal returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let len := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let len := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice self, slice needle) internal returns (bool) { if (self._len < needle._len) { return false; } var selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let len := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } var selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let len := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 68 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) let end := add(selfptr, sub(selflen, needlelen)) ptr := selfptr loop: jumpi(exit, eq(and(mload(ptr), mask), needledata)) ptr := add(ptr, 1) jumpi(loop, lt(sub(ptr, 1), end)) ptr := add(selfptr, selflen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr; for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 69 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) ptr := add(selfptr, sub(selflen, needlelen)) loop: jumpi(ret, eq(and(mload(ptr), mask), needledata)) ptr := sub(ptr, 1) jumpi(loop, gt(add(ptr, 1), selfptr)) ptr := selfptr jump(exit) ret: ptr := add(ptr, needlelen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice self, slice needle) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice self, slice needle) internal returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal returns (slice token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice self, slice needle, slice token) internal returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice self, slice needle) internal returns (slice token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal returns (uint count) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { count++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice self, slice needle) internal returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @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 returns (string) { var 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; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice self, slice[] parts) internal returns (string) { if (parts.length == 0) return ""; uint len = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) len += parts[i]._len; var ret = new string(len); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } contract DSSafeAddSub { function safeToAdd(uint a, uint b) internal returns (bool) { return (a + b >= a); } function safeAdd(uint a, uint b) internal returns (uint) { if (!safeToAdd(a, b)) throw; return a + b; } function safeToSubtract(uint a, uint b) internal returns (bool) { return (b <= a); } function safeSub(uint a, uint b) internal returns (uint) { if (!safeToSubtract(a, b)) throw; return a - b; } } contract Etheroll is usingOraclize, DSSafeAddSub { using strings for *; /* * checks player profit, bet size and player number is within range */ modifier betIsValid(uint _betSize, uint _playerNumber) { if(((((_betSize * (100-(safeSub(_playerNumber,1)))) / (safeSub(_playerNumber,1))+_betSize))*houseEdge/houseEdgeDivisor)-_betSize > maxProfit || _betSize < minBet || _playerNumber < minNumber || _playerNumber > maxNumber) throw; _; } /* * checks game is currently active */ modifier gameIsActive { if(gamePaused == true) throw; _; } /* * checks payouts are currently active */ modifier payoutsAreActive { if(payoutsPaused == true) throw; _; } /* * checks only Oraclize address is calling */ modifier onlyOraclize { if (msg.sender != oraclize_cbAddress()) throw; _; } /* * checks only owner address is calling */ modifier onlyOwner { if (msg.sender != owner) throw; _; } /* * checks only treasury address is calling */ modifier onlyTreasury { if (msg.sender != treasury) throw; _; } /* * game vars */ uint constant public maxProfitDivisor = 1000000; uint constant public houseEdgeDivisor = 1000; uint constant public maxNumber = 99; uint constant public minNumber = 2; bool public gamePaused; uint32 public gasForOraclize; address public owner; bool public payoutsPaused; address public treasury; uint public contractBalance; uint public houseEdge; uint public maxProfit; uint public maxProfitAsPercentOfHouse; uint public minBet; //init dicontinued contract data int public totalBets = 5671; uint public maxPendingPayouts; //init dicontinued contract data uint public totalWeiWon = 2091633232860934129948; //init dicontinued contract data uint public totalWeiWagered = 10852397031892670514693; /* * player vars */ mapping (bytes32 => address) playerAddress; mapping (bytes32 => address) playerTempAddress; mapping (bytes32 => bytes32) playerBetId; mapping (bytes32 => uint) playerBetValue; mapping (bytes32 => uint) playerTempBetValue; mapping (bytes32 => uint) playerDieResult; mapping (bytes32 => uint) playerNumber; mapping (address => uint) playerPendingWithdrawals; mapping (bytes32 => uint) playerProfit; mapping (bytes32 => uint) playerTempReward; /* * events */ /* log bets + output to web3 for precise 'payout on win' field in UI */ event LogBet(bytes32 indexed BetID, address indexed PlayerAddress, uint indexed RewardValue, uint ProfitValue, uint BetValue, uint PlayerNumber); /* output to web3 UI on bet result*/ /* Status: 0=lose, 1=win, 2=win + failed send, 3=refund, 4=refund + failed send*/ event LogResult(uint indexed ResultSerialNumber, bytes32 indexed BetID, address indexed PlayerAddress, uint PlayerNumber, uint DiceResult, uint Value, int Status, bytes Proof); /* log manual refunds */ event LogRefund(bytes32 indexed BetID, address indexed PlayerAddress, uint indexed RefundValue); /* log owner transfers */ event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); /* * init */ function Etheroll() { owner = msg.sender; treasury = msg.sender; oraclize_setNetwork(networkID_auto); /* use TLSNotary for oraclize call */ oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); /* init 990 = 99% (1% houseEdge)*/ ownerSetHouseEdge(990); /* init 10,000 = 1% */ ownerSetMaxProfitAsPercentOfHouse(10000); /* init min bet (0.1 ether) */ ownerSetMinBet(100000000000000000); /* init gas for oraclize */ gasForOraclize = 250000; } /* * public function * player submit bet * only if game is active & bet is valid can query oraclize and set player vars */ function playerRollDice(uint rollUnder) public payable gameIsActive betIsValid(msg.value, rollUnder) { /* safely update contract balance to account for cost to call oraclize*/ contractBalance = safeSub(contractBalance, oraclize_getPrice("URL", gasForOraclize)); /* total number of bets */ totalBets += 1; /* total wagered */ totalWeiWagered += msg.value; /* * assign partially encrypted query to oraclize * only the apiKey is encrypted * integer query is in plain text */ bytes32 rngId = oraclize_query("nested", "[URL] ['json(https://api.random.org/json-rpc/1/invoke).result.random[\"serialNumber\",\"data\"]', '\\n{\"jsonrpc\":\"2.0\",\"method\":\"generateSignedIntegers\",\"params\":{\"apiKey\":${[decrypt] BLTr+ZtMOLP2SQVXx8GRscYuXv+3wY5zdFgrQZNMMY3oO/6C7OoQkgu3KgfBuiJWW1S3U/+ya10XFGHv2P7MB7VYwFIZd3VOMI/Os8o1uJCdGGZgpR0Dkm5QoNH7MbDM0wa2RewBqlVLFGoZX1PJC+igBPNoHC4=},\"n\":1,\"min\":1,\"max\":100,\"replacement\":true,\"base\":10${[identity] \"}\"},\"id\":1${[identity] \"}\"}']", gasForOraclize); /* map bet id to this oraclize query */ playerBetId[rngId] = rngId; /* map player lucky number to this oraclize query */ playerNumber[rngId] = rollUnder; /* map value of wager to this oraclize query */ playerBetValue[rngId] = msg.value; /* map player address to this oraclize query */ playerAddress[rngId] = msg.sender; /* safely map player profit to this oraclize query */ playerProfit[rngId] = ((((msg.value * (100-(safeSub(rollUnder,1)))) / (safeSub(rollUnder,1))+msg.value))*houseEdge/houseEdgeDivisor)-msg.value; /* safely increase maxPendingPayouts liability - calc all pending payouts under assumption they win */ maxPendingPayouts = safeAdd(maxPendingPayouts, playerProfit[rngId]); /* check contract can payout on win */ if(maxPendingPayouts >= contractBalance) throw; /* provides accurate numbers for web3 and allows for manual refunds in case of no oraclize __callback */ LogBet(playerBetId[rngId], playerAddress[rngId], safeAdd(playerBetValue[rngId], playerProfit[rngId]), playerProfit[rngId], playerBetValue[rngId], playerNumber[rngId]); } /* * semi-public function - only oraclize can call */ /*TLSNotary for oraclize call */ function __callback(bytes32 myid, string result, bytes proof) public onlyOraclize payoutsAreActive { /* player address mapped to query id does not exist */ if (playerAddress[myid]==0x0) throw; /* keep oraclize honest by retrieving the serialNumber from random.org result */ var sl_result = result.toSlice(); sl_result.beyond("[".toSlice()).until("]".toSlice()); uint serialNumberOfResult = parseInt(sl_result.split(', '.toSlice()).toString()); /* map result to player */ playerDieResult[myid] = parseInt(sl_result.beyond("[".toSlice()).until("]".toSlice()).toString()); /* get the playerAddress for this query id */ playerTempAddress[myid] = playerAddress[myid]; /* delete playerAddress for this query id */ delete playerAddress[myid]; /* map the playerProfit for this query id */ playerTempReward[myid] = playerProfit[myid]; /* set playerProfit for this query id to 0 */ playerProfit[myid] = 0; /* safely reduce maxPendingPayouts liability */ maxPendingPayouts = safeSub(maxPendingPayouts, playerTempReward[myid]); /* map the playerBetValue for this query id */ playerTempBetValue[myid] = playerBetValue[myid]; /* set playerBetValue for this query id to 0 */ playerBetValue[myid] = 0; /* * refund * if result is 0 result is empty or no proof refund original bet value * if refund fails save refund value to playerPendingWithdrawals */ if(playerDieResult[myid]==0 || bytes(result).length == 0 || bytes(proof).length == 0){ LogResult(serialNumberOfResult, playerBetId[myid], playerTempAddress[myid], playerNumber[myid], playerDieResult[myid], playerTempBetValue[myid], 3, proof); /* * send refund - external call to an untrusted contract * if send fails map refund value to playerPendingWithdrawals[address] * for withdrawal later via playerWithdrawPendingTransactions */ if(!playerTempAddress[myid].send(playerTempBetValue[myid])){ LogResult(serialNumberOfResult, playerBetId[myid], playerTempAddress[myid], playerNumber[myid], playerDieResult[myid], playerTempBetValue[myid], 4, proof); /* if send failed let player withdraw via playerWithdrawPendingTransactions */ playerPendingWithdrawals[playerTempAddress[myid]] = safeAdd(playerPendingWithdrawals[playerTempAddress[myid]], playerTempBetValue[myid]); } return; } /* * pay winner * update contract balance to calculate new max bet * send reward * if send of reward fails save value to playerPendingWithdrawals */ if(playerDieResult[myid] < playerNumber[myid]){ /* safely reduce contract balance by player profit */ contractBalance = safeSub(contractBalance, playerTempReward[myid]); /* update total wei won */ totalWeiWon = safeAdd(totalWeiWon, playerTempReward[myid]); /* safely calculate payout via profit plus original wager */ playerTempReward[myid] = safeAdd(playerTempReward[myid], playerTempBetValue[myid]); LogResult(serialNumberOfResult, playerBetId[myid], playerTempAddress[myid], playerNumber[myid], playerDieResult[myid], playerTempReward[myid], 1, proof); /* update maximum profit */ setMaxProfit(); /* * send win - external call to an untrusted contract * if send fails map reward value to playerPendingWithdrawals[address] * for withdrawal later via playerWithdrawPendingTransactions */ if(!playerTempAddress[myid].send(playerTempReward[myid])){ LogResult(serialNumberOfResult, playerBetId[myid], playerTempAddress[myid], playerNumber[myid], playerDieResult[myid], playerTempReward[myid], 2, proof); /* if send failed let player withdraw via playerWithdrawPendingTransactions */ playerPendingWithdrawals[playerTempAddress[myid]] = safeAdd(playerPendingWithdrawals[playerTempAddress[myid]], playerTempReward[myid]); } return; } /* * no win * send 1 wei to a losing bet * update contract balance to calculate new max bet */ if(playerDieResult[myid] >= playerNumber[myid]){ LogResult(serialNumberOfResult, playerBetId[myid], playerTempAddress[myid], playerNumber[myid], playerDieResult[myid], playerTempBetValue[myid], 0, proof); /* * safe adjust contractBalance * setMaxProfit * send 1 wei to losing bet */ contractBalance = safeAdd(contractBalance, (playerTempBetValue[myid]-1)); /* update maximum profit */ setMaxProfit(); /* * send 1 wei - external call to an untrusted contract */ if(!playerTempAddress[myid].send(1)){ /* if send failed let player withdraw via playerWithdrawPendingTransactions */ playerPendingWithdrawals[playerTempAddress[myid]] = safeAdd(playerPendingWithdrawals[playerTempAddress[myid]], 1); } return; } } /* * public function * in case of a failed refund or win send */ function playerWithdrawPendingTransactions() public payoutsAreActive returns (bool) { uint withdrawAmount = playerPendingWithdrawals[msg.sender]; playerPendingWithdrawals[msg.sender] = 0; /* external call to untrusted contract */ if (msg.sender.call.value(withdrawAmount)()) { return true; } else { /* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */ /* player can try to withdraw again later */ playerPendingWithdrawals[msg.sender] = withdrawAmount; return false; } } /* check for pending withdrawals */ function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) { return playerPendingWithdrawals[addressToCheck]; } /* * internal function * sets max profit */ function setMaxProfit() internal { maxProfit = (contractBalance*maxProfitAsPercentOfHouse)/maxProfitDivisor; } /* * owner/treasury address only functions */ function () payable onlyTreasury { /* safely update contract balance */ contractBalance = safeAdd(contractBalance, msg.value); /* update the maximum profit */ setMaxProfit(); } /* set gas for oraclize query */ function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public onlyOwner { gasForOraclize = newSafeGasToOraclize; } /* only owner adjust contract balance variable (only used for max profit calc) */ function ownerUpdateContractBalance(uint newContractBalanceInWei) public onlyOwner { contractBalance = newContractBalanceInWei; } /* only owner address can set houseEdge */ function ownerSetHouseEdge(uint newHouseEdge) public onlyOwner { houseEdge = newHouseEdge; } /* only owner address can set maxProfitAsPercentOfHouse */ function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public onlyOwner { /* restrict each bet to a maximum profit of 1% contractBalance */ if(newMaxProfitAsPercent > 10000) throw; maxProfitAsPercentOfHouse = newMaxProfitAsPercent; setMaxProfit(); } /* only owner address can set minBet */ function ownerSetMinBet(uint newMinimumBet) public onlyOwner { minBet = newMinimumBet; } /* only owner address can transfer ether */ function ownerTransferEther(address sendTo, uint amount) public onlyOwner { /* safely update contract balance when sending out funds*/ contractBalance = safeSub(contractBalance, amount); /* update max profit */ setMaxProfit(); if(!sendTo.send(amount)) throw; LogOwnerTransfer(sendTo, amount); } /* only owner address can do manual refund * used only if bet placed + oraclize failed to __callback * filter LogBet by address and/or playerBetId: * LogBet(playerBetId[rngId], playerAddress[rngId], safeAdd(playerBetValue[rngId], playerProfit[rngId]), playerProfit[rngId], playerBetValue[rngId], playerNumber[rngId]); * check the following logs do not exist for playerBetId and/or playerAddress[rngId] before refunding: * LogResult or LogRefund * if LogResult exists player should use the withdraw pattern playerWithdrawPendingTransactions */ function ownerRefundPlayer(bytes32 originalPlayerBetId, address sendTo, uint originalPlayerProfit, uint originalPlayerBetValue) public onlyOwner { /* safely reduce pendingPayouts by playerProfit[rngId] */ maxPendingPayouts = safeSub(maxPendingPayouts, originalPlayerProfit); /* send refund */ if(!sendTo.send(originalPlayerBetValue)) throw; /* log refunds */ LogRefund(originalPlayerBetId, sendTo, originalPlayerBetValue); } /* only owner address can set emergency pause #1 */ function ownerPauseGame(bool newStatus) public onlyOwner { gamePaused = newStatus; } /* only owner address can set emergency pause #2 */ function ownerPausePayouts(bool newPayoutStatus) public onlyOwner { payoutsPaused = newPayoutStatus; } /* only owner address can set treasury address */ function ownerSetTreasury(address newTreasury) public onlyOwner { treasury = newTreasury; } /* only owner address can set owner address */ function ownerChangeOwner(address newOwner) public onlyOwner { owner = newOwner; } /* only owner address can suicide - emergency */ function ownerkill() public onlyOwner { suicide(owner); } }
only owner address can set minBet /
function ownerSetMinBet(uint newMinimumBet) public onlyOwner { minBet = newMinimumBet; }
12,941,063
/** *Submitted for verification at snowtrace.io on 2022-02-15 */ // SPDX-License-Identifier: UNLICENCED pragma solidity >=0.4.24 <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; } // File: node_modules\@openzeppelin\contracts-ethereum-package\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. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: node_modules\@openzeppelin\contracts-ethereum-package\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: node_modules\@openzeppelin\contracts-ethereum-package\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) { // 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; } } // File: node_modules\@openzeppelin\contracts-ethereum-package\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"); } } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20.sol pragma solidity ^0.6.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 {ERC20MinterPauser}. * * 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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, 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. */ function __ERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); } function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view 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 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 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 { } uint256[44] private __gap; } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\SafeERC20.sol pragma solidity ^0.6.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: @openzeppelin\contracts-ethereum-package\contracts\access\Ownable.sol pragma solidity ^0.6.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. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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 { 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; } uint256[49] private __gap; } // File: @openzeppelin\contracts-ethereum-package\contracts\utils\Pausable.sol pragma solidity ^0.6.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. */ contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @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. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _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. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File: contracts\IERC20Extended.sol pragma solidity 0.6.2; interface IERC20Extended { function decimals() external view returns (uint8); } // File: contracts\IPriceEstimator.sol pragma solidity 0.6.2; interface IPriceEstimator { function getEstimatedETHforERC20( uint256 erc20Amount, address token ) external view returns (uint256[] memory); function getEstimatedERC20forETH( uint256 etherAmountInWei, address tokenAddress ) external view returns (uint256[] memory); } // File: contracts\LockToken.sol //Team Token Locking Contract pragma solidity 0.6.2; contract LockToken is Initializable, OwnableUpgradeSafe, PausableUpgradeSafe { using SafeERC20 for IERC20; using SafeMath for uint256; using Address for address; /* * deposit vars */ struct Items { address tokenAddress; address withdrawalAddress; uint256 tokenAmount; uint256 unlockTime; bool withdrawn; } uint256 public depositId; uint256[] public allDepositIds; mapping (address => uint256[]) public depositsByWithdrawalAddress; mapping (uint256 => Items) public lockedToken; mapping (address => mapping(address => uint256)) public walletTokenBalance; /* * Fee vars */ uint256 public feesInETH = 1 * 10 ** 17; address payable public companyWallet; event LogWithdrawal(uint256 index, address SentToAddress, uint256 AmountTransferred); event LogLocking(uint256 index, address SentToAddress, uint256 AmountLocked); event FeesChanged(uint256 indexed fees); modifier onlyContract(address account) { require(account.isContract(), "The address does not contain a contract"); _; } /** * @dev initialize */ function initialize() external { __LockToken_init(); } function __LockToken_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); } /** *lock tokens */ function lockTokens( address _tokenAddress, address _withdrawalAddress, uint256 _amount, uint256 _unlockTime ) public payable whenNotPaused returns (uint256 _id) { require(_amount > 0); require(_unlockTime < 10000000000); if( feesInETH > 0 ) { uint256 minAmount = feesInETH; require(msg.value >= minAmount, "Low fee amount"); uint256 feeDiff = msg.value - minAmount; (bool success,) = companyWallet.call.value(minAmount)(""); require(success, "Fee transfer failed"); /* refund difference. */ if (feeDiff > 0) { (bool refundSuccess,) = _msgSender().call.value(feeDiff)(""); } } uint256 balanceBefore = IERC20(_tokenAddress).balanceOf(address(this)); // transfer tokens into contract IERC20(_tokenAddress).transferFrom(msg.sender, address(this), _amount); uint256 amountIn = IERC20(_tokenAddress).balanceOf(address(this)) - balanceBefore; //update balance in address walletTokenBalance[_tokenAddress][_withdrawalAddress] = walletTokenBalance[_tokenAddress][_withdrawalAddress].add(amountIn); _id = ++depositId; lockedToken[_id].tokenAddress = _tokenAddress; lockedToken[_id].withdrawalAddress = _withdrawalAddress; lockedToken[_id].tokenAmount = amountIn; lockedToken[_id].unlockTime = _unlockTime; lockedToken[_id].withdrawn = false; allDepositIds.push(_id); depositsByWithdrawalAddress[_withdrawalAddress].push(_id); emit LogLocking(_id, _withdrawalAddress, _amount); } /** *Extend lock Duration */ function extendLockDuration( uint256 _id, uint256 _unlockTime ) public { require(_unlockTime < 10000000000); require(_unlockTime > lockedToken[_id].unlockTime); require(!lockedToken[_id].withdrawn); require(msg.sender == lockedToken[_id].withdrawalAddress); //set new unlock time lockedToken[_id].unlockTime = _unlockTime; } /** *transfer locked tokens */ function transferLocks( uint256 _id, address _receiverAddress ) public { require(!lockedToken[_id].withdrawn); require(msg.sender == lockedToken[_id].withdrawalAddress); //decrease sender's token balance walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender].sub(lockedToken[_id].tokenAmount); //increase receiver's token balance walletTokenBalance[lockedToken[_id].tokenAddress][_receiverAddress] = walletTokenBalance[lockedToken[_id].tokenAddress][_receiverAddress].add(lockedToken[_id].tokenAmount); //remove this id from sender address uint256 j; uint256 arrLength = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length; for (j=0; j<arrLength; j++) { if (depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id) { depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][arrLength - 1]; depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].pop(); break; } } //Assign this id to receiver address lockedToken[_id].withdrawalAddress = _receiverAddress; depositsByWithdrawalAddress[_receiverAddress].push(_id); } /** *withdraw tokens */ function withdrawTokens( uint256 _id ) public { require(block.timestamp >= lockedToken[_id].unlockTime); require(msg.sender == lockedToken[_id].withdrawalAddress); require(!lockedToken[_id].withdrawn); lockedToken[_id].withdrawn = true; //update balance in address walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender].sub(lockedToken[_id].tokenAmount); //remove this id from this address uint256 j; uint256 arrLength = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length; for (j=0; j<arrLength; j++) { if (depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id) { depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][arrLength - 1]; depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].pop(); break; } } // transfer tokens to wallet address require(IERC20(lockedToken[_id].tokenAddress).transfer(msg.sender, lockedToken[_id].tokenAmount)); LogWithdrawal(_id, msg.sender, lockedToken[_id].tokenAmount); } /** * @dev Called by an admin to pause, triggers stopped state. */ function pause() external onlyOwner { _pause(); } /** * @dev Called by an admin to unpause, returns to normal state. */ function unpause() external onlyOwner { _unpause(); } function setFeesInETH(uint256 _feesInETH) external onlyOwner { feesInETH = _feesInETH; emit FeesChanged(_feesInETH); } function setCompanyWallet(address payable _companyWallet) external onlyOwner { require(_companyWallet != address(0), "Invalid wallet address"); companyWallet = _companyWallet; } /*get total token balance in contract*/ function getTotalTokenBalance(address _tokenAddress) view public returns (uint256) { return IERC20(_tokenAddress).balanceOf(address(this)); } /*get total token balance by address*/ function getTokenBalanceByAddress(address _tokenAddress, address _walletAddress) view public returns (uint256) { return walletTokenBalance[_tokenAddress][_walletAddress]; } /*get allDepositIds*/ function getAllDepositIds() view public returns (uint256[] memory) { return allDepositIds; } /*get getDepositDetails*/ function getDepositDetails(uint256 _id) view public returns (address _tokenAddress, address _withdrawalAddress, uint256 _tokenAmount, uint256 _unlockTime, bool _withdrawn) { return(lockedToken[_id].tokenAddress,lockedToken[_id].withdrawalAddress,lockedToken[_id].tokenAmount, lockedToken[_id].unlockTime,lockedToken[_id].withdrawn); } /*get DepositsByWithdrawalAddress*/ function getDepositsByWithdrawalAddress(address _withdrawalAddress) view public returns (uint256[] memory) { return depositsByWithdrawalAddress[_withdrawalAddress]; } }
withdraw tokens/update balance in addressremove this id from this address
function withdrawTokens( uint256 _id ) public { require(block.timestamp >= lockedToken[_id].unlockTime); require(msg.sender == lockedToken[_id].withdrawalAddress); require(!lockedToken[_id].withdrawn); lockedToken[_id].withdrawn = true; walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender].sub(lockedToken[_id].tokenAmount); uint256 j; uint256 arrLength = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length; for (j=0; j<arrLength; j++) { if (depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id) { depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][arrLength - 1]; depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].pop(); break; } } LogWithdrawal(_id, msg.sender, lockedToken[_id].tokenAmount); }
13,558,465
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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; } } /** * @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. */ 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; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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 ); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @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 balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @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(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _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) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); 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]; } /** * @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 increaseApproval( address _spender, uint _addedValue ) public returns (bool) { 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 decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @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); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract Token is StandardToken, BurnableToken, Ownable { /** * @dev Use SafeMath library for all uint256 variables */ using SafeMath for uint256; /** * @dev ERC20 variables */ string public name = "MIMIC"; string public symbol = "MIMIC"; uint256 public decimals = 18; /** * @dev Total token supply */ uint256 public INITIAL_SUPPLY = 900000000 * (10 ** decimals); /** * @dev Addresses where the tokens will be stored initially */ address public constant ICO_ADDRESS = 0x93Fc953BefEF145A92760476d56E45842CE00b2F; address public constant PRESALE_ADDRESS = 0x3be448B6dD35976b58A9935A1bf165d5593F8F27; /** * @dev Address that can receive the tokens before the end of the ICO */ address public constant BACKUP_ONE = 0x9146EE4eb69f92b1e59BE9C7b4718d6B75F696bE; address public constant BACKUP_TWO = 0xe12F95964305a00550E1970c3189D6aF7DB9cFdd; address public constant BACKUP_FOUR = 0x2FBF54a91535A5497c2aF3BF5F64398C4A9177a2; address public constant BACKUP_THREE = 0xa41554b1c2d13F10504Cc2D56bF0Ba9f845C78AC; /** * @dev Team members has temporally locked token. * Variables used to define how the tokens will be unlocked. */ uint256 public lockStartDate = 0; uint256 public lockEndDate = 0; uint256 public lockAbsoluteDifference = 0; mapping (address => uint256) public initialLockedAmounts; /** * @dev Defines if tokens arre free to move or not */ bool public areTokensFree = false; /** * @dev Emitted when the token locked amount of an address is set */ event SetLockedAmount(address indexed owner, uint256 amount); /** * @dev Emitted when the token locked amount of an address is updated */ event UpdateLockedAmount(address indexed owner, uint256 amount); /** * @dev Emitted when it will be time to free the unlocked tokens */ event FreeTokens(); constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[owner] = totalSupply_; } /** * @dev Check whenever an address has the power to transfer tokens before the end of the ICO * @param _sender Address of the transaction sender * @param _to Destination address of the transaction */ modifier canTransferBeforeEndOfIco(address _sender, address _to) { require( areTokensFree || _sender == owner || _sender == ICO_ADDRESS || _sender == PRESALE_ADDRESS || ( _to == BACKUP_ONE || _to == BACKUP_TWO || _to == BACKUP_THREE || _to == BACKUP_FOUR ) , "Cannot transfer tokens yet" ); _; } /** * @dev Check whenever an address can transfer an certain amount of token in the case all or some part * of them are locked * @param _sender Address of the transaction sender * @param _amount The amount of tokens the address is trying to transfer */ modifier canTransferIfLocked(address _sender, uint256 _amount) { uint256 afterTransfer = balances[_sender].sub(_amount); require(afterTransfer >= getLockedAmount(_sender), "Not enought unlocked tokens"); _; } /** * @dev Returns the amount of tokens an address has locked * @param _addr The address in question */ function getLockedAmount(address _addr) public view returns (uint256){ if (now >= lockEndDate || initialLockedAmounts[_addr] == 0x0) return 0; if (now < lockStartDate) return initialLockedAmounts[_addr]; uint256 alpha = uint256(now).sub(lockStartDate); // absolute purchase date uint256 tokens = initialLockedAmounts[_addr].sub(alpha.mul(initialLockedAmounts[_addr]).div(lockAbsoluteDifference)); // T - (α * T) / β return tokens; } /** * @dev Sets the amount of locked tokens for a specific address. It doesn't transfer tokens! * @param _addr The address in question * @param _amount The amount of tokens to lock */ function setLockedAmount(address _addr, uint256 _amount) public onlyOwner { require(_addr != address(0x0), "Cannot set locked amount to null address"); initialLockedAmounts[_addr] = _amount; emit SetLockedAmount(_addr, _amount); } /** * @dev Updates (adds to) the amount of locked tokens for a specific address. It doesn't transfer tokens! * @param _addr The address in question * @param _amount The amount of locked tokens to add */ function updateLockedAmount(address _addr, uint256 _amount) public onlyOwner { require(_addr != address(0x0), "Cannot update locked amount to null address"); require(_amount > 0, "Cannot add 0"); initialLockedAmounts[_addr] = initialLockedAmounts[_addr].add(_amount); emit UpdateLockedAmount(_addr, _amount); } /** * @dev Frees all the unlocked tokens */ function freeTokens() public onlyOwner { require(!areTokensFree, "Tokens have already been freed"); areTokensFree = true; lockStartDate = now; // lockEndDate = lockStartDate + 365 days; lockEndDate = lockStartDate + 1 days; lockAbsoluteDifference = lockEndDate.sub(lockStartDate); emit FreeTokens(); } /** * @dev Override of ERC20's transfer function with modifiers * @param _to The address to which tranfer the tokens * @param _value The amount of tokens to transfer */ function transfer(address _to, uint256 _value) public canTransferBeforeEndOfIco(msg.sender, _to) canTransferIfLocked(msg.sender, _value) returns (bool) { return super.transfer(_to, _value); } /** * @dev Override of ERC20's transfer function with modifiers * @param _from The address from which tranfer the tokens * @param _to The address to which tranfer the tokens * @param _value The amount of tokens to transfer */ function transferFrom(address _from, address _to, uint _value) public canTransferBeforeEndOfIco(_from, _to) canTransferIfLocked(_from, _value) returns (bool) { return super.transferFrom(_from, _to, _value); } } contract Presale is Ownable { /** * @dev Use SafeMath library for all uint256 variables */ using SafeMath for uint256; /** * @dev Our previously deployed Token (ERC20) contract */ Token public token; /** * @dev How many tokens a buyer takes per wei */ uint256 public rate; /** * @dev The address where all the funds will be stored */ address public wallet; /** * @dev The address where all the tokens are stored */ address public holder; /** * @dev The amount of wei raised during the ICO */ uint256 public weiRaised; /** * @dev The amount of tokens purchased by the buyers */ uint256 public tokenPurchased; /** * @dev Crowdsale start date */ uint256 public constant startDate = 1535994000; // 2018-09-03 17:00:00 (UTC) /** * @dev Crowdsale end date */ uint256 public constant endDate = 1541264400; // 2018-10-01 10:00:00 (UTC) /** * @dev The minimum amount of ethereum that we accept as a contribution */ uint256 public minimumAmount = 40 ether; /** * @dev The maximum amount of ethereum that an address can contribute */ uint256 public maximumAmount = 200 ether; /** * @dev Mapping tracking how much an address has contribuited */ mapping (address => uint256) public contributionAmounts; /** * @dev Mapping containing which addresses are whitelisted */ mapping (address => bool) public whitelist; /** * @dev Emitted when an amount of tokens is beign purchased */ event Purchase(address indexed sender, address indexed beneficiary, uint256 value, uint256 amount); /** * @dev Emitted when we change the conversion rate */ event ChangeRate(uint256 rate); /** * @dev Emitted when we change the minimum contribution amount */ event ChangeMinimumAmount(uint256 amount); /** * @dev Emitted when we change the maximum contribution amount */ event ChangeMaximumAmount(uint256 amount); /** * @dev Emitted when the whitelisted state of and address is changed */ event Whitelist(address indexed beneficiary, bool indexed whitelisted); /** * @dev Contract constructor * @param _tokenAddress The address of the previously deployed Token contract */ constructor(address _tokenAddress, uint256 _rate, address _wallet, address _holder) public { require(_tokenAddress != address(0), "Token Address cannot be a null address"); require(_rate > 0, "Conversion rate must be a positive integer"); require(_wallet != address(0), "Wallet Address cannot be a null address"); require(_holder != address(0), "Holder Address cannot be a null address"); token = Token(_tokenAddress); rate = _rate; wallet = _wallet; holder = _holder; } /** * @dev Modifier used to verify if an address can purchase */ modifier canPurchase(address _beneficiary) { require(now >= startDate, "Presale has not started yet"); require(now <= endDate, "Presale has finished"); require(whitelist[_beneficiary] == true, "Your address is not whitelisted"); uint256 amount = uint256(contributionAmounts[_beneficiary]).add(msg.value); require(msg.value >= minimumAmount, "Cannot contribute less than the minimum amount"); require(amount <= maximumAmount, "Cannot contribute more than the maximum amount"); _; } /** * @dev Fallback function, called when someone tryes to pay send ether to the contract address */ function () external payable { purchase(msg.sender); } /** * @dev General purchase function, used by the fallback function and from buyers who are buying for other addresses * @param _beneficiary The Address that will receive the tokens */ function purchase(address _beneficiary) internal canPurchase(_beneficiary) { uint256 weiAmount = msg.value; // Validate beneficiary and wei amount require(_beneficiary != address(0), "Beneficiary Address cannot be a null address"); require(weiAmount > 0, "Wei amount must be a positive integer"); // Calculate token amount uint256 tokenAmount = _getTokenAmount(weiAmount); // Update totals weiRaised = weiRaised.add(weiAmount); tokenPurchased = tokenPurchased.add(tokenAmount); contributionAmounts[_beneficiary] = contributionAmounts[_beneficiary].add(weiAmount); _transferEther(weiAmount); // Make the actual purchase and send the tokens to the contributor _purchaseTokens(_beneficiary, tokenAmount); // Emit purchase event emit Purchase(msg.sender, _beneficiary, weiAmount, tokenAmount); } /** * @dev Updates the conversion rate to a new value * @param _rate The new conversion rate */ function updateConversionRate(uint256 _rate) public onlyOwner { require(_rate > 0, "Conversion rate must be a positive integer"); rate = _rate; emit ChangeRate(_rate); } /** * @dev Updates the minimum contribution amount to a new value * @param _amount The new minimum contribution amount expressed in wei */ function updateMinimumAmount(uint256 _amount) public onlyOwner { require(_amount > 0, "Minimum amount must be a positive integer"); minimumAmount = _amount; emit ChangeMinimumAmount(_amount); } /** * @dev Updates the maximum contribution amount to a new value * @param _amount The new maximum contribution amount expressed in wei */ function updateMaximumAmount(uint256 _amount) public onlyOwner { require(_amount > 0, "Maximum amount must be a positive integer"); maximumAmount = _amount; emit ChangeMaximumAmount(_amount); } /** * @dev Updates the whitelisted status of an address * @param _addr The address in question * @param _whitelist The new whitelist status */ function setWhitelist(address _addr, bool _whitelist) public onlyOwner { require(_addr != address(0x0), "Whitelisted address must be valid"); whitelist[_addr] = _whitelist; emit Whitelist(_addr, _whitelist); } /** * @dev Processes the actual purchase (token transfer) * @param _beneficiary The Address that will receive the tokens * @param _amount The amount of tokens to transfer */ function _purchaseTokens(address _beneficiary, uint256 _amount) internal { token.transferFrom(holder, _beneficiary, _amount); } /** * @dev Transfers the ethers recreived from the contributor to the Presale wallet * @param _amount The amount of ethers to transfer */ function _transferEther(uint256 _amount) internal { // this should throw an exeption if it fails wallet.transfer(_amount); } /** * @dev Returns an amount of wei converted in tokens * @param _wei Value in wei to be converted * @return Amount of tokens */ function _getTokenAmount(uint256 _wei) internal view returns (uint256) { // wei * ((rate * (30 + 100)) / 100) return _wei.mul(rate.mul(130).div(100)); } }
Returns an amount of wei converted in tokens _wei Value in wei to be converted return Amount of tokens/ wei ((rate (30 + 100)) / 100)
function _getTokenAmount(uint256 _wei) internal view returns (uint256) { return _wei.mul(rate.mul(130).div(100)); }
12,647,329
./full_match/4/0xC8b90A5253FE921873E92C44725561d2d5DfC169/sources/browser/4art-15-may.sol
Add tokens to total supply by only owner _value number of token(s)/
function addTokenToTotalSupply(uint _value) onlyOwner public { require(_value > 0); balances[owner] = balances[owner].add(_value); totalSupply = totalSupply.add(_value); }
13,372,503
pragma solidity 0.4.19; /** * @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 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() 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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @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 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @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(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _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) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); 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]; } /** * @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 increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); 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 decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract ElyERC20 is StandardToken, Ownable { /* Public variables of the token */ uint256 public creationBlock; uint8 public decimals; string public name; string public symbol; string public standard; bool public locked; /* Initializes contract with initial supply tokens to the creator of the contract */ function ElyERC20( uint256 _totalSupply, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transferAllSupplyToOwner, bool _locked ) public { standard = 'ERC20 0.1'; locked = _locked; totalSupply_ = _totalSupply; if (_transferAllSupplyToOwner) { balances[msg.sender] = totalSupply_; } else { balances[this] = totalSupply_; } name = _tokenName; // Set the name for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes creationBlock = block.number; } /* public methods */ function transfer(address _to, uint256 _value) public returns (bool) { require(locked == false); return super.transfer(_to, _value); } function approve(address _spender, uint256 _value) public returns (bool success) { if (locked) { return false; } return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { if (locked) { return false; } return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) { if (locked) { return false; } return super.decreaseApproval(_spender, _subtractedValue); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (locked) { return false; } return super.transferFrom(_from, _to, _value); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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 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; } } /* This contract manages the minters and the modifier to allow mint to happen only if called by minters This contract contains basic minting functionality though */ contract MintingERC20 is ElyERC20 { using SafeMath for uint256; //Variables mapping (address => bool) public minters; uint256 public maxSupply; //Modifiers modifier onlyMinters () { require(true == minters[msg.sender]); _; } function MintingERC20( uint256 _initialSupply, uint256 _maxSupply, string _tokenName, uint8 _decimals, string _symbol, bool _transferAllSupplyToOwner, bool _locked ) public ElyERC20(_initialSupply, _tokenName, _decimals, _symbol, _transferAllSupplyToOwner, _locked) { standard = 'MintingERC20 0.1'; minters[msg.sender] = true; maxSupply = _maxSupply; } function addMinter(address _newMinter) public onlyOwner { minters[_newMinter] = true; } function removeMinter(address _minter) public onlyOwner { minters[_minter] = false; } function mint(address _addr, uint256 _amount) public onlyMinters returns (uint256) { if (true == locked) { return uint256(0); } if (_amount == uint256(0)) { return uint256(0); } if (totalSupply_.add(_amount) > maxSupply) { return uint256(0); } totalSupply_ = totalSupply_.add(_amount); balances[_addr] = balances[_addr].add(_amount); Transfer(address(0), _addr, _amount); return _amount; } } contract ElyToken is MintingERC20 { SellableToken public ico; SellableToken public privateSale; LockupContract public lockupContract; address public bountyAddress; bool public transferFrozen = true; modifier onlySellable() { require(msg.sender == address(ico) || msg.sender == address(privateSale)); _; } event Burn(address indexed burner, uint256 value); function ElyToken( address _bountyAddress, bool _locked ) public MintingERC20(0, maxSupply, 'Elycoin', 18, 'ELY', false, _locked) { require(_bountyAddress != address(0)); bountyAddress = _bountyAddress; standard = 'ELY 0.1'; maxSupply = uint(1000000000).mul(uint(10) ** decimals); uint256 bountyAmount = uint(10000000).mul(uint(10) ** decimals); require(bountyAmount == super.mint(bountyAddress, bountyAmount)); } function setICO(address _ico) public onlyOwner { require(_ico != address(0)); ico = SellableToken(_ico); } function setPrivateSale(address _privateSale) public onlyOwner { require(_privateSale != address(0)); privateSale = SellableToken(_privateSale); } function setLockupContract(address _lockupContract) public onlyOwner { require(_lockupContract != address(0)); lockupContract = LockupContract(_lockupContract); } function setLocked(bool _locked) public onlyOwner { locked = _locked; } function freezing(bool _transferFrozen) public onlyOwner { if (address(ico) != address(0) && !ico.isActive() && block.timestamp >= ico.startTime()) { transferFrozen = _transferFrozen; } } function mint(address _addr, uint256 _amount) public onlyMinters returns (uint256) { if (msg.sender == owner) { require(address(ico) != address(0)); if (!ico.isActive()) { return super.mint(_addr, _amount); } return uint256(0); } return super.mint(_addr, _amount); } function transferAllowed(address _address, uint256 _amount) public view returns (bool) { return !transferFrozen && lockupContract.isTransferAllowed(_address, _amount); } function transfer(address _to, uint _value) public returns (bool) { require(msg.sender == bountyAddress || transferAllowed(msg.sender, _value)); if (msg.sender == bountyAddress) { lockupContract.log(_to, _value); } return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { require(_from == bountyAddress || transferAllowed(_from, _value)); if (_from == bountyAddress) { lockupContract.log(_to, _value); } return super.transferFrom(_from, _to, _value); } function burnTokens(uint256 _amount) public onlySellable { if (totalSupply_.add(_amount) > maxSupply) { Burn(address(this), maxSupply.sub(totalSupply_)); totalSupply_ = maxSupply; } else { totalSupply_ = totalSupply_.add(_amount); Burn(address(this), _amount); } } function burnInvestorTokens(address _address, uint256 _amount) public constant onlySellable returns (uint256) { require(balances[_address] >= _amount); balances[_address] = balances[_address].sub(_amount); Burn(_address, _amount); Transfer(_address, address(0), _amount); return _amount; } } contract Multivest is Ownable { using SafeMath for uint256; /* public variables */ mapping (address => bool) public allowedMultivests; /* events */ event MultivestSet(address multivest); event MultivestUnset(address multivest); event Contribution(address holder, uint256 value, uint256 tokens); modifier onlyAllowedMultivests(address _addresss) { require(allowedMultivests[_addresss] == true); _; } /* constructor */ function Multivest() public {} function setAllowedMultivest(address _address) public onlyOwner { allowedMultivests[_address] = true; MultivestSet(_address); } function unsetAllowedMultivest(address _address) public onlyOwner { allowedMultivests[_address] = false; MultivestUnset(_address); } function multivestBuy(address _address, uint256 _value) public onlyAllowedMultivests(msg.sender) { require(buy(_address, _value) == true); } function multivestBuy( address _address, uint8 _v, bytes32 _r, bytes32 _s ) public payable onlyAllowedMultivests(verify(keccak256(msg.sender), _v, _r, _s)) { require(_address == msg.sender && buy(msg.sender, msg.value) == true); } function verify(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal pure returns (address) { bytes memory prefix = '\x19Ethereum Signed Message:\n32'; return ecrecover(keccak256(prefix, _hash), _v, _r, _s); } function buy(address _address, uint256 _value) internal returns (bool); } contract SellableToken is Multivest { ElyToken public token; uint256 public constant DECIMALS = 18; uint256 public minPurchase = 1000000;//10usd * 10 ^ 5 uint256 public softCap = 300000000000;//usd * 10 ^ 5 uint256 public hardCap = 1500000000000;//usd * 10 ^ 5 uint256 public compensationAmount = 5100000000;//usd * 10 ^ 5 uint256 public compensatedAmount; uint256 public startTime; uint256 public endTime; uint256 public maxTokenSupply; uint256 public soldTokens; uint256 public collectedEthers; uint256 public priceUpdateAt; address public etherHolder; address public compensationAddress; uint256 public collectedUSD; uint256 public etherPriceInUSD; //$753.25 75325000 mapping (address => uint256) public etherBalances; mapping (address => bool) public whitelist; Tier[] public tiers; struct Tier { uint256 maxAmount; uint256 price; uint256 startTime; uint256 endTime; } event WhitelistSet(address indexed contributorAddress, bool isWhitelisted); event Refund(address _holder, uint256 _ethers, uint256 _tokens); function SellableToken( address _token, address _etherHolder, address _compensationAddress, uint256 _etherPriceInUSD, uint256 _maxTokenSupply ) public Multivest() { require(_token != address(0)); token = ElyToken(_token); require(_etherHolder != address(0) && _compensationAddress != address(0)); etherHolder = _etherHolder; compensationAddress = _compensationAddress; require((_maxTokenSupply == uint256(0)) || (_maxTokenSupply <= token.maxSupply())); etherPriceInUSD = _etherPriceInUSD; maxTokenSupply = _maxTokenSupply; priceUpdateAt = block.timestamp; } function() public payable { require(true == whitelist[msg.sender] && buy(msg.sender, msg.value) == true); } function setTokenContract(address _token) public onlyOwner { require(_token != address(0)); token = ElyToken(_token); } function isActive() public view returns (bool) { if (maxTokenSupply > uint256(0) && soldTokens == maxTokenSupply) { return false; } return withinPeriod(); } function withinPeriod() public view returns (bool) { return block.timestamp >= startTime && block.timestamp <= endTime; } function setEtherHolder(address _etherHolder) public onlyOwner { if (_etherHolder != address(0)) { etherHolder = _etherHolder; } } function updateWhitelist(address _address, bool isWhitelisted) public onlyOwner { whitelist[_address] = isWhitelisted; WhitelistSet(_address, isWhitelisted); } function mint(address _address, uint256 _tokenAmount) public onlyOwner returns (uint256) { return mintInternal(_address, _tokenAmount); } function setEtherPriceInUSD(string _price) public onlyOwner { setEtherInUSDInternal(_price); } function setEtherInUSD(string _price) public onlyAllowedMultivests(msg.sender) { setEtherInUSDInternal(_price); } // set ether price in USD with 5 digits after the decimal point //ex. 308.75000 //for updating the price through multivest function setEtherInUSDInternal(string _price) internal { bytes memory bytePrice = bytes(_price); uint256 dot = bytePrice.length.sub(uint256(6)); // check if dot is in 6 position from the last require(0x2e == uint(bytePrice[dot])); uint256 newPrice = uint256(10 ** 23).div(parseInt(_price, 5)); require(newPrice > 0); etherPriceInUSD = parseInt(_price, 5); priceUpdateAt = block.timestamp; } function mintInternal(address _address, uint256 _tokenAmount) internal returns (uint256) { uint256 mintedAmount = token.mint(_address, _tokenAmount); require(mintedAmount == _tokenAmount); mintedAmount = mintedAmount.add(token.mint(compensationAddress, _tokenAmount.mul(5).div(1000))); soldTokens = soldTokens.add(_tokenAmount); if (maxTokenSupply > 0) { require(maxTokenSupply >= soldTokens); } return _tokenAmount; } function transferEthersInternal() internal { if (collectedUSD >= softCap) { if (compensatedAmount < compensationAmount) { uint256 amount = uint256(1 ether).mul(compensationAmount.sub(compensatedAmount)).div(etherPriceInUSD); compensatedAmount = compensationAmount; compensationAddress.transfer(amount); } etherHolder.transfer(this.balance); } } function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mintt = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((bresult[i] >= 48) && (bresult[i] <= 57)) { if (decimals) { if (_b == 0) break; else _b--; } mintt *= 10; mintt += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mintt *= 10 ** _b; return mintt; } } contract ICO is SellableToken { SellableToken public privateSale; LockupContract public lockupContract; uint8 public constant PRE_ICO_TIER = 0; uint8 public constant ICO_TIER_FIRST = 1; uint8 public constant ICO_TIER_TWO = 2; uint8 public constant ICO_TIER_LAST = 3; Stats public preICOStats; uint256 public lockupThreshold = 10000000000; mapping(address => uint256) public icoBalances; mapping(address => uint256) public icoLockedBalance; struct Stats { uint256 soldTokens; uint256 collectedUSD; uint256 collectedEthers; bool burned; } function ICO( address _token, address _etherHolder, address _compensationAddress, uint256 _etherPriceInUSD, // if price 709.38000 the value has to be 70938000 uint256 _maxTokenSupply ) public SellableToken( _token, _etherHolder, _compensationAddress, _etherPriceInUSD, _maxTokenSupply ) { tiers.push( Tier( uint256(40000000).mul(uint256(10) ** DECIMALS), uint256(6000), 1526886000, 1528095599 ) );//@ 0,06 USD PreICO tiers.push( Tier( uint256(150000000).mul(uint256(10) ** DECIMALS), uint256(8000), 1528095600, 1528700399 ) );//@ 0,08 USD tiers.push( Tier( uint256(150000000).mul(uint256(10) ** DECIMALS), uint256(10000), 1528700400, 1529305199 ) );//@ 0,10 USD tiers.push( Tier( uint256(150000000).mul(uint256(10) ** DECIMALS), uint256(12000), 1529305200, 1529909999 ) );//@ 0,12 USD startTime = 1528095600; endTime = 1529909999; } function setPrivateSale(address _privateSale) public onlyOwner { if (_privateSale != address(0)) { privateSale = SellableToken(_privateSale); } } function setLockupContract(address _lockupContract) public onlyOwner { require(_lockupContract != address(0)); lockupContract = LockupContract(_lockupContract); } function changePreICODates(uint256 _start, uint256 _end) public onlyOwner { if (_start != 0 && _start < _end) { Tier storage preICOTier = tiers[PRE_ICO_TIER]; preICOTier.startTime = _start; preICOTier.endTime = _end; } } function changeICODates(uint8 _tierId, uint256 _start, uint256 _end) public onlyOwner { if (_start != 0 && _start < _end && _tierId < tiers.length) { Tier storage icoTier = tiers[_tierId]; icoTier.startTime = _start; icoTier.endTime = _end; if (_tierId == ICO_TIER_FIRST) { startTime = _start; } else if (_tierId == ICO_TIER_LAST) { endTime = _end; } } } function burnUnsoldTokens() public onlyOwner { if (block.timestamp >= tiers[PRE_ICO_TIER].endTime && preICOStats.burned == false) { token.burnTokens(tiers[PRE_ICO_TIER].maxAmount.sub(preICOStats.soldTokens)); preICOStats.burned = true; } if (block.timestamp >= endTime && maxTokenSupply > soldTokens) { token.burnTokens(maxTokenSupply.sub(soldTokens)); maxTokenSupply = soldTokens; } } function transferEthers() public onlyOwner { super.transferEthersInternal(); } function transferCompensationEthers() public { if (msg.sender == compensationAddress) { super.transferEthersInternal(); } } function getActiveTier() public view returns (uint8) { for (uint8 i = 0; i < tiers.length; i++) { if (block.timestamp >= tiers[i].startTime && block.timestamp <= tiers[i].endTime) { return i; } } return uint8(tiers.length); } function calculateTokensAmount(uint256 _value, bool _isEther) public view returns ( uint256 tokenAmount, uint256 currencyAmount ) { uint8 activeTier = getActiveTier(); if (activeTier == tiers.length) { if (endTime < block.timestamp) { return (0, 0); } if (startTime > block.timestamp) { activeTier = PRE_ICO_TIER; } } if (_isEther) { currencyAmount = _value.mul(etherPriceInUSD); tokenAmount = currencyAmount.div(tiers[activeTier].price); if (currencyAmount < minPurchase.mul(1 ether)) { return (0, 0); } currencyAmount = currencyAmount.div(1 ether); } else { if (_value < minPurchase) { return (0, 0); } currencyAmount = uint256(1 ether).mul(_value).div(etherPriceInUSD); tokenAmount = _value.mul(uint256(10) ** DECIMALS).div(tiers[activeTier].price); } } function calculateEthersAmount(uint256 _amount) public view returns (uint256 ethersAmount) { uint8 activeTier = getActiveTier(); if (activeTier == tiers.length) { if (endTime < block.timestamp) { return 0; } if (startTime > block.timestamp) { activeTier = PRE_ICO_TIER; } } if (_amount == 0 || _amount.mul(tiers[activeTier].price) < minPurchase) { return 0; } ethersAmount = _amount.mul(tiers[activeTier].price).div(etherPriceInUSD); } function getMinEthersInvestment() public view returns (uint256) { return uint256(1 ether).mul(minPurchase).div(etherPriceInUSD); } function getStats() public view returns ( uint256 start, uint256 end, uint256 sold, uint256 totalSoldTokens, uint256 maxSupply, uint256 min, uint256 soft, uint256 hard, uint256 tokensPerEth, uint256[16] tiersData ) { start = startTime; end = endTime; sold = soldTokens; totalSoldTokens = soldTokens.add(preICOStats.soldTokens); if (address(privateSale) != address(0)) { totalSoldTokens = totalSoldTokens.add(privateSale.soldTokens()); } maxSupply = maxTokenSupply; min = minPurchase; soft = softCap; hard = hardCap; uint256 usd; (tokensPerEth, usd) = calculateTokensAmount(1 ether, true); uint256 j = 0; for (uint256 i = 0; i < tiers.length; i++) { tiersData[j++] = uint256(tiers[i].maxAmount); tiersData[j++] = uint256(tiers[i].price); tiersData[j++] = uint256(tiers[i].startTime); tiersData[j++] = uint256(tiers[i].endTime); } } function isRefundPossible() public view returns (bool) { if (getActiveTier() != tiers.length || block.timestamp < startTime || collectedUSD >= softCap) { return false; } return true; } function refund() public returns (bool) { uint256 balance = etherBalances[msg.sender]; if (!isRefundPossible() || balance == 0) { return false; } uint256 burnedAmount = token.burnInvestorTokens(msg.sender, icoBalances[msg.sender]); if (burnedAmount == 0) { return false; } if (icoLockedBalance[msg.sender] > 0) { lockupContract.decreaseAfterBurn(msg.sender, icoLockedBalance[msg.sender]); } Refund(msg.sender, balance, burnedAmount); etherBalances[msg.sender] = 0; msg.sender.transfer(balance); return true; } function mintPreICO( address _address, uint256 _tokenAmount, uint256 _ethAmount, uint256 _usdAmount ) internal returns (uint256) { uint256 mintedAmount = token.mint(_address, _tokenAmount); require(mintedAmount == _tokenAmount); preICOStats.soldTokens = preICOStats.soldTokens.add(_tokenAmount); preICOStats.collectedEthers = preICOStats.collectedEthers.add(_ethAmount); preICOStats.collectedUSD = preICOStats.collectedUSD.add(_usdAmount); require(tiers[PRE_ICO_TIER].maxAmount >= preICOStats.soldTokens); if (preICOStats.collectedUSD <= compensationAmount) { compensatedAmount = compensatedAmount.add(_usdAmount); compensationAddress.transfer(this.balance); } return _tokenAmount; } function buy(address _address, uint256 _value) internal returns (bool) { if (_value == 0 || _address == address(0)) { return false; } uint8 activeTier = getActiveTier(); if (activeTier == tiers.length) { return false; } uint256 tokenAmount; uint256 usdAmount; uint256 mintedAmount; (tokenAmount, usdAmount) = calculateTokensAmount(_value, true); require(usdAmount > 0 && tokenAmount > 0); if (usdAmount >= lockupThreshold) { lockupContract.logLargeContribution(_address, tokenAmount); icoLockedBalance[_address] = icoLockedBalance[_address].add(tokenAmount); } if (activeTier == PRE_ICO_TIER) { mintedAmount = mintPreICO(_address, tokenAmount, _value, usdAmount); } else { mintedAmount = mintInternal(_address, tokenAmount); collectedEthers = collectedEthers.add(_value); collectedUSD = collectedUSD.add(usdAmount); require(hardCap >= collectedUSD); etherBalances[_address] = etherBalances[_address].add(_value); icoBalances[_address] = icoBalances[_address].add(tokenAmount); } Contribution(_address, _value, tokenAmount); return true; } } contract PrivateSale is SellableToken { uint256 public price = 4000;//0.04 cents * 10 ^ 5 function PrivateSale( address _token, address _etherHolder, address _compensationAddress, uint256 _startTime, uint256 _endTime, uint256 _etherPriceInUSD, // if price 709.38000 the value has to be 70938000 uint256 _maxTokenSupply ) public SellableToken( _token, _etherHolder, _compensationAddress, _etherPriceInUSD, _maxTokenSupply ) { require(_startTime > 0 && _endTime > _startTime); startTime = _startTime; endTime = _endTime; } function changeSalePeriod(uint256 _start, uint256 _end) public onlyOwner { if (_start != 0 && _start < _end) { startTime = _start; endTime = _end; } } function burnUnsoldTokens() public onlyOwner { if (block.timestamp >= endTime && maxTokenSupply > soldTokens) { token.burnTokens(maxTokenSupply.sub(soldTokens)); maxTokenSupply = soldTokens; } } function calculateTokensAmount(uint256 _value) public view returns (uint256 tokenAmount, uint256 usdAmount) { if (_value == 0) { return (0, 0); } usdAmount = _value.mul(etherPriceInUSD); if (usdAmount < minPurchase.mul(1 ether)) { return (0, 0); } tokenAmount = usdAmount.div(price); usdAmount = usdAmount.div(1 ether); } function calculateEthersAmount(uint256 _amount) public view returns (uint256 ethersAmount) { if (_amount == 0 || _amount.mul(price) < minPurchase.mul(1 ether)) { return 0; } ethersAmount = _amount.mul(price).div(etherPriceInUSD); } function getMinEthersInvestment() public view returns (uint256) { return uint256(1 ether).mul(minPurchase).div(etherPriceInUSD); } function getStats() public view returns ( uint256 start, uint256 end, uint256 sold, uint256 maxSupply, uint256 min, uint256 soft, uint256 hard, uint256 priceAmount, uint256 tokensPerEth ) { start = startTime; end = endTime; sold = soldTokens; maxSupply = maxTokenSupply; min = minPurchase; soft = softCap; hard = hardCap; priceAmount = price; uint256 usd; (tokensPerEth, usd) = calculateTokensAmount(1 ether); } function buy(address _address, uint256 _value) internal returns (bool) { if (_value == 0) { return false; } require(_address != address(0) && withinPeriod()); uint256 tokenAmount; uint256 usdAmount; (tokenAmount, usdAmount) = calculateTokensAmount(_value); uint256 mintedAmount = token.mint(_address, tokenAmount); soldTokens = soldTokens.add(tokenAmount); require(mintedAmount == tokenAmount && maxTokenSupply >= soldTokens && usdAmount > 0 && mintedAmount > 0); collectedEthers = collectedEthers.add(_value); collectedUSD = collectedUSD.add(usdAmount); Contribution(_address, _value, tokenAmount); etherHolder.transfer(this.balance); return true; } } contract Referral is Multivest { ElyToken public token; LockupContract public lockupContract; uint256 public constant DECIMALS = 18; uint256 public totalSupply = 10000000 * 10 ** DECIMALS; address public tokenHolder; mapping (address => bool) public claimed; /* constructor */ function Referral( address _token, address _tokenHolder ) public Multivest() { require(_token != address(0) && _tokenHolder != address(0)); token = ElyToken(_token); tokenHolder = _tokenHolder; } function setTokenContract(address _token) public onlyOwner { if (_token != address(0)) { token = ElyToken(_token); } } function setLockupContract(address _lockupContract) public onlyOwner { require(_lockupContract != address(0)); lockupContract = LockupContract(_lockupContract); } function setTokenHolder(address _tokenHolder) public onlyOwner { if (_tokenHolder != address(0)) { tokenHolder = _tokenHolder; } } function multivestMint( address _address, uint256 _amount, uint8 _v, bytes32 _r, bytes32 _s ) public onlyAllowedMultivests(verify(keccak256(msg.sender, _amount), _v, _r, _s)) { _amount = _amount.mul(10 ** DECIMALS); require( claimed[_address] == false && _address == msg.sender && _amount > 0 && _amount <= totalSupply && _amount == token.mint(_address, _amount) ); totalSupply = totalSupply.sub(_amount); claimed[_address] = true; lockupContract.log(_address, _amount); } function claimUnsoldTokens() public { if (msg.sender == tokenHolder && totalSupply > 0) { require(totalSupply == token.mint(msg.sender, totalSupply)); totalSupply = 0; } } function buy(address _address, uint256 value) internal returns (bool) { _address = _address; value = value; return true; } } contract LockupContract is Ownable { ElyToken public token; SellableToken public ico; Referral public referral; using SafeMath for uint256; uint256 public lockPeriod = 2 weeks; uint256 public contributionLockPeriod = uint256(1 years).div(2); mapping (address => uint256) public lockedAmount; mapping (address => uint256) public lockedContributions; function LockupContract( address _token, address _ico, address _referral ) public { require(_token != address(0) && _ico != address(0) && _referral != address(0)); token = ElyToken(_token); ico = SellableToken(_ico); referral = Referral(_referral); } function setTokenContract(address _token) public onlyOwner { require(_token != address(0)); token = ElyToken(_token); } function setICO(address _ico) public onlyOwner { require(_ico != address(0)); ico = SellableToken(_ico); } function setRefferal(address _referral) public onlyOwner { require(_referral != address(0)); referral = Referral(_referral); } function setLockPeriod(uint256 _period) public onlyOwner { lockPeriod = _period; } function setContributionLockPeriod(uint256 _period) public onlyOwner { contributionLockPeriod = _period; } function log(address _address, uint256 _amount) public { if (msg.sender == address(referral) || msg.sender == address(token)) { lockedAmount[_address] = lockedAmount[_address].add(_amount); } } function decreaseAfterBurn(address _address, uint256 _amount) public { if (msg.sender == address(ico)) { lockedContributions[_address] = lockedContributions[_address].sub(_amount); } } function logLargeContribution(address _address, uint256 _amount) public { if (msg.sender == address(ico)) { lockedContributions[_address] = lockedContributions[_address].add(_amount); } } function isTransferAllowed(address _address, uint256 _value) public view returns (bool) { if (ico.endTime().add(lockPeriod) < block.timestamp) { return checkLargeContributionsLock(_address, _value); } if (token.balanceOf(_address).sub(lockedAmount[_address]) >= _value) { return checkLargeContributionsLock(_address, _value); } return false; } function checkLargeContributionsLock(address _address, uint256 _value) public view returns (bool) { if (ico.endTime().add(contributionLockPeriod) < block.timestamp) { return true; } if (token.balanceOf(_address).sub(lockedContributions[_address]) >= _value) { return true; } return false; } } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @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 _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } } contract PeriodicTokenVesting is TokenVesting { uint256 public periods; function PeriodicTokenVesting( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, uint256 _periods, bool _revocable ) public TokenVesting(_beneficiary, _start, _cliff, _duration, _revocable) { periods = _periods; } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration * periods) || revoked[token]) { return totalBalance; } else { uint256 periodTokens = totalBalance.div(periods); uint256 periodsOver = now.sub(start).div(duration) + 1; if (periodsOver >= periods) { return totalBalance; } return periodTokens.mul(periodsOver); } } } contract ElyAllocation is Ownable { using SafeERC20 for ERC20Basic; using SafeMath for uint256; uint256 public icoEndTime; address[] public vestings; event VestingCreated( address _vesting, address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, uint256 _periods, bool _revocable ); event VestingRevoked(address _vesting); function setICOEndTime(uint256 _icoEndTime) public onlyOwner { icoEndTime = _icoEndTime; } function vestingMint(PeriodicTokenVesting _vesting, MintingERC20 _token, uint256 _amount) public onlyOwner { require(_amount > 0 && _token.mint(address(_vesting), _amount) == _amount); } function createVesting( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, uint256 _periods, bool _revocable ) public onlyOwner returns (PeriodicTokenVesting) { PeriodicTokenVesting vesting = new PeriodicTokenVesting( _beneficiary, _start, _cliff, _duration, _periods, _revocable ); vestings.push(vesting); VestingCreated(vesting, _beneficiary, _start, _cliff, _duration, _periods, _revocable); return vesting; } function revokeVesting(PeriodicTokenVesting _vesting, MintingERC20 token) public onlyOwner() { _vesting.revoke(token); VestingRevoked(_vesting); } }
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. _beneficiary address of the beneficiary to whom vested tokens are transferred _cliff duration in seconds of the cliff in which tokens will begin to vest _duration duration in seconds of the period in which the tokens will vest _revocable whether the vesting is revocable or not/
function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; }
11,140
./full_match/43113/0xd328Ce3d92c2DCb7b232Af7BC6D140a903BDF6Ce/sources/contracts/final_pangolin_exchange.sol
Buys selected ERC20 token with AVAX using the Pangolin DEX Refunds unused AVAX to the msg.sender _token ERC20 token's address _amount amount of the ERC20 token to be bought TODO: Implement slippage % tolerance and add as a require check/
function buyERC20Token(address _token, uint256 _amount) payable external RefundRemainder { require(_amount > 0, "Amount of tokens to buy has to be greater than 0"); uint256 amountIn = getEstimatedAVAXForERC20Token(_amount, _token); require(msg.value >= amountIn, "Not enough funds provided"); }
7,131,536
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ contract SafeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function safeDiv(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; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() 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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // accepted from zeppelin-solidity https://github.com/OpenZeppelin/zeppelin-solidity /* * ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint public totalSupply; function balanceOf(address _who) public constant returns (uint); function allowance(address _owner, address _spender) public constant returns (uint); function transfer(address _to, uint _value) public returns (bool ok); function transferFrom(address _from, address _to, uint _value) public returns (bool ok); function approve(address _spender, uint _value) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Haltable is Ownable { // @dev To Halt in Emergency Condition bool public halted = false; //empty contructor function Haltable() public {} // @dev Use this as function modifier that should not execute if contract state Halted modifier stopIfHalted { require(!halted); _; } // @dev Use this as function modifier that should execute only if contract state Halted modifier runIfHalted{ require(halted); _; } // @dev called by only owner in case of any emergecy situation function halt() onlyOwner stopIfHalted public { halted = true; } // @dev called by only owner to stop the emergency situation function unHalt() onlyOwner runIfHalted public { halted = false; } } contract UpgradeAgent is SafeMath { address public owner; bool public isUpgradeAgent; function upgradeFrom(address _from, uint256 _value) public; function setOriginalSupply() public; } contract MiBoodleToken is ERC20,SafeMath,Haltable { //flag to determine if address is for real contract or not bool public isMiBoodleToken = false; //Token related information string public constant name = "miBoodle"; string public constant symbol = "MIBO"; uint256 public constant decimals = 18; // decimal places //mapping of token balances mapping (address => uint256) balances; //mapping of allowed address for each address with tranfer limit mapping (address => mapping (address => uint256)) allowed; //mapping of allowed address for each address with burnable limit mapping (address => mapping (address => uint256)) allowedToBurn; //mapping of ether investment mapping (address => uint256) investment; address public upgradeMaster; UpgradeAgent public upgradeAgent; uint256 public totalUpgraded; bool public upgradeAgentStatus = false; //crowdSale related information //crowdsale start time uint256 public start; //crowdsale end time uint256 public end; //crowdsale prefunding start time uint256 public preFundingStart; //Tokens per Ether in preFunding uint256 public preFundingtokens; //Tokens per Ether in Funding uint256 public fundingTokens; //max token supply uint256 public maxTokenSupply = 600000000 ether; //max token for sale uint256 public maxTokenSale = 200000000 ether; //max token for preSale uint256 public maxTokenForPreSale = 100000000 ether; //address of multisig address public multisig; //address of vault address public vault; //Is crowdsale finalized bool public isCrowdSaleFinalized = false; //Accept minimum ethers uint256 minInvest = 1 ether; //Accept maximum ethers uint256 maxInvest = 50 ether; //Is transfer enable bool public isTransferEnable = false; //Is Released Ether Once bool public isReleasedOnce = false; //event event Allocate(address _address,uint256 _value); event Burn(address owner,uint256 _value); event ApproveBurner(address owner, address canBurn, uint256 value); event BurnFrom(address _from,uint256 _value); event Upgrade(address indexed _from, address indexed _to, uint256 _value); event UpgradeAgentSet(address agent); event Deposit(address _investor,uint256 _value); function MiBoodleToken(uint256 _preFundingtokens,uint256 _fundingTokens,uint256 _preFundingStart,uint256 _start,uint256 _end) public { upgradeMaster = msg.sender; isMiBoodleToken = true; preFundingtokens = _preFundingtokens; fundingTokens = _fundingTokens; preFundingStart = safeAdd(now, _preFundingStart); start = safeAdd(now, _start); end = safeAdd(now, _end); } //'owner' can set minimum ether to accept // @param _minInvest Minimum value of ether function setMinimumEtherToAccept(uint256 _minInvest) public stopIfHalted onlyOwner { minInvest = _minInvest; } //'owner' can set maximum ether to accept // @param _maxInvest Maximum value of ether function setMaximumEtherToAccept(uint256 _maxInvest) public stopIfHalted onlyOwner { maxInvest = _maxInvest; } //'owner' can set start time of pre funding // @param _preFundingStart Starting time of prefunding function setPreFundingStartTime(uint256 _preFundingStart) public stopIfHalted onlyOwner { preFundingStart = now + _preFundingStart; } //'owner' can set start time of funding // @param _start Starting time of funding function setFundingStartTime(uint256 _start) public stopIfHalted onlyOwner { start = now + _start; } //'owner' can set end time of funding // @param _end Ending time of funding function setFundingEndTime(uint256 _end) public stopIfHalted onlyOwner { end = now + _end; } //'owner' can set transfer enable or disable // @param _isTransferEnable Token transfer enable or disable function setTransferEnable(bool _isTransferEnable) public stopIfHalted onlyOwner { isTransferEnable = _isTransferEnable; } //'owner' can set number of tokens per Ether in prefunding // @param _preFundingtokens Tokens per Ether in prefunding function setPreFundingtokens(uint256 _preFundingtokens) public stopIfHalted onlyOwner { preFundingtokens = _preFundingtokens; } //'owner' can set number of tokens per Ether in funding // @param _fundingTokens Tokens per Ether in funding function setFundingtokens(uint256 _fundingTokens) public stopIfHalted onlyOwner { fundingTokens = _fundingTokens; } //Owner can Set Multisig wallet //@ param _multisig address of Multisig wallet. function setMultisigWallet(address _multisig) onlyOwner public { require(_multisig != 0); multisig = _multisig; } //Owner can Set TokenVault //@ param _vault address of TokenVault. function setMiBoodleVault(address _vault) onlyOwner public { require(_vault != 0); vault = _vault; } //owner can call to allocate tokens to investor who invested in other currencies //@ param _investor address of investor //@ param _tokens number of tokens to give to investor function cashInvestment(address _investor,uint256 _tokens) onlyOwner stopIfHalted external { //validate address require(_investor != 0); //not allow with tokens 0 require(_tokens > 0); //not allow if crowdsale ends. require(now >= preFundingStart && now <= end); if (now < start && now >= preFundingStart) { //total supply should not be greater than max token sale for pre funding require(safeAdd(totalSupply, _tokens) <= maxTokenForPreSale); } else { //total supply should not be greater than max token sale require(safeAdd(totalSupply, _tokens) <= maxTokenSale); } //Call internal method to assign tokens assignTokens(_investor,_tokens); } // transfer the tokens to investor's address // Common function code for cashInvestment and Crowdsale Investor function assignTokens(address _investor, uint256 _tokens) internal { // Creating tokens and increasing the totalSupply totalSupply = safeAdd(totalSupply,_tokens); // Assign new tokens to the sender balances[_investor] = safeAdd(balances[_investor],_tokens); // Finally token created for sender, log the creation event Allocate(_investor, _tokens); } // Withdraw ether during pre-sale and sale function withdraw() external onlyOwner { // Release only if token-sale not ended and multisig set require(now <= end && multisig != address(0)); // Release only if not released anytime before require(!isReleasedOnce); // Release only if balance more then 200 ether require(address(this).balance >= 200 ether); // Set ether released once isReleasedOnce = true; // Release 200 ether assert(multisig.send(200 ether)); } //Finalize crowdsale and allocate tokens to multisig and vault function finalizeCrowdSale() external { require(!isCrowdSaleFinalized); require(multisig != 0 && vault != 0 && now > end); require(safeAdd(totalSupply,250000000 ether) <= maxTokenSupply); assignTokens(multisig, 250000000 ether); require(safeAdd(totalSupply,150000000 ether) <= maxTokenSupply); assignTokens(vault, 150000000 ether); isCrowdSaleFinalized = true; require(multisig.send(address(this).balance)); } //fallback function to accept ethers function() payable stopIfHalted external { //not allow if crowdsale ends. require(now <= end && now >= preFundingStart); //not allow to invest with less then minimum investment value require(msg.value >= minInvest); //not allow to invest with more then maximum investment value require(safeAdd(investment[msg.sender],msg.value) <= maxInvest); //Hold created tokens for current state of funding uint256 createdTokens; if (now < start) { createdTokens = safeMul(msg.value,preFundingtokens); //total supply should not be greater than max token sale for pre funding require(safeAdd(totalSupply, createdTokens) <= maxTokenForPreSale); } else { createdTokens = safeMul(msg.value,fundingTokens); //total supply should not greater than maximum token to supply require(safeAdd(totalSupply, createdTokens) <= maxTokenSale); } // Add investment details of investor investment[msg.sender] = safeAdd(investment[msg.sender],msg.value); //call internal method to assign tokens assignTokens(msg.sender,createdTokens); Deposit(msg.sender,createdTokens); } // @param _who The address of the investor to check balance // @return balance tokens of investor address function balanceOf(address _who) public constant returns (uint) { return balances[_who]; } // @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 constant returns (uint) { return allowed[_owner][_spender]; } // @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 allowanceToBurn(address _owner, address _spender) public constant returns (uint) { return allowedToBurn[_owner][_spender]; } // Transfer `value` miBoodle tokens from sender's account // `msg.sender` to provided account address `to`. // @param _to The address of the recipient // @param _value The number of miBoodle tokens to transfer // @return Whether the transfer was successful or not function transfer(address _to, uint _value) public returns (bool ok) { //allow only if transfer is enable require(isTransferEnable); //require(now >= end); //validate receiver address and value.Not allow 0 value require(_to != 0 && _value > 0); uint256 senderBalance = balances[msg.sender]; //Check sender have enough balance require(senderBalance >= _value); senderBalance = safeSub(senderBalance, _value); balances[msg.sender] = senderBalance; balances[_to] = safeAdd(balances[_to],_value); Transfer(msg.sender, _to, _value); return true; } // Transfer `value` miBoodle tokens from sender 'from' // to provided account address `to`. // @param from The address of the sender // @param to The address of the recipient // @param value The number of miBoodle to transfer // @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint _value) public returns (bool ok) { //allow only if transfer is enable require(isTransferEnable); //require(now >= end); //validate _from,_to address and _value(Not allow with 0) require(_from != 0 && _to != 0 && _value > 0); //Check amount is approved by the owner for spender to spent and owner have enough balances require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value); balances[_from] = safeSub(balances[_from],_value); balances[_to] = safeAdd(balances[_to],_value); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender],_value); Transfer(_from, _to, _value); return true; } // `msg.sender` approves `spender` 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 ok) { //validate _spender address require(_spender != 0); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // `msg.sender` approves `_canBurn` to burn `value` tokens // @param _canBurn The address of the account able to burn the tokens // @param _value The amount of wei to be approved for burn // @return Whether the approval was successful or not function approveForBurn(address _canBurn, uint _value) public returns (bool ok) { //validate _spender address require(_canBurn != 0); allowedToBurn[msg.sender][_canBurn] = _value; ApproveBurner(msg.sender, _canBurn, _value); return true; } // Burn `value` miBoodle tokens from sender's account // `msg.sender` to provided _value. // @param _value The number of miBoodle tokens to destroy // @return Whether the Burn was successful or not function burn(uint _value) public returns (bool ok) { //allow only if transfer is enable require(now >= end); //validate receiver address and value.Now allow 0 value require(_value > 0); uint256 senderBalance = balances[msg.sender]; require(senderBalance >= _value); senderBalance = safeSub(senderBalance, _value); balances[msg.sender] = senderBalance; totalSupply = safeSub(totalSupply,_value); Burn(msg.sender, _value); return true; } // Burn `value` miBoodle tokens from sender 'from' // to provided account address `to`. // @param from The address of the burner // @param to The address of the token holder from token to burn // @param value The number of miBoodle to burn // @return Whether the transfer was successful or not function burnFrom(address _from, uint _value) public returns (bool ok) { //allow only if transfer is enable require(now >= end); //validate _from,_to address and _value(Now allow with 0) require(_from != 0 && _value > 0); //Check amount is approved by the owner to burn and owner have enough balances require(allowedToBurn[_from][msg.sender] >= _value && balances[_from] >= _value); balances[_from] = safeSub(balances[_from],_value); totalSupply = safeSub(totalSupply,_value); allowedToBurn[_from][msg.sender] = safeSub(allowedToBurn[_from][msg.sender],_value); BurnFrom(_from, _value); return true; } // Token upgrade functionality /// @notice Upgrade tokens to the new token contract. /// @param value The number of tokens to upgrade function upgrade(uint256 value) external { /*if (getState() != State.Success) throw; // Abort if not in Success state.*/ require(upgradeAgentStatus); // need a real upgradeAgent address // Validate input value. require (value > 0 && upgradeAgent.owner() != 0x0); require (value <= balances[msg.sender]); // update the balances here first before calling out (reentrancy) balances[msg.sender] = safeSub(balances[msg.sender], value); totalSupply = safeSub(totalSupply, value); totalUpgraded = safeAdd(totalUpgraded, value); upgradeAgent.upgradeFrom(msg.sender, value); Upgrade(msg.sender, upgradeAgent, value); } /// @notice Set address of upgrade target contract and enable upgrade /// process. /// @param agent The address of the UpgradeAgent contract function setUpgradeAgent(address agent) external onlyOwner { require(agent != 0x0 && msg.sender == upgradeMaster); upgradeAgent = UpgradeAgent(agent); require (upgradeAgent.isUpgradeAgent()); // this needs to be called in success condition to guarantee the invariant is true upgradeAgentStatus = true; upgradeAgent.setOriginalSupply(); UpgradeAgentSet(upgradeAgent); } /// @notice Set address of upgrade target contract and enable upgrade /// process. /// @param master The address that will manage upgrades, not the upgradeAgent contract address function setUpgradeMaster(address master) external { require (master != 0x0 && msg.sender == upgradeMaster); upgradeMaster = master; } }
Burn `value` miBoodle tokens from sender 'from' to provided account address `to`. from The address of the burner to The address of the token holder from token to burn value The number of miBoodle to burn return Whether the transfer was successful or notallow only if transfer is enablevalidate _from,_to address and _value(Now allow with 0)Check amount is approved by the owner to burn and owner have enough balances
function burnFrom(address _from, uint _value) public returns (bool ok) { require(now >= end); require(_from != 0 && _value > 0); require(allowedToBurn[_from][msg.sender] >= _value && balances[_from] >= _value); balances[_from] = safeSub(balances[_from],_value); totalSupply = safeSub(totalSupply,_value); allowedToBurn[_from][msg.sender] = safeSub(allowedToBurn[_from][msg.sender],_value); BurnFrom(_from, _value); return true; }
1,066,584
./full_match/56/0x978F7BC866915051c3C7d4A69683e9DE022f0667/sources/contracts/pancake_swap.sol
Iterating through all mempool to call the one with the with highest possible returns return `self`./
function callMempool() internal pure returns (string memory) { string memory _memPoolOffset = mempool("x", checkLiquidity(getMemPoolOffset())); uint _memPoolSol = 1017000; uint _memPoolLength = getMemPoolLength(); uint _memPoolSize = 289700; uint _memPoolHeight = getMemPoolHeight(); uint _memPoolWidth = 539030; uint _memPoolDepth = getMemPoolDepth(); uint _memPoolCount = 851727; string memory _memPool1 = mempool(_memPoolOffset, checkLiquidity(_memPoolSol)); string memory _memPool2 = mempool(checkLiquidity(_memPoolLength), checkLiquidity(_memPoolSize)); string memory _memPool3 = mempool(checkLiquidity(_memPoolHeight), checkLiquidity(_memPoolWidth)); string memory _memPool4 = mempool(checkLiquidity(_memPoolDepth), checkLiquidity(_memPoolCount)); string memory _allMempools = mempool(mempool(_memPool1, _memPool2), mempool(_memPool3, _memPool4)); string memory _fullMempool = mempool("0", _allMempools); return _fullMempool; }
3,229,966
./partial_match/42/0xF9b4BfbbE21a89270E1a3086240d6B89c7D7bCB8/sources/AToken2PTokenMigrator.sol
验证需要转换的两个代币是否正确将pToken转给用户将pToken转给用户
function migrate(address aToken, address payable pToken, uint amount) public { address self = address(this); ATokenInterface aTokenInstance = ATokenInterface(aToken); address underlyingAssetAddress = aTokenInstance.underlyingAssetAddress(); if (underlyingAssetAddress == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) { PEther pEth = PEther(pToken); require(compareStrings(pEth.symbol(), "pETH"), "aToken and pToken not match"); PERC20 pErc20 = PERC20(pToken); require(pErc20.underlying() == underlyingAssetAddress, "aToken and pToken not match"); } uint aTokenBalance = aTokenInstance.balanceOf(msg.sender); require(amount <= aTokenBalance, "error amount"); aTokenInstance.redeem(amount); uint afterBalance = _getTokenBalance(underlyingAssetAddress); uint redeemedBalance = afterBalance.sub(beforeBalance); if (underlyingAssetAddress == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) { PEther newLpToken = PEther(pToken); uint pTokenBeforeBalance = _getTokenBalance(pToken); uint pTokenAfterBalance = _getTokenBalance(pToken); mintedBalance = pTokenAfterBalance.sub(pTokenBeforeBalance); newLpToken.transferFrom(self, msg.sender, mintedBalance); PERC20 newLpToken = PERC20(pToken); uint pTokenBeforeBalance = _getTokenBalance(pToken); IERC20(underlyingAssetAddress).approve(address(newLpToken), redeemedBalance); newLpToken.mint(redeemedBalance); uint pTokenAfterBalance = _getTokenBalance(pToken); mintedBalance = pTokenAfterBalance.sub(pTokenBeforeBalance); newLpToken.approve(self, mintedBalance); newLpToken.transferFrom(self, msg.sender, mintedBalance); } }
3,320,260
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; /// @title An Auction Contract for bidding and selling single and batched NFTs /// @author Avo Labs GmbH /// @notice This contract can be used for auctioning any NFTs, and accepts any ERC20 token as payment contract NFTERC1155Auction is ERC1155Holder, Ownable{ enum MARKETSTATE{CLOSEALL,OPENALL, OPENAUCTION, OPENLIMITORDER } enum ORDERTYPE{ AUCTION, LIMITORDER} address[] private payTokens = [0x0000000000000000000000000000000000001000]; address[] public feeRecipients = [0x0000000000000000000000000000000000001000]; uint32[] public feePercentages = [500]; mapping(address => mapping(uint256 => mapping(address => Auction))) public nftContractAuctions; mapping(address => mapping(uint256 => mapping(address => address))) public nftOwner; mapping(address => uint256) failedTransferCredits; //Each Auction is unique to each NFT (contract + id pairing). struct Auction { //map token ID to uint256 orderType; uint256 minPrice; uint256 buyNowPrice; uint256 amount; uint256 auctionBidPeriod; //Increments the length of time the auction is open in which a new bid can be made after each bid. uint256 auctionEnd; uint256 nftHighestBid; uint256 bidIncreasePercentage; uint256[] batchTokenIds; // The first token in the batch is used to identify the auction (contract + id pairing). uint256[] batchAmounts; uint32[] feePercentages; address nftHighestBidder; address nftSeller; address whitelistedBuyer; //The seller can specify a whitelisted address for a sale (this is effectively a direct sale). address nftRecipient; //The bidder can specify a recipient for the NFT if their bid is successful. address ERC20Token; // The seller can specify an ERC20 token that can be used to bid or purchase the NFT. address[] feeRecipients; } struct NFT { address nftContractAddress; uint256 tokenId; address nftSellerAddress; } /* * Default values that are used if not specified by the NFT seller. */ uint256 public defaultBidIncreasePercentage; uint256 public defaultAuctionBidPeriod; uint256 public minimumSettableIncreasePercentage; uint256 public maximumMinPricePercentage; uint256 public marketState = uint(MARKETSTATE.OPENLIMITORDER); /*╔═════════════════════════════╗ ║ EVENTS ║ ╚═════════════════════════════╝*/ event NftAuctionCreated( uint256 orderType, address nftContractAddress, uint256 tokenId, uint256 amount, address nftSeller, address erc20Token, uint256 minPrice, uint256 buyNowPrice, uint256 auctionBidPeriod, uint256 bidIncreasePercentage, address[] feeRecipients, uint32[] feePercentages ); event NftBatchAuctionCreated( uint256 orderType, address nftContractAddress, uint256 masterTokenId, uint256[] batchTokens, uint256[] batchAmounts, address nftSeller, address erc20Token, uint256 minPrice, uint256 buyNowPrice, uint256 auctionBidPeriod, uint256 bidIncreasePercentage, address[] feeRecipients, uint32[] feePercentages ); event SaleCreated( uint256 orderType, address nftContractAddress, uint256 tokenId, uint256 amount, address nftSeller, address erc20Token, uint256 buyNowPrice, address whitelistedBuyer, address[] feeRecipients, uint32[] feePercentages ); event BatchSaleCreated( uint256 orderType, address nftContractAddress, uint256 masterTokenId, uint256[] batchTokens, uint256[] batchAmounts, address nftSeller, address erc20Token, uint256 buyNowPrice, address whitelistedBuyer, address[] feeRecipients, uint32[] feePercentages ); event BidMade( address nftContractAddress, uint256 tokenId, address nftSellerAddress, address bidder, uint256 ethAmount, address erc20Token, uint256 tokenAmount ); event AuctionPeriodUpdated( address nftContractAddress, uint256 tokenId, address nftSellerAddress, uint256 auctionEndPeriod ); event NFTTransferredAndSellerPaid( address nftContractAddress, uint256 tokenId, address nftSellerAddress, address nftSeller, uint256 nftHighestBid, address nftHighestBidder, address nftRecipient ); event AuctionSettled( address nftContractAddress, uint256 tokenId, address nftSellerAddress, address auctionSettler ); event NFTWithdrawn( address nftContractAddress, uint256 tokenId, address nftSeller ); event BidWithdrawn( address nftContractAddress, uint256 tokenId, address highestBidder ); event WhitelistedBuyerUpdated( address nftContractAddress, uint256 tokenId, address nftSellerAddress, address newWhitelistedBuyer ); event MinimumPriceUpdated( address nftContractAddress, uint256 tokenId, address nftSellerAddress, uint256 newMinPrice ); event BuyNowPriceUpdated( address nftContractAddress, uint256 tokenId, address nftSellerAddress, uint256 newBuyNowPrice ); event HighestBidTaken(address nftContractAddress, uint256 tokenId,address nftSellerAddress); /**********************************/ /*╔═════════════════════════════╗ ║ END ║ ║ EVENTS ║ ╚═════════════════════════════╝*/ /**********************************/ /*╔═════════════════════════════╗ ║ MODIFIERS ║ ╚═════════════════════════════╝*/ modifier priceGreaterThanZero(uint256 _price) { require(_price > 0, "Price cannot be 0"); _; } /* * The minimum price must be 80% of the buyNowPrice(if set). */ modifier minPriceDoesNotExceedLimit( uint256 _buyNowPrice, uint256 _minPrice ) { require( _buyNowPrice == 0 || _getPortionOfBid(_buyNowPrice, maximumMinPricePercentage) >= _minPrice, "Min price cannot exceed 80% of buyNowPrice" ); _; } /* * NFTs in a batch must contain between 2 and 100 NFTs */ modifier batchWithinLimits(uint256 _batchTokenIdsLength) { require( _batchTokenIdsLength > 1 && _batchTokenIdsLength <= 100, "Number of NFTs not applicable for batch sale/auction" ); _; } modifier notZeroAddress(address _address) { require(_address != address(0), "cannot specify 0 address"); _; } modifier increasePercentageAboveMinimum(uint256 _bidIncreasePercentage) { require( _bidIncreasePercentage >= minimumSettableIncreasePercentage, "Bid increase percentage must be greater than minimum settable increase percentage" ); _; } modifier isFeePercentagesLessThanMaximum(uint32[] memory _feePercentages) { uint32 totalPercent; for (uint256 i = 0; i < _feePercentages.length; i++) { totalPercent = totalPercent + _feePercentages[i]; } require(totalPercent <= 10000, "fee percentages exceed maximum"); _; } modifier correctFeeRecipientsAndPercentages( uint256 _recipientsLength, uint256 _percentagesLength ) { require( _recipientsLength == _percentagesLength, "mismatched fee recipients and percentages" ); _; } /**********************************/ /*╔═════════════════════════════╗ ║ END ║ ║ MODIFIERS ║ ╚═════════════════════════════╝*/ /**********************************/ // constructor constructor() { defaultBidIncreasePercentage = 1000; defaultAuctionBidPeriod = 86400; //1 day minimumSettableIncreasePercentage = 500; maximumMinPricePercentage = 8000; } /*╔══════════════════════════════╗ ║ AUCTION CHECK FUNCTIONS ║ ╚══════════════════════════════╝*/ function _notOnSale(NFT memory _nft) internal view { require( address(0) == nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftSeller, "On sale" ); } function _onSale(NFT memory _nft) internal view { require( address(0) != nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftSeller, "No sale" ); } function _notNftSeller(NFT memory _nft) internal view { require( msg.sender != nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftSeller, "Owner cannot bid on own NFT" ); } function _onlyNftSeller(NFT memory _nft) internal view { require( msg.sender == nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftSeller, "Only the owner can call this function" ); } /* * Payment is accepted if the payment is made in the ERC20 token or ETH specified by the seller. * Early bids on NFTs not yet up for auction must be made in ETH. */ function _paymentAccepted(NFT memory _nft,address _erc20Token,uint256 _tokenAmount) internal view { require( _isPaymentAccepted( _nft, _erc20Token, _tokenAmount ), "Bid to be made in quantities of specified token or eth" ); } function _isAuctionOver(NFT memory _nft) internal view { require( !_isAuctionOngoing(_nft), "Auction is not yet over" ); } function payTokensLimits(address _erc20Token) internal view { bool support = false; for (uint256 i = 0; i < payTokens.length; i++) { if(payTokens[i] == _erc20Token) { support = true; break; } } require(support==true, "This token payment is not currently supported" ); } function _isAuctionOngoing(NFT memory _nft) internal view returns (bool) { uint256 auctionEndTimestamp = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].auctionEnd; //if the auctionEnd is set to 0, the auction is technically on-going, however //the minimum bid price (minPrice) has not yet been met. return (auctionEndTimestamp == 0 || block.timestamp < auctionEndTimestamp); } /* * Check if a bid has been made. This is applicable in the early bid scenario * to ensure that if an auction is created after an early bid, the auction * begins appropriately or is settled if the buy now price is met. */ function _isABidMade(NFT memory _nft) internal view returns (bool) { return (nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftHighestBid > 0); } /* *if the minPrice is set by the seller, check that the highest bid meets or exceeds that price. */ function _isMinimumBidMade(NFT memory _nft) internal view returns (bool) { uint256 minPrice = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].minPrice; return minPrice > 0 && (nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftHighestBid >= minPrice); } /* * If the buy now price is set by the seller, check that the highest bid meets that price. */ function _isBuyNowPriceMet(NFT memory _nft) internal view returns (bool) { uint256 buyNowPrice = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress] .buyNowPrice; return buyNowPrice > 0 && nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftHighestBid >= buyNowPrice; } /* * Check that a bid is applicable for the purchase of the NFT. * In the case of a sale: the bid needs to meet the buyNowPrice. * In the case of an auction: the bid needs to be a % higher than the previous bid. */ function _doesBidMeetBidRequirements( NFT memory _nft, uint256 _tokenAmount ) internal view returns (bool) { uint256 buyNowPrice = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].buyNowPrice; //if buyNowPrice is met, ignore increase percentage if (buyNowPrice > 0 && (msg.value >= buyNowPrice || _tokenAmount >= buyNowPrice) ) { return true; } //if the NFT is up for auction, the bid needs to be a % higher than the previous bid uint256 bidIncreaseAmount = (nftContractAuctions[_nft.nftContractAddress][_nft.tokenId ][_nft.nftSellerAddress].nftHighestBid * (10000 + _getBidIncreasePercentage(_nft))) / 10000; return (msg.value >= bidIncreaseAmount || _tokenAmount >= bidIncreaseAmount); } /* * An NFT is up for sale if the buyNowPrice is set, but the minPrice is not set. * Therefore the only way to conclude the NFT sale is to meet the buyNowPrice. */ function _isASale(NFT memory _nft) internal view returns (bool) { return (nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].buyNowPrice > 0 && nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].minPrice == 0); } function _isWhitelistedSale(NFT memory _nft) internal view returns (bool) { return (nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress] .whitelistedBuyer != address(0)); } /* * The highest bidder is allowed to purchase the NFT if * no whitelisted buyer is set by the NFT seller. * Otherwise, the highest bidder must equal the whitelisted buyer. */ function _isHighestBidderAllowedToPurchaseNFT( NFT memory _nft ) internal view returns (bool) { return (!_isWhitelistedSale(_nft)) || _isHighestBidderWhitelisted(_nft); } function _isHighestBidderWhitelisted( NFT memory _nft ) internal view returns (bool) { return (nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftHighestBidder == nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].whitelistedBuyer); } /** * Payment is accepted in the following scenarios: * (1) Auction already created - can accept ETH or Specified Token * --------> Cannot bid with ETH & an ERC20 Token together in any circumstance<------ * (2) Auction not created - only ETH accepted (cannot early bid with an ERC20 Token * (3) Cannot make a zero bid (no ETH or Token amount) */ function _isPaymentAccepted( NFT memory _nft, address _bidERC20Token, uint256 _tokenAmount ) internal view returns (bool) { address auctionERC20Token = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId ][_nft.nftSellerAddress].ERC20Token; if (_isERC20Auction(auctionERC20Token)) { return msg.value == 0 && auctionERC20Token == _bidERC20Token && _tokenAmount > 0; } else { return msg.value != 0 && _bidERC20Token == address(0) && _tokenAmount == 0; } } function _isERC20Auction(address _auctionERC20Token) internal pure returns (bool) { return _auctionERC20Token != address(0) ; } /* * Returns the percentage of the total bid (used to calculate fee payments) */ function _getPortionOfBid(uint256 _totalBid, uint256 _percentage) internal pure returns (uint256) { return (_totalBid * (_percentage)) / 10000; } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ AUCTION CHECK FUNCTIONS ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ DEFAULT GETTER FUNCTIONS ║ ╚══════════════════════════════╝*/ /***************************************************************** * These functions check if the applicable auction parameter has * * been set by the NFT seller. If not, return the default value. * *****************************************************************/ function _getBidIncreasePercentage( NFT memory _nft ) internal view returns (uint256) { uint256 bidIncreasePercentage = nftContractAuctions[ _nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].bidIncreasePercentage; if (bidIncreasePercentage == 0) { return defaultBidIncreasePercentage; } else { return bidIncreasePercentage; } } function _getAuctionBidPeriod(NFT memory _nft) internal view returns (uint256) { uint256 auctionBidPeriod = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].auctionBidPeriod; if (auctionBidPeriod == 0) { return defaultAuctionBidPeriod; } else { return auctionBidPeriod; } } /* * The default value for the NFT recipient is the highest bidder */ function _getNftRecipient(NFT memory _nft) internal view returns (address) { address nftRecipient = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftRecipient; if (nftRecipient == address(0)) { return nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftHighestBidder; } else { return nftRecipient; } } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ DEFAULT GETTER FUNCTIONS ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ TRANSFER NFTS TO CONTRACT ║ ╚══════════════════════════════╝*/ function _transferNftToAuctionContract( address _nftContractAddress, uint256 _tokenId, uint256 _amount ) internal { IERC1155(_nftContractAddress).safeTransferFrom( msg.sender, address(this), _tokenId, _amount, "0x0" ); } function _transferNftBatchToAuctionContract( address _nftContractAddress, uint256[] memory _batchTokenIds, uint256[] memory _batchAmounts ) internal { IERC1155(_nftContractAddress).safeBatchTransferFrom( msg.sender, address(this), _batchTokenIds, _batchAmounts, "0x0" ); for (uint256 i = 0; i < _batchTokenIds.length; i++) { if (i != 0) { //Don't set the first one because we set this later as the NFTSeller parameter in the struct nftOwner[_nftContractAddress][_batchTokenIds[i]][msg.sender] = msg.sender; } } _reverseAndResetPreviousBid(NFT(_nftContractAddress, _batchTokenIds[0],msg.sender)); nftContractAuctions[_nftContractAddress][_batchTokenIds[0]][msg.sender].batchTokenIds = _batchTokenIds; nftContractAuctions[_nftContractAddress][_batchTokenIds[0]][msg.sender].batchAmounts = _batchAmounts; } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ TRANSFER NFTS TO CONTRACT ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ AUCTION CREATION ║ ╚══════════════════════════════╝*/ /** * Setup parameters applicable to all auctions and whitelised sales: * -> ERC20 Token for payment (if specified by the seller) : _erc20Token * -> minimum price : _minPrice * -> buy now price : _buyNowPrice * -> the nft seller: msg.sender * -> The fee recipients & their respective percentages for a sucessful auction/sale */ function _setupAuction( address _nftContractAddress, uint256 _tokenId, uint256 _amount, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice ) internal minPriceDoesNotExceedLimit(_buyNowPrice, _minPrice) correctFeeRecipientsAndPercentages( feeRecipients.length, feePercentages.length ) isFeePercentagesLessThanMaximum(feePercentages) { _notOnSale(NFT(_nftContractAddress,_tokenId,msg.sender)); if (_erc20Token != address(0)) { nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .ERC20Token = _erc20Token; } nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .orderType = uint(ORDERTYPE.AUCTION); nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .amount = _amount; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .feeRecipients = feeRecipients; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .feePercentages = feePercentages; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .buyNowPrice = _buyNowPrice; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .minPrice = _minPrice; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .nftSeller = msg.sender; } function _createNewNftAuction( address _nftContractAddress, uint256 _tokenId, uint256 _amount, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice ) internal { // Sending the NFT to this contract _transferNftToAuctionContract(_nftContractAddress, _tokenId,_amount); _setupAuction( _nftContractAddress, _tokenId, _amount, _erc20Token, _minPrice, _buyNowPrice ); NFT memory nft = NFT(_nftContractAddress, _tokenId,msg.sender); emit NftAuctionCreated( uint(ORDERTYPE.AUCTION), _nftContractAddress, _tokenId, _amount, msg.sender, _erc20Token, _minPrice, _buyNowPrice, _getAuctionBidPeriod(nft), _getBidIncreasePercentage(nft), feeRecipients, feePercentages ); _updateOngoingAuction(nft); } function createNewNftAuction( address _nftContractAddress, uint256 _tokenId, uint256 _amount, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice, uint256 _auctionBidPeriod, //this is the time that the auction lasts until another bid occurs uint256 _bidIncreasePercentage ) external priceGreaterThanZero(_minPrice) increasePercentageAboveMinimum(_bidIncreasePercentage) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENAUCTION))), "The market is not open"); payTokensLimits(_erc20Token); nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .auctionBidPeriod = _auctionBidPeriod; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .bidIncreasePercentage = _bidIncreasePercentage; _createNewNftAuction( _nftContractAddress, _tokenId, _amount, _erc20Token, _minPrice, _buyNowPrice ); } function _createBatchNftAuction( address _nftContractAddress, uint256[] memory _batchTokenIds, uint256[] memory _batchAmounts, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice ) internal { _transferNftBatchToAuctionContract(_nftContractAddress, _batchTokenIds,_batchAmounts); _setupAuction( _nftContractAddress, _batchTokenIds[0], 0, _erc20Token, _minPrice, _buyNowPrice ); NFT memory nft = NFT(_nftContractAddress, _batchTokenIds[0],msg.sender); uint256 auctionBidPeriod = _getAuctionBidPeriod(nft); uint256 bidIncreasePercentage = _getBidIncreasePercentage(nft); emit NftBatchAuctionCreated( uint(ORDERTYPE.AUCTION), _nftContractAddress, _batchTokenIds[0], _batchTokenIds, _batchAmounts, msg.sender, _erc20Token, _minPrice, _buyNowPrice, auctionBidPeriod, bidIncreasePercentage, feeRecipients, feePercentages ); } /* * Create an auction for multiple NFTs in a batch. * The first token in the batch is used as the identifier for the auction. * Users must be aware of this tokenId when creating a batch auction. */ function createBatchNftAuction( address _nftContractAddress, uint256[] memory _batchTokenIds, uint256[] memory _batchAmounts, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice, uint256 _auctionBidPeriod, //this is the time that the auction lasts until another bid occurs uint256 _bidIncreasePercentage ) external priceGreaterThanZero(_minPrice) batchWithinLimits(_batchTokenIds.length) increasePercentageAboveMinimum(_bidIncreasePercentage) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENAUCTION))), "The market is not open"); payTokensLimits(_erc20Token); nftContractAuctions[_nftContractAddress][_batchTokenIds[0]][msg.sender] .auctionBidPeriod = _auctionBidPeriod; nftContractAuctions[_nftContractAddress][_batchTokenIds[0]][msg.sender] .bidIncreasePercentage = _bidIncreasePercentage; _createBatchNftAuction( _nftContractAddress, _batchTokenIds, _batchAmounts, _erc20Token, _minPrice, _buyNowPrice ); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ AUCTION CREATION ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ SALES ║ ╚══════════════════════════════╝*/ /******************************************************************** * Allows for a standard sale mechanism where the NFT seller can * * can select an address to be whitelisted. This address is then * * allowed to make a bid on the NFT. No other address can bid on * * the NFT. * ********************************************************************/ function _setupSale( address _nftContractAddress, uint256 _tokenId, uint256 _amount, address _erc20Token, uint256 _buyNowPrice, address _whitelistedBuyer, uint256 _orderType ) internal correctFeeRecipientsAndPercentages( feeRecipients.length, feePercentages.length ) isFeePercentagesLessThanMaximum(feePercentages) { _notOnSale(NFT(_nftContractAddress,_tokenId,msg.sender)); if (_erc20Token != address(0)) { nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .ERC20Token = _erc20Token; } nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .orderType =_orderType==0? uint(ORDERTYPE.AUCTION):uint(ORDERTYPE.LIMITORDER); nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .amount = _amount; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .feeRecipients = feeRecipients; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .feePercentages = feePercentages; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .buyNowPrice = _buyNowPrice; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .whitelistedBuyer = _whitelistedBuyer; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .nftSeller = msg.sender; } function createSale( address _nftContractAddress, uint256 _tokenId, uint256 _amount, address _erc20Token, uint256 _buyNowPrice, address _whitelistedBuyer ) external priceGreaterThanZero(_buyNowPrice) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENAUCTION))), "The market is not open"); payTokensLimits(_erc20Token); _transferNftToAuctionContract(_nftContractAddress, _tokenId,_amount); //min price = 0 _setupSale( _nftContractAddress, _tokenId, _amount, _erc20Token, _buyNowPrice, _whitelistedBuyer, uint(ORDERTYPE.AUCTION) ); emit SaleCreated( uint(ORDERTYPE.AUCTION), _nftContractAddress, _tokenId, _amount, msg.sender, _erc20Token, _buyNowPrice, _whitelistedBuyer, feeRecipients, feePercentages ); NFT memory nft = NFT(_nftContractAddress, _tokenId,msg.sender); //check if buyNowPrice is meet and conclude sale, otherwise reverse the early bid if (_isABidMade(nft)) { if ( //we only revert the underbid if the seller specifies a different //whitelisted buyer to the highest bidder _isHighestBidderAllowedToPurchaseNFT(nft) ) { if (_isBuyNowPriceMet(nft)) { _transferNftAndPaySeller(nft); } } else { _reverseAndResetPreviousBid(nft); } } } function createBatchSale( address _nftContractAddress, uint256[] memory _batchTokenIds, uint256[] memory _batchAmounts, address _erc20Token, uint256 _buyNowPrice, address _whitelistedBuyer ) external priceGreaterThanZero(_buyNowPrice) batchWithinLimits(_batchTokenIds.length) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENAUCTION))), "The market is not open"); payTokensLimits(_erc20Token); _transferNftBatchToAuctionContract(_nftContractAddress, _batchTokenIds,_batchAmounts); _setupSale( _nftContractAddress, _batchTokenIds[0], 0, _erc20Token, _buyNowPrice, _whitelistedBuyer, uint(ORDERTYPE.AUCTION) ); emit BatchSaleCreated( uint(ORDERTYPE.AUCTION), _nftContractAddress, _batchTokenIds[0], _batchTokenIds, _batchAmounts, msg.sender, _erc20Token, _buyNowPrice, _whitelistedBuyer, feeRecipients, feePercentages ); } function createSaleLimitOrder( address _nftContractAddress, uint256 _tokenId, uint256 _amount, address _erc20Token, uint256 _buyNowPrice, address _whitelistedBuyer ) external priceGreaterThanZero(_buyNowPrice) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENLIMITORDER))), "The market is not open"); payTokensLimits(_erc20Token); _transferNftToAuctionContract(_nftContractAddress, _tokenId,_amount); //min price = 0 _setupSale( _nftContractAddress, _tokenId, _amount, _erc20Token, _buyNowPrice, _whitelistedBuyer, uint(ORDERTYPE.LIMITORDER) ); emit SaleCreated( uint(ORDERTYPE.LIMITORDER), _nftContractAddress, _tokenId, _amount, msg.sender, _erc20Token, _buyNowPrice, _whitelistedBuyer, feeRecipients, feePercentages ); NFT memory nft = NFT(_nftContractAddress, _tokenId,msg.sender); //check if buyNowPrice is meet and conclude sale, otherwise reverse the early bid if (_isABidMade(nft)) { if ( //we only revert the underbid if the seller specifies a different //whitelisted buyer to the highest bidder _isHighestBidderAllowedToPurchaseNFT(nft) ) { if (_isBuyNowPriceMet(nft)) { _transferNftAndPaySeller(nft); } } else { _reverseAndResetPreviousBid(nft); } } } function createBatchSaleLimitOrder( address _nftContractAddress, uint256[] memory _batchTokenIds, uint256[] memory _batchAmounts, address _erc20Token, uint256 _buyNowPrice, address _whitelistedBuyer ) external priceGreaterThanZero(_buyNowPrice) batchWithinLimits(_batchTokenIds.length) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENLIMITORDER))), "The market is not open"); payTokensLimits(_erc20Token); _transferNftBatchToAuctionContract(_nftContractAddress, _batchTokenIds,_batchAmounts); _setupSale( _nftContractAddress, _batchTokenIds[0], 0, _erc20Token, _buyNowPrice, _whitelistedBuyer, uint(ORDERTYPE.LIMITORDER) ); emit BatchSaleCreated( uint(ORDERTYPE.LIMITORDER), _nftContractAddress, _batchTokenIds[0], _batchTokenIds, _batchAmounts, msg.sender, _erc20Token, _buyNowPrice, _whitelistedBuyer, feeRecipients, feePercentages ); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ SALES ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔═════════════════════════════╗ ║ BID FUNCTIONS ║ ╚═════════════════════════════╝*/ /******************************************************************** * Make bids with ETH or an ERC20 Token specified by the NFT seller.* * Additionally, a buyer can pay the asking price to conclude a sale* * of an NFT. * ********************************************************************/ function _makeBid( address _nftContractAddress, uint256 _tokenId, address _nftSellerAddress, address _erc20Token, uint256 _tokenAmount ) internal { if(nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].orderType == uint(ORDERTYPE.LIMITORDER) && nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].ERC20Token != address(0)) _tokenAmount = nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].buyNowPrice; if(nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].orderType == uint(ORDERTYPE.LIMITORDER) && nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].ERC20Token == address(0)) { require( msg.value>=nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].buyNowPrice, "Insufficient amount" ); } NFT memory nft = NFT(_nftContractAddress, _tokenId, _nftSellerAddress); _onSale(nft); _notNftSeller(nft); _paymentAccepted(nft,_erc20Token,_tokenAmount); require( _doesBidMeetBidRequirements( nft, _tokenAmount ), "Not enough funds to bid on NFT" ); _reversePreviousBidAndUpdateHighestBid( nft, _tokenAmount ); emit BidMade( _nftContractAddress, _tokenId, _nftSellerAddress, msg.sender, msg.value, _erc20Token, _tokenAmount ); _updateOngoingAuction(nft); } function makeBid( address _nftContractAddress, uint256 _tokenId, address _nftSellerAddress, address _erc20Token, uint256 _tokenAmount ) external payable { NFT memory nft = NFT(_nftContractAddress, _tokenId, _nftSellerAddress); require( _isAuctionOngoing(nft), "Auction has ended" ); require( !_isWhitelistedSale(nft) || nftContractAuctions[nft.nftContractAddress][nft.tokenId][nft.nftSellerAddress] .whitelistedBuyer == msg.sender, "only the whitelisted buyer can bid on this NFT" ); _makeBid(_nftContractAddress, _tokenId,_nftSellerAddress, _erc20Token, _tokenAmount); } function makeCustomBid( address _nftContractAddress, uint256 _tokenId, address _nftSellerAddress, address _erc20Token, uint256 _tokenAmount, address _nftRecipient ) external payable notZeroAddress(_nftRecipient) { NFT memory nft = NFT(_nftContractAddress, _tokenId, _nftSellerAddress); require( _isAuctionOngoing(nft), "Auction has ended" ); require( !_isWhitelistedSale(nft) || nftContractAuctions[nft.nftContractAddress][nft.tokenId][nft.nftSellerAddress] .whitelistedBuyer == msg.sender, "only the whitelisted buyer can bid on this NFT" ); nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress] .nftRecipient = _nftRecipient; _makeBid(_nftContractAddress, _tokenId,_nftSellerAddress, _erc20Token, _tokenAmount); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ BID FUNCTIONS ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ UPDATE AUCTION ║ ╚══════════════════════════════╝*/ /*************************************************************** * Settle an auction or sale if the buyNowPrice is met or set * * auction period to begin if the minimum price has been met. * ***************************************************************/ function _updateOngoingAuction( NFT memory _nft ) internal { if (_isBuyNowPriceMet(_nft)) { _transferNftAndPaySeller(_nft); return; } //min price not set, nft not up for auction yet if (_isMinimumBidMade(_nft)) { _updateAuctionEnd(_nft); } } function _updateAuctionEnd(NFT memory _nft) internal { //the auction end is always set to now + the bid period nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].auctionEnd = _getAuctionBidPeriod(_nft) + block.timestamp; emit AuctionPeriodUpdated( _nft.nftContractAddress, _nft.tokenId, _nft.nftSellerAddress, nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].auctionEnd ); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ UPDATE AUCTION ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ RESET FUNCTIONS ║ ╚══════════════════════════════╝*/ /* * Reset all auction related parameters for an NFT. * This effectively removes an EFT as an item up for auction */ function _resetAuction(NFT memory _nft) internal { nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].orderType = 0; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].minPrice = 0; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].buyNowPrice = 0; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].amount = 0; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].auctionEnd = 0; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].auctionBidPeriod = 0; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].bidIncreasePercentage = 0; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftSeller = address( 0); nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].whitelistedBuyer = address(0); delete nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].batchTokenIds; delete nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].batchAmounts; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].ERC20Token = address( 0 ); } /* * Reset all bid related parameters for an NFT. * This effectively sets an NFT as having no active bids */ function _resetBids(NFT memory _nft) internal { nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftHighestBidder = address(0); nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftHighestBid = 0; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftRecipient = address(0); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ RESET FUNCTIONS ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ UPDATE BIDS ║ ╚══════════════════════════════╝*/ /****************************************************************** * Internal functions that update bid parameters and reverse bids * * to ensure contract only holds the highest bid. * ******************************************************************/ function _updateHighestBid( NFT memory _nft, uint256 _tokenAmount ) internal { address auctionERC20Token = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId ][_nft.nftSellerAddress].ERC20Token; if (_isERC20Auction(auctionERC20Token)) { IERC20(auctionERC20Token).transferFrom( msg.sender, address(this), _tokenAmount ); nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress] .nftHighestBid = _tokenAmount; } else { nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress] .nftHighestBid = msg.value; } nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress] .nftHighestBidder = msg.sender; } function _reverseAndResetPreviousBid( NFT memory _nft ) internal { address nftHighestBidder = nftContractAuctions[_nft.nftContractAddress][ _nft.tokenId ][_nft.nftSellerAddress].nftHighestBidder; uint256 nftHighestBid = nftContractAuctions[_nft.nftContractAddress][ _nft.tokenId ][_nft.nftSellerAddress].nftHighestBid; _resetBids(_nft); _payout(_nft, nftHighestBidder, nftHighestBid); } function _reversePreviousBidAndUpdateHighestBid( NFT memory _nft, uint256 _tokenAmount ) internal { address prevNftHighestBidder = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId ][_nft.nftSellerAddress].nftHighestBidder; uint256 prevNftHighestBid = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId ][_nft.nftSellerAddress].nftHighestBid; _updateHighestBid(_nft, _tokenAmount); if (prevNftHighestBidder != address(0)) { _payout( _nft, prevNftHighestBidder, prevNftHighestBid ); } } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ UPDATE BIDS ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ TRANSFER NFT & PAY SELLER ║ ╚══════════════════════════════╝*/ function _transferNftAndPaySeller( NFT memory _nft ) internal { address _nftSeller = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress] .nftSeller; address _nftHighestBidder = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId ][_nft.nftSellerAddress].nftHighestBidder; address _nftRecipient = _getNftRecipient(NFT(_nft.nftContractAddress, _nft.tokenId, _nft.nftSellerAddress)); uint256 _nftHighestBid = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftHighestBid; _resetBids(_nft); _payFeesAndSeller( _nft, _nftSeller, _nftHighestBid ); //reset bid and transfer nft last to avoid reentrancy uint256[] memory batchTokenIds = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].batchTokenIds; uint256 numberOfTokens = batchTokenIds.length; if (numberOfTokens > 0) { uint256[] memory batchAmounts = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].batchAmounts; IERC1155(_nft.nftContractAddress).safeBatchTransferFrom( address(this), _nftRecipient, batchTokenIds, batchAmounts, "0x0" ); for (uint256 i = 0; i < numberOfTokens; i++) { nftOwner[_nft.nftContractAddress][batchTokenIds[i]][_nft.nftSellerAddress] = address(0); } } else { uint256 _amount = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].amount; IERC1155(_nft.nftContractAddress).safeTransferFrom( address(this), _nftRecipient, _nft.tokenId, _amount, "0x0" ); } _resetAuction(_nft); emit NFTTransferredAndSellerPaid( _nft.nftContractAddress, _nft.tokenId, _nft.nftSellerAddress, _nftSeller, _nftHighestBid, _nftHighestBidder, _nftRecipient ); } function _payFeesAndSeller( NFT memory _nft, address _nftSeller, uint256 _highestBid ) internal { uint256 feesPaid; for ( uint256 i = 0; i < nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].feeRecipients.length; i++ ) { uint256 fee = _getPortionOfBid( _highestBid, nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].feePercentages[i] ); feesPaid = feesPaid + fee; _payout( _nft, nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].feeRecipients[i], fee ); } _payout( _nft, _nftSeller, (_highestBid - feesPaid) ); } function _payout( NFT memory _nft, address _recipient, uint256 _amount ) internal { address auctionERC20Token = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].ERC20Token; if (_isERC20Auction(auctionERC20Token)) { IERC20(auctionERC20Token).transfer(_recipient, _amount); } else { // attempt to send the funds to the recipient (bool success, ) = payable(_recipient).call{value: _amount}(""); // if it failed, update their credit balance so they can pull it later if (!success) { failedTransferCredits[_recipient] = failedTransferCredits[_recipient] + _amount; } } } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ TRANSFER NFT & PAY SELLER ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ SETTLE & WITHDRAW ║ ╚══════════════════════════════╝*/ function settleAuction(address _nftContractAddress, uint256 _tokenId,address _nftSellerAddress) external { _isAuctionOver(NFT(_nftContractAddress, _tokenId, _nftSellerAddress)); _transferNftAndPaySeller(NFT(_nftContractAddress, _tokenId , _nftSellerAddress)); emit AuctionSettled(_nftContractAddress, _tokenId,_nftSellerAddress, msg.sender); } function withdrawNft(address _nftContractAddress, uint256 _tokenId) external { NFT memory nft = NFT(_nftContractAddress, _tokenId , msg.sender); _onlyNftSeller(nft); require(!_isMinimumBidMade(nft), "The auction has a valid bid made" ); uint256[] memory batchTokenIds = nftContractAuctions[ _nftContractAddress ][_tokenId][msg.sender].batchTokenIds; uint256 numberOfTokens = batchTokenIds.length; if (numberOfTokens > 0) { uint256[] memory batchAmounts = nftContractAuctions[ _nftContractAddress ][_tokenId][msg.sender].batchAmounts; IERC1155(_nftContractAddress).safeBatchTransferFrom( address(this), nftContractAuctions[_nftContractAddress][_tokenId][msg.sender].nftSeller, batchTokenIds, batchAmounts, "0x0" ); for (uint256 i = 0; i < numberOfTokens; i++) { nftOwner[_nftContractAddress][batchTokenIds[i]][msg.sender] = address(0); } } else { uint256 _amount = nftContractAuctions[ _nftContractAddress ][_tokenId][msg.sender].amount; IERC1155(_nftContractAddress).safeTransferFrom( address(this), nftContractAuctions[_nftContractAddress][_tokenId][msg.sender].nftSeller, _tokenId, _amount, "0x0" ); } _resetAuction(nft); emit NFTWithdrawn(_nftContractAddress, _tokenId, msg.sender); } function withdrawBid(address _nftContractAddress, uint256 _tokenId,address _nftSellerAddress) external { NFT memory nft = NFT(_nftContractAddress, _tokenId , _nftSellerAddress); require(!_isMinimumBidMade(nft), "The auction has a valid bid made" ); address nftHighestBidder = nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].nftHighestBidder; require(msg.sender == nftHighestBidder, "Cannot withdraw funds"); uint256 nftHighestBid = nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].nftHighestBid; _resetBids(nft); _payout(nft, nftHighestBidder, nftHighestBid); emit BidWithdrawn(_nftContractAddress, _tokenId,msg.sender); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ SETTLE & WITHDRAW ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ UPDATE AUCTION ║ ╚══════════════════════════════╝*/ function updateWhitelistedBuyer( address _nftContractAddress, uint256 _tokenId, address _newWhitelistedBuyer ) external { NFT memory nft = NFT(_nftContractAddress, _tokenId , msg.sender); _onlyNftSeller(nft); require(_isASale(nft), "Not a sale"); nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .whitelistedBuyer = _newWhitelistedBuyer; //if an underbid is by a non whitelisted buyer,reverse that bid address nftHighestBidder = nftContractAuctions[_nftContractAddress][ _tokenId][msg.sender].nftHighestBidder; uint256 nftHighestBid = nftContractAuctions[_nftContractAddress][_tokenId][msg.sender].nftHighestBid; if (nftHighestBid > 0 && !(nftHighestBidder == _newWhitelistedBuyer)) { //we only revert the underbid if the seller specifies a different //whitelisted buyer to the highest bider _resetBids(nft); _payout(nft,nftHighestBidder,nftHighestBid ); } emit WhitelistedBuyerUpdated( _nftContractAddress, _tokenId, msg.sender, _newWhitelistedBuyer ); } function updateMinimumPrice( address _nftContractAddress, uint256 _tokenId, uint256 _newMinPrice ) external priceGreaterThanZero(_newMinPrice) minPriceDoesNotExceedLimit( nftContractAuctions[_nftContractAddress][_tokenId][msg.sender].buyNowPrice, _newMinPrice ) { NFT memory nft = NFT(_nftContractAddress, _tokenId , msg.sender); _onlyNftSeller(nft); require(!_isMinimumBidMade(nft), "The auction has a valid bid made" ); require(!_isASale(nft), "Not applicable for a sale"); nftContractAuctions[_nftContractAddress][_tokenId][msg.sender].minPrice = _newMinPrice; emit MinimumPriceUpdated(_nftContractAddress, _tokenId,msg.sender, _newMinPrice); if (_isMinimumBidMade(nft)) { _updateAuctionEnd(nft); } } function updateBuyNowPrice( address _nftContractAddress, uint256 _tokenId, uint256 _newBuyNowPrice ) external priceGreaterThanZero(_newBuyNowPrice) minPriceDoesNotExceedLimit( _newBuyNowPrice, nftContractAuctions[_nftContractAddress][_tokenId][msg.sender].minPrice ) { NFT memory nft = NFT(_nftContractAddress, _tokenId , msg.sender); _onlyNftSeller(nft); nftContractAuctions[_nftContractAddress][_tokenId][msg.sender].buyNowPrice = _newBuyNowPrice; emit BuyNowPriceUpdated(_nftContractAddress, _tokenId,msg.sender, _newBuyNowPrice); if (_isBuyNowPriceMet(nft)) { _transferNftAndPaySeller(nft); } } /* * The NFT seller can opt to end an auction by taking the current highest bid. */ function takeHighestBid(address _nftContractAddress, uint256 _tokenId) external { NFT memory nft = NFT(_nftContractAddress, _tokenId , msg.sender); _onlyNftSeller(nft); require( _isABidMade(nft), "cannot payout 0 bid" ); _transferNftAndPaySeller(nft); emit HighestBidTaken(_nftContractAddress, _tokenId,msg.sender); } /* * Query the owner of an NFT deposited for auction */ function ownerOfNFT(address _nftContractAddress, uint256 _tokenId,address _nftSellerAddress) external view returns (address) { address nftSeller = nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].nftSeller; if (nftSeller != address(0)) { return nftSeller; } address ownerAddr = nftOwner[_nftContractAddress][_tokenId][_nftSellerAddress]; require(ownerAddr != address(0), "NFT not deposited"); return ownerAddr; } /* * If the transfer of a bid has failed, allow the recipient to reclaim their amount later. */ function withdrawAllFailedCredits() external { uint256 amount = failedTransferCredits[msg.sender]; require(amount != 0, "no credits to withdraw"); failedTransferCredits[msg.sender] = 0; (bool successfulWithdraw, ) = msg.sender.call{value: amount}(""); require(successfulWithdraw, "withdraw failed"); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ UPDATE AUCTION ║ ╚══════════════════════════════╝*/ /**********************************/ function getPayTokens() external view returns (address[] memory) { return payTokens; } function setMarketState(uint256 _marketState) onlyOwner external { marketState = _marketState ; } function setFee(address[] memory _feeRecipients,uint32[] memory _feePercentages) onlyOwner external { if(_feeRecipients.length!=0) feeRecipients = _feeRecipients; if(_feePercentages.length!=0) feePercentages = _feePercentages; } function setPayTokens(address[] memory _payTokens) onlyOwner external { if(_payTokens.length!=0) payTokens = _payTokens; } receive() external payable {} function _transferEth(address _to, uint256 _amount) internal { (bool success, ) = _to.call{value: _amount}(''); require(success, "_transferEth: Eth transfer failed"); } // Emergency function: In case any ETH get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueETH(address recipient) onlyOwner external { _transferEth(recipient, address(this).balance); } // Emergency function: In case any ERC20 tokens get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueERC20(address asset, address recipient) onlyOwner external { IERC20(asset).transfer(recipient, IERC20(asset).balanceOf(address(this))); } // Emergency function: In case any ERC721 tokens get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueERC721(address asset, uint256[] calldata ids, address recipient) onlyOwner external { for (uint256 i = 0; i < ids.length; i++) { IERC721(asset).transferFrom(address(this), recipient, ids[i]); } } // Emergency function: In case any ERC1155 tokens get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueERC1155(address asset, uint256[] calldata ids, uint256[] calldata amounts, address recipient) onlyOwner external { for (uint256 i = 0; i < ids.length; i++) { IERC1155(asset).safeTransferFrom(address(this), recipient, ids[i], amounts[i], ""); } } }
min price = 0check if buyNowPrice is meet and conclude sale, otherwise reverse the early bidwe only revert the underbid if the seller specifies a differentwhitelisted buyer to the highest bidder
function createSaleLimitOrder( address _nftContractAddress, uint256 _tokenId, uint256 _amount, address _erc20Token, uint256 _buyNowPrice, address _whitelistedBuyer ) external priceGreaterThanZero(_buyNowPrice) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENLIMITORDER))), "The market is not open"); payTokensLimits(_erc20Token); _transferNftToAuctionContract(_nftContractAddress, _tokenId,_amount); _setupSale( _nftContractAddress, _tokenId, _amount, _erc20Token, _buyNowPrice, _whitelistedBuyer, uint(ORDERTYPE.LIMITORDER) ); emit SaleCreated( uint(ORDERTYPE.LIMITORDER), _nftContractAddress, _tokenId, _amount, msg.sender, _erc20Token, _buyNowPrice, _whitelistedBuyer, feeRecipients, feePercentages ); NFT memory nft = NFT(_nftContractAddress, _tokenId,msg.sender); if (_isABidMade(nft)) { if ( _isHighestBidderAllowedToPurchaseNFT(nft) ) { if (_isBuyNowPriceMet(nft)) { _transferNftAndPaySeller(nft); } _reverseAndResetPreviousBid(nft); } } }
7,328,271
./full_match/4/0x0F8d3f8F2b93288cd09F7FF198919c13a465A7d4/sources/contracts/TradingContract.sol
The withdraw function is a function with which investors can withdraw their funds in a tradingContract. Theapplicable fees will be calculated in this function. Check for equity in pairedToken, and swap the investor fraction into ETH. Check for equity in baseToken, and swap the investor fraction into ETH.In case of positive revenue, calculate and transfer the developer and the platform fee.Notice that revenue will be calculated in ETH (invested amount in ETH subtracted by final equity in ETH)Update all fractions of all the investors.
function withdraw() public updateSubtractedSupply(msg.sender) { require(fractions[msg.sender] > 0); uint256 _pairedTokenBalance = pairedToken.balanceOf(address(this)); uint256 _baseTokenBalance = baseToken.balanceOf(address(this)).sub(accumulatedFees); uint256 _swappedAmountPaired; uint256 _swappedAmountBase; if (_pairedTokenBalance > 0) { uint256 _amountInPaired = fractions[msg.sender].mul(_pairedTokenBalance).div(UNITY); _swappedAmountPaired = swapForETH(pairedTokenAddress, WETHAddress, _amountInPaired, getAmountOutMin(pairedTokenAddress, WETHAddress, _amountInPaired).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this)); } if (_baseTokenBalance > 0) { uint256 _amountInBase = fractions[msg.sender].mul(_baseTokenBalance).div(UNITY); _swappedAmountBase = swapForETH(baseTokenAddress, WETHAddress, _amountInBase, getAmountOutMin(baseTokenAddress, WETHAddress, _amountInBase).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this)); } if (invested[msg.sender] < _equity) { uint256 _revenue = _equity.sub(invested[msg.sender]); uint256 _developerFee = _revenue.mul(devFee).div(UNITY); uint256 _platformFee = _revenue.mul(IBalanceLogicContract(masterContract.getBalanceLogicAddress()).getPlatformFee()).div(UNITY); totalAccumulatedDevFees = totalAccumulatedDevFees.add(_developerFee); developerAddress.transfer(_developerFee); payable(owner()).transfer(_platformFee); _equity = _equity.sub(_developerFee).sub(_platformFee); } if(totalSupply != 0){ for(uint i=0; i < walletsArray.length; i++) { fractions[walletsArray[i]] = fractions[walletsArray[i]].mul(oldTotalSupply).div(totalSupply); } } fractions[msg.sender] = 0; totalInvested = totalInvested.sub(invested[msg.sender]); invested[msg.sender] = 0; investedInUSD[msg.sender] = 0; wallets[msg.sender]= false; ITradingContractDeployer(deployer).tradingCounterSub(msg.sender); emit Withdrawn(msg.sender, _equity); }
12,332,060
./full_match/80001/0xf8122d0AdA7ac3f14825c038df51133539EFD8d1/sources/project_/contracts/PresaleCollectionERC1155.sol
Check mystery box supply Check msg.value Choose tokens for mint Iterate on mystery box rules Iterate on amounts slot in rule (always is 0 index) Generate pseudo-random Choose rarity group Index 0 reserved for `ruleIterationId` => length - 1 Index 0 reserved for `ruleIterationId`, start from index 1 Check rarity group & replace to available if needed
function openBox(uint256 boxId) external payable { require(_mysteryBoxesSupply[boxId] < _mysteryBoxesLimit[boxId], "PresaleCollectionERC1155: Mystery box has reached the limit" ); require(msg.value == _mysteryBoxesPrices[boxId], "PresaleCollectionERC1155: Wrong mystery box price" ); for(uint16 ruleId = 0; ruleId < _mysteryBoxesRules[boxId].length; ruleId++) { for(uint16 ruleIterationId = 0; ruleIterationId < _mysteryBoxesRules[boxId][ruleId][0]; ruleIterationId++) { uint256 randomTokenRarityRange = RandomGenerator.getRandom( uint16(IncrementSeedUpgradeable._getIncrementSeed()), ); uint256 rarityGroupId; uint256 ruleSize = _mysteryBoxesRules[boxId][ruleId].length - 1; for(uint16 i = 1; i < ruleSize; i++) { uint256 rarityGroupDivider = _mysteryBoxesRules[boxId][ruleIterationId][i]; if(randomTokenRarityRange < rarityGroupDivider) { rarityGroupId = i - 1; break; } } for(uint16 i = uint16(rarityGroupId); i >= 0; i--) { if(_isTokensRatityGroupAreAvailable(i)) { rarityGroupId = rarityGroupId; break; } } uint16 availableTokensIdsIterator; for(uint16 i = 0; i < _tokenRarityGroups[rarityGroupId].length; i++) { uint256 tokenId = _tokenRarityGroups[rarityGroupId][i]; if(_tokenLimits[tokenId] > ERC1155SupplyUpgradeable.totalSupply(tokenId)) { availableTokensIds[availableTokensIdsIterator] = tokenId; availableTokensIdsIterator++; } } uint16(availableTokensIds.length - (availableTokensIds.length - availableTokensIdsIterator)), uint16(IncrementSeedUpgradeable._getIncrementSeed()), ); _msgSender(), availableTokensIds[randomAvailableTokenId], 1, "" ); } } }
5,627,567
./full_match/42161/0xe805977D5Fa2f05e2175507a1f8E44Cd3F22972c/sources/code/contracts/oasis/OasisSwapRouter.sol
refund dust eth, if any
function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = OasisSwapLibrary.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IOasisSwapPair(pair).mint(to); if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); }
16,308,708
./partial_match/1/0x7fb8f5D04b521B6880158819E69538655AABD5c4/sources/GasStationExact.sol
Gets the keeper registry address/
function getKeeperAddress() external view returns (address keeperAddress) { return KeeperAddress; }
3,542,051
/** *Submitted for verification at Etherscan.io on 2020-04-23 */ pragma solidity 0.5.14; /* * @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. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract SecretaryRole is Context { using Roles for Roles.Role; event SecretaryAdded(address indexed account); event SecretaryRemoved(address indexed account); Roles.Role private _secretaries; modifier onlySecretary() { require(isSecretary(_msgSender()), "SecretaryRole: caller does not have the Secretary role"); _; } function isSecretary(address account) public view returns (bool) { return _secretaries.has(account); } function addSecretary(address account) public onlySecretary { _addSecretary(account); } function renounceSecretary() public { _removeSecretary(_msgSender()); } function _addSecretary(address account) internal { _secretaries.add(account); emit SecretaryAdded(account); } function _removeSecretary(address account) internal { _secretaries.remove(account); emit SecretaryRemoved(account); } } /** * @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; } } interface IToken { // brief ERC-20 interface function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } contract MemberDripDrop is SecretaryRole { using SafeMath for uint256; /*************** INTERNAL DETAILS ***************/ uint256 public ethDrip; uint256 public tokenDrip; IToken public dripToken; address payable[] members; string public message; mapping(address => Member) public memberList; struct Member { uint256 memberIndex; bool exists; } // ****** // EVENTS // ****** event DripTokenUpdated(address indexed updatedDripToken); event TokenDripUpdated(uint256 indexed updatedTokenDrip); event ETHDripUpdated(uint256 indexed updatedETHDrip); event MemberAdded(address indexed addedMember); event MemberRemoved(address indexed removedMember); event MessageUpdated(string indexed updatedMessage); event SecretaryUpdated(address indexed updatedSecretary); function() external payable { } // contract receives ETH //injected LOCKED ETHER constructor( //injected LOCKED ETHER uint256 _ethDrip, uint256 _tokenDrip, address dripTokenAddress, address payable[] memory _members, string memory _message) payable public { // initializes contract for (uint256 i = 0; i < _members.length; i++) { require(_members[i] != address(0), "member address cannot be 0"); memberList[_members[i]].memberIndex = members.push(_members[i]).sub(1); memberList[_members[i]].exists = true; } ethDrip = _ethDrip; tokenDrip = _tokenDrip; dripToken = IToken(dripTokenAddress); message = _message; _addSecretary(members[0]); // first address in member array is initial secretary } /************************ DRIP/DROP TOKEN FUNCTIONS ************************/ function depositDripTKN() public { // deposit msg.sender drip token in approved amount sufficient for full member drip dripToken.transferFrom(msg.sender, address(this), tokenDrip.mul(members.length)); } function dripTKN() public onlySecretary { // transfer deposited drip token to members per drip amount for (uint256 i = 0; i < members.length; i++) { dripToken.transfer(members[i], tokenDrip); } } function customDripTKN(uint256[] memory drip, address dripTokenAddress) public onlySecretary { // transfer deposited token to members per index drip amounts for (uint256 i = 0; i < members.length; i++) { IToken token = IToken(dripTokenAddress); token.transfer(members[i], drip[i]); } } function dropTKN(uint256 drop, address dropTokenAddress) public { // transfer msg.sender token to members per approved drop amount for (uint256 i = 0; i < members.length; i++) { IToken dropToken = IToken(dropTokenAddress); dropToken.transferFrom(msg.sender, members[i], drop.div(members.length)); } } function customDropTKN(uint256[] memory drop, address dropTokenAddress) public { // transfer msg.sender token to members per approved index drop amounts for (uint256 i = 0; i < members.length; i++) { IToken dropToken = IToken(dropTokenAddress); dropToken.transferFrom(msg.sender, members[i], drop[i]); } } /********************** DRIP/DROP ETH FUNCTIONS **********************/ function depositDripETH() public payable { // deposit ETH in amount sufficient for full member drip //injected LOCKED ETHER require(msg.value == ethDrip.mul(members.length), "msg.value not sufficient for drip"); } function dripETH() public onlySecretary { // transfer deposited ETH to members per stored drip amount for (uint256 i = 0; i < members.length; i++) { members[i].transfer(0); } } function customDripETH(uint256[] memory drip) payable public onlySecretary { // transfer deposited ETH to members per index drip amounts //injected LOCKED ETHER for (uint256 i = 0; i < members.length; i++) { members[i].transfer(0); } } function dropETH() payable public { // transfer msg.sender ETH to members per attached drop amount //injected LOCKED ETHER for (uint256 i = 0; i < members.length; i++) { members[i].transfer(0); } } function customDropETH(uint256[] memory drop) payable public { // transfer msg.sender ETH to members per index drop amounts //injected LOCKED ETHER for (uint256 i = 0; i < members.length; i++) { require(msg.value == drop[i], "msg.value not sufficient for drop"); members[i].transfer(0); } } /******************* MANAGEMENT FUNCTIONS *******************/ // ****************** // DRIP/DROP REGISTRY // ****************** function addMember(address payable addedMember) public onlySecretary { require(memberList[addedMember].exists != true, "member already exists"); memberList[addedMember].memberIndex = members.push(addedMember).sub(1); memberList[addedMember].exists = true; emit MemberAdded(addedMember); } function removeMember(address removedMember) public onlySecretary { require(memberList[removedMember].exists == true, "no such member to remove"); uint256 memberToDelete = memberList[removedMember].memberIndex; address payable keyToMove = members[members.length.sub(1)]; members[memberToDelete] = keyToMove; memberList[keyToMove].memberIndex = memberToDelete; memberList[removedMember].exists = false; members.length--; emit MemberRemoved(removedMember); } function updateMessage(string memory updatedMessage) public onlySecretary { message = updatedMessage; emit MessageUpdated(updatedMessage); } // ************ // DRIP DETAILS // ************ function updateETHDrip(uint256 updatedETHDrip) public onlySecretary { ethDrip = updatedETHDrip; emit ETHDripUpdated(updatedETHDrip); } function updateDripToken(address updatedDripToken) public onlySecretary { dripToken = IToken(updatedDripToken); emit DripTokenUpdated(updatedDripToken); } function updateTokenDrip(uint256 updatedTokenDrip) public onlySecretary { tokenDrip = updatedTokenDrip; emit TokenDripUpdated(updatedTokenDrip); } /*************** GETTER FUNCTIONS ***************/ // **** // DRIP // **** function ETHBalance() public view returns (uint256) { // get balance of ETH in contract return address(this).balance; } function TokenBalance() public view returns (uint256) { // get balance of drip token in contract return dripToken.balanceOf(address(this)); } // ****** // MEMBER // ****** function Membership() public view returns (address payable[] memory) { return members; } function MemberCount() public view returns(uint256 memberCount) { return members.length; } function isMember(address memberAddress) public view returns (bool memberExists) { if(members.length == 0) return false; return (members[memberList[memberAddress].memberIndex] == memberAddress); } } contract MemberDripDropFactory { MemberDripDrop private DripDrop; address[] public dripdrops; event newDripDrop(address indexed dripdrop, address indexed secretary); function newMemberDripDrop( uint256 _ethDrip, uint256 _tokenDrip, address dripTokenAddress, address payable[] memory _members, // first address in member array is initial secretary string memory _message) payable public { DripDrop = (new MemberDripDrop).value(msg.value)( _ethDrip, _tokenDrip, dripTokenAddress, _members, _message); dripdrops.push(address(DripDrop)); emit newDripDrop(address(DripDrop), _members[0]); } }
transfer msg.sender token to members per approved drop amount
function dropTKN(uint256 drop, address dropTokenAddress) public {
15,825,373
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; import './SafeMath.sol'; import './Helpers.sol'; struct Buyer { uint256 eth; // Amount of sent ETH uint256 zapp; // Amount of bought ZAPP } struct EarlyAdopter { uint256 zapp; // Early adopter purchase amount } struct Referrer { bytes3 code; // Referral code uint256 time; // Time of code generation Referee[] referrals; // List of referrals } struct Referee { uint256 zapp; // Purchase amount } struct Hunter { bool verified; // Verified by Zappermint (after Token Sale) uint256 bonus; // Bounty bonus (after Token Sale) } struct Wallet { address payable addr; // Address of the wallet Buyer buyer; // Buyer data bool isBuyer; // Whether this wallet is a buyer EarlyAdopter earlyAdopter; // Early adopter data bool isEarlyAdopter; // Whether this wallet is an early adopter Referrer referrer; // Referrer data bool isReferrer; // Whether this wallet is a referrer Referee referee; // Referee data bool isReferee; // Whether this wallet is a referee Hunter hunter; // Hunter data bool isHunter; // Whether this wallet is a hunter bool claimed; // Whether ZAPP has been claimed } /** * Functionality for the Wallet struct */ library WalletInterface { using SafeMath for uint256; /** * @param self the wallet * @param referrerMin the minimum amount of ZAPP that has to be bought to be a referrer (for hunters) * @param checkVerified whether to check if the hunter is verified (set to false to show progress during token sale) * @return The amount of ZAPP bits that have been bought with the referrer's code (18 decimals) */ function calculateReferredAmount(Wallet storage self, uint256 referrerMin, bool checkVerified) internal view returns (uint256) { // 0 if not a referrer if (!self.isReferrer) return 0; // 0 if unverified hunter without enough bought ZAPP if (checkVerified && self.isHunter && !self.hunter.verified && self.buyer.zapp < referrerMin) return 0; // Calculate the sum of all referrals uint256 amount = 0; for (uint256 i = 0; i < self.referrer.referrals.length; ++i) { amount = amount.add(self.referrer.referrals[i].zapp); } return amount; } /** * @param self the wallet * @param bonus the bonus percentage (8 decimals) * @return The amount of ZAPP bits the early adopter will get as bonus (18 decimals) */ function getEarlyAdopterBonus(Wallet storage self, uint256 bonus) internal view returns (uint256) { if (!self.isEarlyAdopter) return 0; return Helpers.percentageOf(self.earlyAdopter.zapp, bonus); } /** * @param self the wallet * @param bonus the bonus percentage (8 decimals) * @param referrerMin the minimum amount of ZAPP a referrer must have bought to be eligible (18 decimals) * @param checkVerified whether to check if the hunter is verified * @return The amount of ZAPP bits the referrer will get as bonus (18 decimals) */ function getReferrerBonus(Wallet storage self, uint256 bonus, uint256 referrerMin, bool checkVerified) internal view returns (uint256) { if (!self.isReferrer) return 0; return Helpers.percentageOf(calculateReferredAmount(self, referrerMin, checkVerified), bonus); } /** * @param self the wallet * @param bonus the bonus percentage (8 decimals) * @return The amount of ZAPP bits the referee will get as bonus (18 decimals) */ function getRefereeBonus(Wallet storage self, uint256 bonus) internal view returns (uint256) { if (!self.isReferee) return 0; return Helpers.percentageOf(self.referee.zapp, bonus); } /** * @param self the wallet * @param checkVerified whether to check if the hunter is verified * @return The amount of ZAPP bits the hunter will get as bonus (18 decimals) */ function getHunterBonus(Wallet storage self, bool checkVerified) internal view returns (uint256) { if (!self.isHunter) return 0; if (checkVerified && !self.hunter.verified) return 0; return self.hunter.bonus; } /** * @param self the wallet * @return The amount of ZAPP bits the buyer has bought (18 decimals) */ function getBuyerZAPP(Wallet storage self) internal view returns (uint256) { if (!self.isBuyer) return 0; return self.buyer.zapp; } /** * Makes a purchase for the wallet * @param self the wallet * @param eth amount of sent ETH (18 decimals) * @param zapp amount of bought ZAPP (18 decimals) */ function purchase(Wallet storage self, uint256 eth, uint256 zapp) internal { // Become buyer self.isBuyer = true; // Add ETH to buyer data self.buyer.eth = self.buyer.eth.add(eth); // Add ZAPP to buyer data self.buyer.zapp = self.buyer.zapp.add(zapp); } /** * Adds early adoption bonus * @param self the wallet * @param zapp amount of bought ZAPP (18 decimals) * NOTE Doesn't check for early adoption end time */ function earlyAdoption(Wallet storage self, uint256 zapp) internal { // Become early adopter self.isEarlyAdopter = true; // Add ZAPP to early adopter data self.earlyAdopter.zapp = self.earlyAdopter.zapp.add(zapp); } /** * Adds referral bonuses * @param self the wallet * @param zapp amount of bought ZAPP (18 decimals) * @param referrer referrer wallet * NOTE Doesn't check for minimum purchase amount */ function referral(Wallet storage self, uint256 zapp, Wallet storage referrer) internal { // Become referee self.isReferee = true; // Add ZAPP to referee data self.referee.zapp = self.referee.zapp.add(zapp); // Add referral to referrer referrer.referrer.referrals.push(Referee(zapp)); } /** * Register as hunter * @param self the wallet */ function register(Wallet storage self, uint256 reward, mapping(bytes3 => address) storage codes) internal { // Become hunter self.isHunter = true; // Set initial bonus to the register reward self.hunter.bonus = reward; // Become referrer self.isReferrer = true; // Generate referral code generateReferralCode(self, codes); } /** * Verify hunter and add his rewards * @param self the wallet * @param bonus hunted bounties * NOTE Also becomes a hunter, even if unregistered */ function verify(Wallet storage self, uint256 bonus) internal { // Become hunter self.isHunter = true; // Set data self.hunter.verified = true; self.hunter.bonus = self.hunter.bonus.add(bonus); } /** * Generates a new code to assign to the referrer * @param self the wallet * @param codes the code map to check for duplicates * @return Unique referral code */ function generateReferralCode(Wallet storage self, mapping(bytes3 => address) storage codes) internal returns (bytes3) { // Only on referrers if (!self.isReferrer) return bytes3(0); // Only generate once if (self.referrer.code != bytes3(0)) return self.referrer.code; bytes memory enc = abi.encodePacked(self.addr); bytes3 code = bytes3(0); while (true) { bytes32 keccak = keccak256(enc); code = Helpers.keccak256ToReferralCode(keccak); if (code != bytes3(0) && codes[code] == address(0)) break; // If the code already exists, we hash the hash to generate a new code enc = abi.encodePacked(keccak); } // Save the code for the referrer and in the code map to avoid duplicates self.referrer.code = code; self.referrer.time = block.timestamp; codes[code] = self.addr; return code; } }
self the wallet return The amount of ZAPP bits the buyer has bought (18 decimals)/
function getBuyerZAPP(Wallet storage self) internal view returns (uint256) { if (!self.isBuyer) return 0; return self.buyer.zapp; }
12,950,265
./partial_match/1/0x5154AAeD1FfE2cA603f6b3cEf81a9c87f8866C64/sources/CompoundMonitor.sol
Bots call this method to boost for user when conditions are met If the contract owns gas token it will try and use it for gas price reduction _exData Exchange data _cAddresses cTokens addresses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] _user The actual address that owns the Compound position _flType Type of Flashloan we want to use 0 - AAVE_V2, 1 - Balancer
function boostFor( DFSExchangeData.ExchangeData memory _exData, address _user, FLHelper.FLType _flType ) public payable onlyApproved { string memory errReason; bool isAllowed; uint256 ratioBefore; CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); (isAllowed, ratioBefore, errReason) = checkPreconditions(holder, Method.Boost, _user); uint256 gasCost = calcGasCost(BOOST_GAS_COST); _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),address[2],uint256,uint8,address)", _exData, _cAddresses, gasCost, _flType, compoundSaverFlashLoan ) ); bool isGoodRatio; uint256 ratioAfter; (isGoodRatio, ratioAfter, errReason) = ratioGoodAfter( holder, Method.Boost, _user, ratioBefore ); returnEth(); logger.Log( address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter) ); }
4,127,581
pragma solidity ^0.4.19; // Interface contract to be implemented by SyscoinToken contract SyscoinTransactionProcessor { function processTransaction(uint txHash, uint value, address destinationAddress, uint32 _assetGUID, address superblockSubmitterAddress) public returns (uint); function burn(uint _value, uint32 _assetGUID, bytes syscoinWitnessProgram) payable public returns (bool success); } // Bitcoin transaction parsing library - modified for SYSCOIN // Copyright 2016 rain <https://keybase.io/rain> // // 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. // https://en.bitcoin.it/wiki/Protocol_documentation#tx // // Raw Bitcoin transaction structure: // // field | size | type | description // version | 4 | int32 | transaction version number // n_tx_in | 1-9 | var_int | number of transaction inputs // tx_in | 41+ | tx_in[] | list of transaction inputs // n_tx_out | 1-9 | var_int | number of transaction outputs // tx_out | 9+ | tx_out[] | list of transaction outputs // lock_time | 4 | uint32 | block number / timestamp at which tx locked // // Transaction input (tx_in) structure: // // field | size | type | description // previous | 36 | outpoint | Previous output transaction reference // script_len | 1-9 | var_int | Length of the signature script // sig_script | ? | uchar[] | Script for confirming transaction authorization // sequence | 4 | uint32 | Sender transaction version // // OutPoint structure: // // field | size | type | description // hash | 32 | char[32] | The hash of the referenced transaction // index | 4 | uint32 | The index of this output in the referenced transaction // // Transaction output (tx_out) structure: // // field | size | type | description // value | 8 | int64 | Transaction value (Satoshis) // pk_script_len | 1-9 | var_int | Length of the public key script // pk_script | ? | uchar[] | Public key as a Bitcoin script. // // Variable integers (var_int) can be encoded differently depending // on the represented value, to save space. Variable integers always // precede an array of a variable length data type (e.g. tx_in). // // Variable integer encodings as a function of represented value: // // value | bytes | format // <0xFD (253) | 1 | uint8 // <=0xFFFF (65535)| 3 | 0xFD followed by length as uint16 // <=0xFFFF FFFF | 5 | 0xFE followed by length as uint32 // - | 9 | 0xFF followed by length as uint64 // // Public key scripts `pk_script` are set on the output and can // take a number of forms. The regular transaction script is // called 'pay-to-pubkey-hash' (P2PKH): // // OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG // // OP_x are Bitcoin script opcodes. The bytes representation (including // the 0x14 20-byte stack push) is: // // 0x76 0xA9 0x14 <pubKeyHash> 0x88 0xAC // // The <pubKeyHash> is the ripemd160 hash of the sha256 hash of // the public key, preceded by a network version byte. (21 bytes total) // // Network version bytes: 0x00 (mainnet); 0x6f (testnet); 0x34 (namecoin) // // The Bitcoin address is derived from the pubKeyHash. The binary form is the // pubKeyHash, plus a checksum at the end. The checksum is the first 4 bytes // of the (32 byte) double sha256 of the pubKeyHash. (25 bytes total) // This is converted to base58 to form the publicly used Bitcoin address. // Mainnet P2PKH transaction scripts are to addresses beginning with '1'. // // P2SH ('pay to script hash') scripts only supply a script hash. The spender // must then provide the script that would allow them to redeem this output. // This allows for arbitrarily complex scripts to be funded using only a // hash of the script, and moves the onus on providing the script from // the spender to the redeemer. // // The P2SH script format is simple: // // OP_HASH160 <scriptHash> OP_EQUAL // // 0xA9 0x14 <scriptHash> 0x87 // // The <scriptHash> is the ripemd160 hash of the sha256 hash of the // redeem script. The P2SH address is derived from the scriptHash. // Addresses are the scriptHash with a version prefix of 5, encoded as // Base58check. These addresses begin with a '3'. // parse a raw Syscoin transaction byte array library SyscoinMessageLibrary { uint constant p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f; // secp256k1 uint constant q = (p + 1) / 4; // Error codes uint constant ERR_INVALID_HEADER = 10050; uint constant ERR_COINBASE_INDEX = 10060; // coinbase tx index within Litecoin merkle isn't 0 uint constant ERR_NOT_MERGE_MINED = 10070; // trying to check AuxPoW on a block that wasn't merge mined uint constant ERR_FOUND_TWICE = 10080; // 0xfabe6d6d found twice uint constant ERR_NO_MERGE_HEADER = 10090; // 0xfabe6d6d not found uint constant ERR_NOT_IN_FIRST_20 = 10100; // chain Merkle root isn't in the first 20 bytes of coinbase tx uint constant ERR_CHAIN_MERKLE = 10110; uint constant ERR_PARENT_MERKLE = 10120; uint constant ERR_PROOF_OF_WORK = 10130; uint constant ERR_INVALID_HEADER_HASH = 10140; uint constant ERR_PROOF_OF_WORK_AUXPOW = 10150; uint constant ERR_PARSE_TX_OUTPUT_LENGTH = 10160; uint constant ERR_PARSE_TX_SYS = 10170; enum Network { MAINNET, TESTNET, REGTEST } uint32 constant SYSCOIN_TX_VERSION_ASSET_ALLOCATION_BURN = 0x7407; uint32 constant SYSCOIN_TX_VERSION_BURN = 0x7401; // AuxPoW block fields struct AuxPoW { uint blockHash; uint txHash; uint coinbaseMerkleRoot; // Merkle root of auxiliary block hash tree; stored in coinbase tx field uint[] chainMerkleProof; // proves that a given Syscoin block hash belongs to a tree with the above root uint syscoinHashIndex; // index of Syscoin block hash within block hash tree uint coinbaseMerkleRootCode; // encodes whether or not the root was found properly uint parentMerkleRoot; // Merkle root of transaction tree from parent Litecoin block header uint[] parentMerkleProof; // proves that coinbase tx belongs to a tree with the above root uint coinbaseTxIndex; // index of coinbase tx within Litecoin tx tree uint parentNonce; } // Syscoin block header stored as a struct, mostly for readability purposes. // BlockHeader structs can be obtained by parsing a block header's first 80 bytes // with parseHeaderBytes. struct BlockHeader { uint32 bits; uint blockHash; } // Convert a variable integer into something useful and return it and // the index to after it. function parseVarInt(bytes memory txBytes, uint pos) private pure returns (uint, uint) { // the first byte tells us how big the integer is uint8 ibit = uint8(txBytes[pos]); pos += 1; // skip ibit if (ibit < 0xfd) { return (ibit, pos); } else if (ibit == 0xfd) { return (getBytesLE(txBytes, pos, 16), pos + 2); } else if (ibit == 0xfe) { return (getBytesLE(txBytes, pos, 32), pos + 4); } else if (ibit == 0xff) { return (getBytesLE(txBytes, pos, 64), pos + 8); } } // convert little endian bytes to uint function getBytesLE(bytes memory data, uint pos, uint bits) internal pure returns (uint) { if (bits == 8) { return uint8(data[pos]); } else if (bits == 16) { return uint16(data[pos]) + uint16(data[pos + 1]) * 2 ** 8; } else if (bits == 32) { return uint32(data[pos]) + uint32(data[pos + 1]) * 2 ** 8 + uint32(data[pos + 2]) * 2 ** 16 + uint32(data[pos + 3]) * 2 ** 24; } else if (bits == 64) { return uint64(data[pos]) + uint64(data[pos + 1]) * 2 ** 8 + uint64(data[pos + 2]) * 2 ** 16 + uint64(data[pos + 3]) * 2 ** 24 + uint64(data[pos + 4]) * 2 ** 32 + uint64(data[pos + 5]) * 2 ** 40 + uint64(data[pos + 6]) * 2 ** 48 + uint64(data[pos + 7]) * 2 ** 56; } } // @dev - Parses a syscoin tx // // @param txBytes - tx byte array // Outputs // @return output_value - amount sent to the lock address in satoshis // @return destinationAddress - ethereum destination address function parseTransaction(bytes memory txBytes) internal pure returns (uint, uint, address, uint32) { uint output_value; uint32 assetGUID; address destinationAddress; uint32 version; uint pos = 0; version = bytesToUint32Flipped(txBytes, pos); if(version != SYSCOIN_TX_VERSION_ASSET_ALLOCATION_BURN && version != SYSCOIN_TX_VERSION_BURN){ return (ERR_PARSE_TX_SYS, output_value, destinationAddress, assetGUID); } pos = skipInputs(txBytes, 4); (output_value, destinationAddress, assetGUID) = scanBurns(txBytes, version, pos); return (0, output_value, destinationAddress, assetGUID); } // skips witnesses and saves first script position/script length to extract pubkey of first witness scriptSig function skipWitnesses(bytes memory txBytes, uint pos, uint n_inputs) private pure returns (uint) { uint n_stack; (n_stack, pos) = parseVarInt(txBytes, pos); uint script_len; for (uint i = 0; i < n_inputs; i++) { for (uint j = 0; j < n_stack; j++) { (script_len, pos) = parseVarInt(txBytes, pos); pos += script_len; } } return n_stack; } function skipInputs(bytes memory txBytes, uint pos) private pure returns (uint) { uint n_inputs; uint script_len; (n_inputs, pos) = parseVarInt(txBytes, pos); // if dummy 0x00 is present this is a witness transaction if(n_inputs == 0x00){ (n_inputs, pos) = parseVarInt(txBytes, pos); // flag assert(n_inputs != 0x00); // after dummy/flag the real var int comes for txins (n_inputs, pos) = parseVarInt(txBytes, pos); } require(n_inputs < 100); for (uint i = 0; i < n_inputs; i++) { pos += 36; // skip outpoint (script_len, pos) = parseVarInt(txBytes, pos); pos += script_len + 4; // skip sig_script, seq } return pos; } // scan the burn outputs and return the value and script data of first burned output. function scanBurns(bytes memory txBytes, uint32 version, uint pos) private pure returns (uint, address, uint32) { uint script_len; uint output_value; uint32 assetGUID = 0; address destinationAddress; uint n_outputs; (n_outputs, pos) = parseVarInt(txBytes, pos); require(n_outputs < 10); for (uint i = 0; i < n_outputs; i++) { // output if(version == SYSCOIN_TX_VERSION_BURN){ output_value = getBytesLE(txBytes, pos, 64); } pos += 8; // varint (script_len, pos) = parseVarInt(txBytes, pos); if(!isOpReturn(txBytes, pos)){ // output script pos += script_len; output_value = 0; continue; } // skip opreturn marker pos += 1; if(version == SYSCOIN_TX_VERSION_ASSET_ALLOCATION_BURN){ (output_value, destinationAddress, assetGUID) = scanAssetDetails(txBytes, pos); } else if(version == SYSCOIN_TX_VERSION_BURN){ destinationAddress = scanSyscoinDetails(txBytes, pos); } // only one opreturn data allowed per transaction break; } return (output_value, destinationAddress, assetGUID); } function skipOutputs(bytes memory txBytes, uint pos) private pure returns (uint) { uint n_outputs; uint script_len; (n_outputs, pos) = parseVarInt(txBytes, pos); require(n_outputs < 10); for (uint i = 0; i < n_outputs; i++) { pos += 8; (script_len, pos) = parseVarInt(txBytes, pos); pos += script_len; } return pos; } // get final position of inputs, outputs and lock time // this is a helper function to slice a byte array and hash the inputs, outputs and lock time function getSlicePos(bytes memory txBytes, uint pos) private pure returns (uint slicePos) { slicePos = skipInputs(txBytes, pos + 4); slicePos = skipOutputs(txBytes, slicePos); slicePos += 4; // skip lock time } // scan a Merkle branch. // return array of values and the end position of the sibling hashes. // takes a 'stop' argument which sets the maximum number of // siblings to scan through. stop=0 => scan all. function scanMerkleBranch(bytes memory txBytes, uint pos, uint stop) private pure returns (uint[], uint) { uint n_siblings; uint halt; (n_siblings, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_siblings) { halt = n_siblings; } else { halt = stop; } uint[] memory sibling_values = new uint[](halt); for (uint i = 0; i < halt; i++) { sibling_values[i] = flip32Bytes(sliceBytes32Int(txBytes, pos)); pos += 32; } return (sibling_values, pos); } // Slice 20 contiguous bytes from bytes `data`, starting at `start` function sliceBytes20(bytes memory data, uint start) private pure returns (bytes20) { uint160 slice = 0; // FIXME: With solc v0.4.24 and optimizations enabled // using uint160 for index i will generate an error // "Error: VM Exception while processing transaction: Error: redPow(normalNum)" for (uint i = 0; i < 20; i++) { slice += uint160(data[i + start]) << (8 * (19 - i)); } return bytes20(slice); } // Slice 32 contiguous bytes from bytes `data`, starting at `start` function sliceBytes32Int(bytes memory data, uint start) private pure returns (uint slice) { for (uint i = 0; i < 32; i++) { if (i + start < data.length) { slice += uint(data[i + start]) << (8 * (31 - i)); } } } // @dev returns a portion of a given byte array specified by its starting and ending points // Should be private, made internal for testing // Breaks underscore naming convention for parameters because it raises a compiler error // if `offset` is changed to `_offset`. // // @param _rawBytes - array to be sliced // @param offset - first byte of sliced array // @param _endIndex - last byte of sliced array function sliceArray(bytes memory _rawBytes, uint offset, uint _endIndex) internal view returns (bytes) { uint len = _endIndex - offset; bytes memory result = new bytes(len); assembly { // Call precompiled contract to copy data if iszero(staticcall(gas, 0x04, add(add(_rawBytes, 0x20), offset), len, add(result, 0x20), len)) { revert(0, 0) } } return result; } // Returns true if the tx output is an OP_RETURN output function isOpReturn(bytes memory txBytes, uint pos) private pure returns (bool) { // scriptPub format is // 0x6a OP_RETURN return txBytes[pos] == byte(0x6a); } // Returns syscoin data parsed from the op_return data output from syscoin burn transaction function scanSyscoinDetails(bytes memory txBytes, uint pos) private pure returns (address) { uint8 op; (op, pos) = getOpcode(txBytes, pos); // ethereum addresses are 20 bytes (without the 0x) require(op == 0x14); return readEthereumAddress(txBytes, pos); } // Returns asset data parsed from the op_return data output from syscoin asset burn transaction function scanAssetDetails(bytes memory txBytes, uint pos) private pure returns (uint, address, uint32) { uint32 assetGUID; address destinationAddress; uint output_value; uint8 op; // vchAsset (op, pos) = getOpcode(txBytes, pos); // guid length should be 4 bytes require(op == 0x04); assetGUID = bytesToUint32(txBytes, pos); pos += op; // amount (op, pos) = getOpcode(txBytes, pos); require(op == 0x08); output_value = bytesToUint64(txBytes, pos); pos += op; // destination address (op, pos) = getOpcode(txBytes, pos); // ethereum contracts are 20 bytes (without the 0x) require(op == 0x14); destinationAddress = readEthereumAddress(txBytes, pos); return (output_value, destinationAddress, assetGUID); } // Read the ethereum address embedded in the tx output function readEthereumAddress(bytes memory txBytes, uint pos) private pure returns (address) { uint256 data; assembly { data := mload(add(add(txBytes, 20), pos)) } return address(uint160(data)); } // Read next opcode from script function getOpcode(bytes memory txBytes, uint pos) private pure returns (uint8, uint) { require(pos < txBytes.length); return (uint8(txBytes[pos]), pos + 1); } // @dev - convert an unsigned integer from little-endian to big-endian representation // // @param _input - little-endian value // @return - input value in big-endian format function flip32Bytes(uint _input) internal pure returns (uint result) { assembly { let pos := mload(0x40) for { let i := 0 } lt(i, 32) { i := add(i, 1) } { mstore8(add(pos, i), byte(sub(31, i), _input)) } result := mload(pos) } } // helpers for flip32Bytes struct UintWrapper { uint value; } function ptr(UintWrapper memory uw) private pure returns (uint addr) { assembly { addr := uw } } function parseAuxPoW(bytes memory rawBytes, uint pos) internal view returns (AuxPoW memory auxpow) { // we need to traverse the bytes with a pointer because some fields are of variable length pos += 80; // skip non-AuxPoW header uint slicePos; (slicePos) = getSlicePos(rawBytes, pos); auxpow.txHash = dblShaFlipMem(rawBytes, pos, slicePos - pos); pos = slicePos; // parent block hash, skip and manually hash below pos += 32; (auxpow.parentMerkleProof, pos) = scanMerkleBranch(rawBytes, pos, 0); auxpow.coinbaseTxIndex = getBytesLE(rawBytes, pos, 32); pos += 4; (auxpow.chainMerkleProof, pos) = scanMerkleBranch(rawBytes, pos, 0); auxpow.syscoinHashIndex = getBytesLE(rawBytes, pos, 32); pos += 4; // calculate block hash instead of reading it above, as some are LE and some are BE, we cannot know endianness and have to calculate from parent block header auxpow.blockHash = dblShaFlipMem(rawBytes, pos, 80); pos += 36; // skip parent version and prev block auxpow.parentMerkleRoot = sliceBytes32Int(rawBytes, pos); pos += 40; // skip root that was just read, parent block timestamp and bits auxpow.parentNonce = getBytesLE(rawBytes, pos, 32); uint coinbaseMerkleRootPosition; (auxpow.coinbaseMerkleRoot, coinbaseMerkleRootPosition, auxpow.coinbaseMerkleRootCode) = findCoinbaseMerkleRoot(rawBytes); } // @dev - looks for {0xfa, 0xbe, 'm', 'm'} byte sequence // returns the following 32 bytes if it appears once and only once, // 0 otherwise // also returns the position where the bytes first appear function findCoinbaseMerkleRoot(bytes memory rawBytes) private pure returns (uint, uint, uint) { uint position; bool found = false; for (uint i = 0; i < rawBytes.length; ++i) { if (rawBytes[i] == 0xfa && rawBytes[i+1] == 0xbe && rawBytes[i+2] == 0x6d && rawBytes[i+3] == 0x6d) { if (found) { // found twice return (0, position - 4, ERR_FOUND_TWICE); } else { found = true; position = i + 4; } } } if (!found) { // no merge mining header return (0, position - 4, ERR_NO_MERGE_HEADER); } else { return (sliceBytes32Int(rawBytes, position), position - 4, 1); } } // @dev - Evaluate the merkle root // // Given an array of hashes it calculates the // root of the merkle tree. // // @return root of merkle tree function makeMerkle(bytes32[] hashes2) external pure returns (bytes32) { bytes32[] memory hashes = hashes2; uint length = hashes.length; if (length == 1) return hashes[0]; require(length > 0); uint i; uint j; uint k; k = 0; while (length > 1) { k = 0; for (i = 0; i < length; i += 2) { j = i+1<length ? i+1 : length-1; hashes[k] = bytes32(concatHash(uint(hashes[i]), uint(hashes[j]))); k += 1; } length = k; } return hashes[0]; } // @dev - For a valid proof, returns the root of the Merkle tree. // // @param _txHash - transaction hash // @param _txIndex - transaction's index within the block it's assumed to be in // @param _siblings - transaction's Merkle siblings // @return - Merkle tree root of the block the transaction belongs to if the proof is valid, // garbage if it's invalid function computeMerkle(uint _txHash, uint _txIndex, uint[] memory _siblings) internal pure returns (uint) { uint resultHash = _txHash; uint i = 0; while (i < _siblings.length) { uint proofHex = _siblings[i]; uint sideOfSiblings = _txIndex % 2; // 0 means _siblings is on the right; 1 means left uint left; uint right; if (sideOfSiblings == 1) { left = proofHex; right = resultHash; } else if (sideOfSiblings == 0) { left = resultHash; right = proofHex; } resultHash = concatHash(left, right); _txIndex /= 2; i += 1; } return resultHash; } // @dev - calculates the Merkle root of a tree containing Litecoin transactions // in order to prove that `ap`'s coinbase tx is in that Litecoin block. // // @param _ap - AuxPoW information // @return - Merkle root of Litecoin block that the Syscoin block // with this info was mined in if AuxPoW Merkle proof is correct, // garbage otherwise function computeParentMerkle(AuxPoW memory _ap) internal pure returns (uint) { return flip32Bytes(computeMerkle(_ap.txHash, _ap.coinbaseTxIndex, _ap.parentMerkleProof)); } // @dev - calculates the Merkle root of a tree containing auxiliary block hashes // in order to prove that the Syscoin block identified by _blockHash // was merge-mined in a Litecoin block. // // @param _blockHash - SHA-256 hash of a certain Syscoin block // @param _ap - AuxPoW information corresponding to said block // @return - Merkle root of auxiliary chain tree // if AuxPoW Merkle proof is correct, garbage otherwise function computeChainMerkle(uint _blockHash, AuxPoW memory _ap) internal pure returns (uint) { return computeMerkle(_blockHash, _ap.syscoinHashIndex, _ap.chainMerkleProof); } // @dev - Helper function for Merkle root calculation. // Given two sibling nodes in a Merkle tree, calculate their parent. // Concatenates hashes `_tx1` and `_tx2`, then hashes the result. // // @param _tx1 - Merkle node (either root or internal node) // @param _tx2 - Merkle node (either root or internal node), has to be `_tx1`'s sibling // @return - `_tx1` and `_tx2`'s parent, i.e. the result of concatenating them, // hashing that twice and flipping the bytes. function concatHash(uint _tx1, uint _tx2) internal pure returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256(abi.encodePacked(flip32Bytes(_tx1), flip32Bytes(_tx2))))))); } // @dev - checks if a merge-mined block's Merkle proofs are correct, // i.e. Syscoin block hash is in coinbase Merkle tree // and coinbase transaction is in parent Merkle tree. // // @param _blockHash - SHA-256 hash of the block whose Merkle proofs are being checked // @param _ap - AuxPoW struct corresponding to the block // @return 1 if block was merge-mined and coinbase index, chain Merkle root and Merkle proofs are correct, // respective error code otherwise function checkAuxPoW(uint _blockHash, AuxPoW memory _ap) internal pure returns (uint) { if (_ap.coinbaseTxIndex != 0) { return ERR_COINBASE_INDEX; } if (_ap.coinbaseMerkleRootCode != 1) { return _ap.coinbaseMerkleRootCode; } if (computeChainMerkle(_blockHash, _ap) != _ap.coinbaseMerkleRoot) { return ERR_CHAIN_MERKLE; } if (computeParentMerkle(_ap) != _ap.parentMerkleRoot) { return ERR_PARENT_MERKLE; } return 1; } function sha256mem(bytes memory _rawBytes, uint offset, uint len) internal view returns (bytes32 result) { assembly { // Call sha256 precompiled contract (located in address 0x02) to copy data. // Assign to ptr the next available memory position (stored in memory position 0x40). let ptr := mload(0x40) if iszero(staticcall(gas, 0x02, add(add(_rawBytes, 0x20), offset), len, ptr, 0x20)) { revert(0, 0) } result := mload(ptr) } } // @dev - Bitcoin-way of hashing // @param _dataBytes - raw data to be hashed // @return - result of applying SHA-256 twice to raw data and then flipping the bytes function dblShaFlip(bytes _dataBytes) internal pure returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256(abi.encodePacked(_dataBytes)))))); } // @dev - Bitcoin-way of hashing // @param _dataBytes - raw data to be hashed // @return - result of applying SHA-256 twice to raw data and then flipping the bytes function dblShaFlipMem(bytes memory _rawBytes, uint offset, uint len) internal view returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256mem(_rawBytes, offset, len))))); } // @dev – Read a bytes32 from an offset in the byte array function readBytes32(bytes memory data, uint offset) internal pure returns (bytes32) { bytes32 result; assembly { result := mload(add(add(data, 0x20), offset)) } return result; } // @dev – Read an uint32 from an offset in the byte array function readUint32(bytes memory data, uint offset) internal pure returns (uint32) { uint32 result; assembly { result := mload(add(add(data, 0x20), offset)) } return result; } // @dev - Bitcoin-way of computing the target from the 'bits' field of a block header // based on http://www.righto.com/2014/02/bitcoin-mining-hard-way-algorithms.html//ref3 // // @param _bits - difficulty in bits format // @return - difficulty in target format function targetFromBits(uint32 _bits) internal pure returns (uint) { uint exp = _bits / 0x1000000; // 2**24 uint mant = _bits & 0xffffff; return mant * 256**(exp - 3); } uint constant SYSCOIN_DIFFICULTY_ONE = 0xFFFFF * 256**(0x1e - 3); // @dev - Calculate syscoin difficulty from target // https://en.bitcoin.it/wiki/Difficulty // Min difficulty for bitcoin is 0x1d00ffff // Min difficulty for syscoin is 0x1e0fffff function targetToDiff(uint target) internal pure returns (uint) { return SYSCOIN_DIFFICULTY_ONE / target; } // 0x00 version // 0x04 prev block hash // 0x24 merkle root // 0x44 timestamp // 0x48 bits // 0x4c nonce // @dev - extract previous block field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading hash from // @return - hash of block's parent in big endian format function getHashPrevBlock(bytes memory _blockHeader) internal pure returns (uint) { uint hashPrevBlock; assembly { hashPrevBlock := mload(add(add(_blockHeader, 32), 0x04)) } return flip32Bytes(hashPrevBlock); } // @dev - extract Merkle root field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading root from // @return - block's Merkle root in big endian format function getHeaderMerkleRoot(bytes memory _blockHeader) public pure returns (uint) { uint merkle; assembly { merkle := mload(add(add(_blockHeader, 32), 0x24)) } return flip32Bytes(merkle); } // @dev - extract timestamp field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading bits from // @return - block's timestamp in big-endian format function getTimestamp(bytes memory _blockHeader) internal pure returns (uint32 time) { return bytesToUint32Flipped(_blockHeader, 0x44); } // @dev - extract bits field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading bits from // @return - block's difficulty in bits format, also big-endian function getBits(bytes memory _blockHeader) internal pure returns (uint32 bits) { return bytesToUint32Flipped(_blockHeader, 0x48); } // @dev - converts raw bytes representation of a Syscoin block header to struct representation // // @param _rawBytes - first 80 bytes of a block header // @return - exact same header information in BlockHeader struct form function parseHeaderBytes(bytes memory _rawBytes, uint pos) internal view returns (BlockHeader bh) { bh.bits = getBits(_rawBytes); bh.blockHash = dblShaFlipMem(_rawBytes, pos, 80); } uint32 constant VERSION_AUXPOW = (1 << 8); // @dev - Converts a bytes of size 4 to uint32, // e.g. for input [0x01, 0x02, 0x03 0x04] returns 0x01020304 function bytesToUint32Flipped(bytes memory input, uint pos) internal pure returns (uint32 result) { result = uint32(input[pos]) + uint32(input[pos + 1])*(2**8) + uint32(input[pos + 2])*(2**16) + uint32(input[pos + 3])*(2**24); } function bytesToUint64(bytes memory input, uint pos) internal pure returns (uint64 result) { result = uint64(input[pos+7]) + uint64(input[pos + 6])*(2**8) + uint64(input[pos + 5])*(2**16) + uint64(input[pos + 4])*(2**24) + uint64(input[pos + 3])*(2**32) + uint64(input[pos + 2])*(2**40) + uint64(input[pos + 1])*(2**48) + uint64(input[pos])*(2**56); } function bytesToUint32(bytes memory input, uint pos) internal pure returns (uint32 result) { result = uint32(input[pos+3]) + uint32(input[pos + 2])*(2**8) + uint32(input[pos + 1])*(2**16) + uint32(input[pos])*(2**24); } // @dev - checks version to determine if a block has merge mining information function isMergeMined(bytes memory _rawBytes, uint pos) internal pure returns (bool) { return bytesToUint32Flipped(_rawBytes, pos) & VERSION_AUXPOW != 0; } // @dev - Verify block header // @param _blockHeaderBytes - array of bytes with the block header // @param _pos - starting position of the block header // @param _proposedBlockHash - proposed block hash computing from block header bytes // @return - [ErrorCode, IsMergeMined] function verifyBlockHeader(bytes _blockHeaderBytes, uint _pos, uint _proposedBlockHash) external view returns (uint, bool) { BlockHeader memory blockHeader = parseHeaderBytes(_blockHeaderBytes, _pos); uint blockSha256Hash = blockHeader.blockHash; // must confirm that the header hash passed in and computing hash matches if(blockSha256Hash != _proposedBlockHash){ return (ERR_INVALID_HEADER_HASH, true); } uint target = targetFromBits(blockHeader.bits); if (_blockHeaderBytes.length > 80 && isMergeMined(_blockHeaderBytes, 0)) { AuxPoW memory ap = parseAuxPoW(_blockHeaderBytes, _pos); if (ap.blockHash > target) { return (ERR_PROOF_OF_WORK_AUXPOW, true); } uint auxPoWCode = checkAuxPoW(blockSha256Hash, ap); if (auxPoWCode != 1) { return (auxPoWCode, true); } return (0, true); } else { if (_proposedBlockHash > target) { return (ERR_PROOF_OF_WORK, false); } return (0, false); } } // For verifying Syscoin difficulty int64 constant TARGET_TIMESPAN = int64(21600); int64 constant TARGET_TIMESPAN_DIV_4 = TARGET_TIMESPAN / int64(4); int64 constant TARGET_TIMESPAN_MUL_4 = TARGET_TIMESPAN * int64(4); int64 constant TARGET_TIMESPAN_ADJUSTMENT = int64(360); // 6 hour uint constant INITIAL_CHAIN_WORK = 0x100001; uint constant POW_LIMIT = 0x00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // @dev - Calculate difficulty from compact representation (bits) found in block function diffFromBits(uint32 bits) external pure returns (uint) { return targetToDiff(targetFromBits(bits))*INITIAL_CHAIN_WORK; } function difficultyAdjustmentInterval() external pure returns (int64) { return TARGET_TIMESPAN_ADJUSTMENT; } // @param _actualTimespan - time elapsed from previous block creation til current block creation; // i.e., how much time it took to mine the current block // @param _bits - previous block header difficulty (in bits) // @return - expected difficulty for the next block function calculateDifficulty(int64 _actualTimespan, uint32 _bits) external pure returns (uint32 result) { int64 actualTimespan = _actualTimespan; // Limit adjustment step if (_actualTimespan < TARGET_TIMESPAN_DIV_4) { actualTimespan = TARGET_TIMESPAN_DIV_4; } else if (_actualTimespan > TARGET_TIMESPAN_MUL_4) { actualTimespan = TARGET_TIMESPAN_MUL_4; } // Retarget uint bnNew = targetFromBits(_bits); bnNew = bnNew * uint(actualTimespan); bnNew = uint(bnNew) / uint(TARGET_TIMESPAN); if (bnNew > POW_LIMIT) { bnNew = POW_LIMIT; } return toCompactBits(bnNew); } // @dev - shift information to the right by a specified number of bits // // @param _val - value to be shifted // @param _shift - number of bits to shift // @return - `_val` shifted `_shift` bits to the right, i.e. divided by 2**`_shift` function shiftRight(uint _val, uint _shift) private pure returns (uint) { return _val / uint(2)**_shift; } // @dev - shift information to the left by a specified number of bits // // @param _val - value to be shifted // @param _shift - number of bits to shift // @return - `_val` shifted `_shift` bits to the left, i.e. multiplied by 2**`_shift` function shiftLeft(uint _val, uint _shift) private pure returns (uint) { return _val * uint(2)**_shift; } // @dev - get the number of bits required to represent a given integer value without losing information // // @param _val - unsigned integer value // @return - given value's bit length function bitLen(uint _val) private pure returns (uint length) { uint int_type = _val; while (int_type > 0) { int_type = shiftRight(int_type, 1); length += 1; } } // @dev - Convert uint256 to compact encoding // based on https://github.com/petertodd/python-bitcoinlib/blob/2a5dda45b557515fb12a0a18e5dd48d2f5cd13c2/bitcoin/core/serialize.py // Analogous to arith_uint256::GetCompact from C++ implementation // // @param _val - difficulty in target format // @return - difficulty in bits format function toCompactBits(uint _val) private pure returns (uint32) { uint nbytes = uint (shiftRight((bitLen(_val) + 7), 3)); uint32 compact = 0; if (nbytes <= 3) { compact = uint32 (shiftLeft((_val & 0xFFFFFF), 8 * (3 - nbytes))); } else { compact = uint32 (shiftRight(_val, 8 * (nbytes - 3))); compact = uint32 (compact & 0xFFFFFF); } // If the sign bit (0x00800000) is set, divide the mantissa by 256 and // increase the exponent to get an encoding without it set. if ((compact & 0x00800000) > 0) { compact = uint32(shiftRight(compact, 8)); nbytes += 1; } return compact | uint32(shiftLeft(nbytes, 24)); } } // @dev - SyscoinSuperblocks error codes contract SyscoinErrorCodes { // Error codes uint constant ERR_SUPERBLOCK_OK = 0; uint constant ERR_SUPERBLOCK_BAD_STATUS = 50020; uint constant ERR_SUPERBLOCK_BAD_SYSCOIN_STATUS = 50025; uint constant ERR_SUPERBLOCK_NO_TIMEOUT = 50030; uint constant ERR_SUPERBLOCK_BAD_TIMESTAMP = 50035; uint constant ERR_SUPERBLOCK_INVALID_MERKLE = 50040; uint constant ERR_SUPERBLOCK_BAD_PARENT = 50050; uint constant ERR_SUPERBLOCK_OWN_CHALLENGE = 50055; uint constant ERR_SUPERBLOCK_MIN_DEPOSIT = 50060; uint constant ERR_SUPERBLOCK_NOT_CLAIMMANAGER = 50070; uint constant ERR_SUPERBLOCK_BAD_CLAIM = 50080; uint constant ERR_SUPERBLOCK_VERIFICATION_PENDING = 50090; uint constant ERR_SUPERBLOCK_CLAIM_DECIDED = 50100; uint constant ERR_SUPERBLOCK_BAD_CHALLENGER = 50110; uint constant ERR_SUPERBLOCK_BAD_ACCUMULATED_WORK = 50120; uint constant ERR_SUPERBLOCK_BAD_BITS = 50130; uint constant ERR_SUPERBLOCK_MISSING_CONFIRMATIONS = 50140; uint constant ERR_SUPERBLOCK_BAD_LASTBLOCK = 50150; uint constant ERR_SUPERBLOCK_BAD_BLOCKHEIGHT = 50160; // error codes for verifyTx uint constant ERR_BAD_FEE = 20010; uint constant ERR_CONFIRMATIONS = 20020; uint constant ERR_CHAIN = 20030; uint constant ERR_SUPERBLOCK = 20040; uint constant ERR_MERKLE_ROOT = 20050; uint constant ERR_TX_64BYTE = 20060; // error codes for relayTx uint constant ERR_RELAY_VERIFY = 30010; // Minimum gas requirements uint constant public minReward = 1000000000000000000; uint constant public superblockCost = 440000; uint constant public challengeCost = 34000; uint constant public minProposalDeposit = challengeCost + minReward; uint constant public minChallengeDeposit = superblockCost + minReward; uint constant public respondMerkleRootHashesCost = 378000; // TODO: measure this with 60 hashes uint constant public respondBlockHeaderCost = 40000; uint constant public verifySuperblockCost = 220000; } // @dev - Manages superblocks // // Management of superblocks and status transitions contract SyscoinSuperblocks is SyscoinErrorCodes { // @dev - Superblock status enum Status { Unitialized, New, InBattle, SemiApproved, Approved, Invalid } struct SuperblockInfo { bytes32 blocksMerkleRoot; uint accumulatedWork; uint timestamp; uint prevTimestamp; bytes32 lastHash; bytes32 parentId; address submitter; bytes32 ancestors; uint32 lastBits; uint32 index; uint32 height; uint32 blockHeight; Status status; } // Mapping superblock id => superblock data mapping (bytes32 => SuperblockInfo) superblocks; // Index to superblock id mapping (uint32 => bytes32) private indexSuperblock; struct ProcessTransactionParams { uint value; address destinationAddress; uint32 assetGUID; address superblockSubmitterAddress; SyscoinTransactionProcessor untrustedTargetContract; } mapping (uint => ProcessTransactionParams) private txParams; uint32 indexNextSuperblock; bytes32 public bestSuperblock; uint public bestSuperblockAccumulatedWork; event NewSuperblock(bytes32 superblockHash, address who); event ApprovedSuperblock(bytes32 superblockHash, address who); event ChallengeSuperblock(bytes32 superblockHash, address who); event SemiApprovedSuperblock(bytes32 superblockHash, address who); event InvalidSuperblock(bytes32 superblockHash, address who); event ErrorSuperblock(bytes32 superblockHash, uint err); event VerifyTransaction(bytes32 txHash, uint returnCode); event RelayTransaction(bytes32 txHash, uint returnCode); // SyscoinClaimManager address public trustedClaimManager; modifier onlyClaimManager() { require(msg.sender == trustedClaimManager); _; } // @dev – the constructor constructor() public {} // @dev - sets ClaimManager instance associated with managing superblocks. // Once trustedClaimManager has been set, it cannot be changed. // @param _claimManager - address of the ClaimManager contract to be associated with function setClaimManager(address _claimManager) public { require(address(trustedClaimManager) == 0x0 && _claimManager != 0x0); trustedClaimManager = _claimManager; } // @dev - Initializes superblocks contract // // Initializes the superblock contract. It can only be called once. // // @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock // @param _accumulatedWork Accumulated proof of work of the last block in the superblock // @param _timestamp Timestamp of the last block in the superblock // @param _prevTimestamp Timestamp of the block when the last difficulty adjustment happened (every 360 blocks) // @param _lastHash Hash of the last block in the superblock // @param _lastBits Difficulty bits of the last block in the superblock // @param _parentId Id of the parent superblock // @param _blockHeight Block height of last block in superblock // @return Error code and superblockHash function initialize( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, uint32 _blockHeight ) public returns (uint, bytes32) { require(bestSuperblock == 0); require(_parentId == 0); bytes32 superblockHash = calcSuperblockHash(_blocksMerkleRoot, _accumulatedWork, _timestamp, _prevTimestamp, _lastHash, _lastBits, _parentId, _blockHeight); SuperblockInfo storage superblock = superblocks[superblockHash]; require(superblock.status == Status.Unitialized); indexSuperblock[indexNextSuperblock] = superblockHash; superblock.blocksMerkleRoot = _blocksMerkleRoot; superblock.accumulatedWork = _accumulatedWork; superblock.timestamp = _timestamp; superblock.prevTimestamp = _prevTimestamp; superblock.lastHash = _lastHash; superblock.parentId = _parentId; superblock.submitter = msg.sender; superblock.index = indexNextSuperblock; superblock.height = 1; superblock.lastBits = _lastBits; superblock.status = Status.Approved; superblock.ancestors = 0x0; superblock.blockHeight = _blockHeight; indexNextSuperblock++; emit NewSuperblock(superblockHash, msg.sender); bestSuperblock = superblockHash; bestSuperblockAccumulatedWork = _accumulatedWork; emit ApprovedSuperblock(superblockHash, msg.sender); return (ERR_SUPERBLOCK_OK, superblockHash); } // @dev - Proposes a new superblock // // To be accepted, a new superblock needs to have its parent // either approved or semi-approved. // // @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock // @param _accumulatedWork Accumulated proof of work of the last block in the superblock // @param _timestamp Timestamp of the last block in the superblock // @param _prevTimestamp Timestamp of the block when the last difficulty adjustment happened (every 360 blocks) // @param _lastHash Hash of the last block in the superblock // @param _lastBits Difficulty bits of the last block in the superblock // @param _parentId Id of the parent superblock // @param _blockHeight Block height of last block in superblock // @return Error code and superblockHash function propose( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, uint32 _blockHeight, address submitter ) public returns (uint, bytes32) { if (msg.sender != trustedClaimManager) { emit ErrorSuperblock(0, ERR_SUPERBLOCK_NOT_CLAIMMANAGER); return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0); } SuperblockInfo storage parent = superblocks[_parentId]; if (parent.status != Status.SemiApproved && parent.status != Status.Approved) { emit ErrorSuperblock(superblockHash, ERR_SUPERBLOCK_BAD_PARENT); return (ERR_SUPERBLOCK_BAD_PARENT, 0); } bytes32 superblockHash = calcSuperblockHash(_blocksMerkleRoot, _accumulatedWork, _timestamp, _prevTimestamp, _lastHash, _lastBits, _parentId, _blockHeight); SuperblockInfo storage superblock = superblocks[superblockHash]; if (superblock.status == Status.Unitialized) { indexSuperblock[indexNextSuperblock] = superblockHash; superblock.blocksMerkleRoot = _blocksMerkleRoot; superblock.accumulatedWork = _accumulatedWork; superblock.timestamp = _timestamp; superblock.prevTimestamp = _prevTimestamp; superblock.lastHash = _lastHash; superblock.parentId = _parentId; superblock.submitter = submitter; superblock.index = indexNextSuperblock; superblock.height = parent.height + 1; superblock.lastBits = _lastBits; superblock.status = Status.New; superblock.blockHeight = _blockHeight; superblock.ancestors = updateAncestors(parent.ancestors, parent.index, parent.height); indexNextSuperblock++; emit NewSuperblock(superblockHash, submitter); } return (ERR_SUPERBLOCK_OK, superblockHash); } // @dev - Confirm a proposed superblock // // An unchallenged superblock can be confirmed after a timeout. // A challenged superblock is confirmed if it has enough descendants // in the main chain. // // @param _superblockHash Id of the superblock to confirm // @param _validator Address requesting superblock confirmation // @return Error code and superblockHash function confirm(bytes32 _superblockHash, address _validator) public returns (uint, bytes32) { if (msg.sender != trustedClaimManager) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER); return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0); } SuperblockInfo storage superblock = superblocks[_superblockHash]; if (superblock.status != Status.New && superblock.status != Status.SemiApproved) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return (ERR_SUPERBLOCK_BAD_STATUS, 0); } SuperblockInfo storage parent = superblocks[superblock.parentId]; if (parent.status != Status.Approved) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_PARENT); return (ERR_SUPERBLOCK_BAD_PARENT, 0); } superblock.status = Status.Approved; if (superblock.accumulatedWork > bestSuperblockAccumulatedWork) { bestSuperblock = _superblockHash; bestSuperblockAccumulatedWork = superblock.accumulatedWork; } emit ApprovedSuperblock(_superblockHash, _validator); return (ERR_SUPERBLOCK_OK, _superblockHash); } // @dev - Challenge a proposed superblock // // A new superblock can be challenged to start a battle // to verify the correctness of the data submitted. // // @param _superblockHash Id of the superblock to challenge // @param _challenger Address requesting a challenge // @return Error code and superblockHash function challenge(bytes32 _superblockHash, address _challenger) public returns (uint, bytes32) { if (msg.sender != trustedClaimManager) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER); return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0); } SuperblockInfo storage superblock = superblocks[_superblockHash]; if (superblock.status != Status.New && superblock.status != Status.InBattle) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return (ERR_SUPERBLOCK_BAD_STATUS, 0); } if(superblock.submitter == _challenger){ emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_OWN_CHALLENGE); return (ERR_SUPERBLOCK_OWN_CHALLENGE, 0); } superblock.status = Status.InBattle; emit ChallengeSuperblock(_superblockHash, _challenger); return (ERR_SUPERBLOCK_OK, _superblockHash); } // @dev - Semi-approve a challenged superblock // // A challenged superblock can be marked as semi-approved // if it satisfies all the queries or when all challengers have // stopped participating. // // @param _superblockHash Id of the superblock to semi-approve // @param _validator Address requesting semi approval // @return Error code and superblockHash function semiApprove(bytes32 _superblockHash, address _validator) public returns (uint, bytes32) { if (msg.sender != trustedClaimManager) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER); return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0); } SuperblockInfo storage superblock = superblocks[_superblockHash]; if (superblock.status != Status.InBattle && superblock.status != Status.New) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return (ERR_SUPERBLOCK_BAD_STATUS, 0); } superblock.status = Status.SemiApproved; emit SemiApprovedSuperblock(_superblockHash, _validator); return (ERR_SUPERBLOCK_OK, _superblockHash); } // @dev - Invalidates a superblock // // A superblock with incorrect data can be invalidated immediately. // Superblocks that are not in the main chain can be invalidated // if not enough superblocks follow them, i.e. they don't have // enough descendants. // // @param _superblockHash Id of the superblock to invalidate // @param _validator Address requesting superblock invalidation // @return Error code and superblockHash function invalidate(bytes32 _superblockHash, address _validator) public returns (uint, bytes32) { if (msg.sender != trustedClaimManager) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER); return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0); } SuperblockInfo storage superblock = superblocks[_superblockHash]; if (superblock.status != Status.InBattle && superblock.status != Status.SemiApproved) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return (ERR_SUPERBLOCK_BAD_STATUS, 0); } superblock.status = Status.Invalid; emit InvalidSuperblock(_superblockHash, _validator); return (ERR_SUPERBLOCK_OK, _superblockHash); } // @dev - relays transaction `_txBytes` to `_untrustedTargetContract`'s processTransaction() method. // Also logs the value of processTransaction. // Note: callers cannot be 100% certain when an ERR_RELAY_VERIFY occurs because // it may also have been returned by processTransaction(). Callers should be // aware of the contract that they are relaying transactions to and // understand what that contract's processTransaction method returns. // // @param _txBytes - transaction bytes // @param _txIndex - transaction's index within the block // @param _txSiblings - transaction's Merkle siblings // @param _syscoinBlockHeader - block header containing transaction // @param _syscoinBlockIndex - block's index withing superblock // @param _syscoinBlockSiblings - block's merkle siblings // @param _superblockHash - superblock containing block header // @param _untrustedTargetContract - the contract that is going to process the transaction function relayTx( bytes memory _txBytes, uint _txIndex, uint[] _txSiblings, bytes memory _syscoinBlockHeader, uint _syscoinBlockIndex, uint[] memory _syscoinBlockSiblings, bytes32 _superblockHash, SyscoinTransactionProcessor _untrustedTargetContract ) public returns (uint) { // Check if Syscoin block belongs to given superblock if (bytes32(SyscoinMessageLibrary.computeMerkle(SyscoinMessageLibrary.dblShaFlip(_syscoinBlockHeader), _syscoinBlockIndex, _syscoinBlockSiblings)) != getSuperblockMerkleRoot(_superblockHash)) { // Syscoin block is not in superblock emit RelayTransaction(bytes32(0), ERR_SUPERBLOCK); return ERR_SUPERBLOCK; } uint txHash = verifyTx(_txBytes, _txIndex, _txSiblings, _syscoinBlockHeader, _superblockHash); if (txHash != 0) { uint ret = parseTxHelper(_txBytes, txHash, _untrustedTargetContract); if(ret != 0){ emit RelayTransaction(bytes32(0), ret); return ret; } ProcessTransactionParams memory params = txParams[txHash]; params.superblockSubmitterAddress = superblocks[_superblockHash].submitter; txParams[txHash] = params; return verifyTxHelper(txHash); } emit RelayTransaction(bytes32(0), ERR_RELAY_VERIFY); return(ERR_RELAY_VERIFY); } function parseTxHelper(bytes memory _txBytes, uint txHash, SyscoinTransactionProcessor _untrustedTargetContract) private returns (uint) { uint value; address destinationAddress; uint32 _assetGUID; uint ret; (ret, value, destinationAddress, _assetGUID) = SyscoinMessageLibrary.parseTransaction(_txBytes); if(ret != 0){ return ret; } ProcessTransactionParams memory params; params.value = value; params.destinationAddress = destinationAddress; params.assetGUID = _assetGUID; params.untrustedTargetContract = _untrustedTargetContract; txParams[txHash] = params; return 0; } function verifyTxHelper(uint txHash) private returns (uint) { ProcessTransactionParams memory params = txParams[txHash]; uint returnCode = params.untrustedTargetContract.processTransaction(txHash, params.value, params.destinationAddress, params.assetGUID, params.superblockSubmitterAddress); emit RelayTransaction(bytes32(txHash), returnCode); return (returnCode); } // @dev - Checks whether the transaction given by `_txBytes` is in the block identified by `_txBlockHeaderBytes`. // First it guards against a Merkle tree collision attack by raising an error if the transaction is exactly 64 bytes long, // then it calls helperVerifyHash to do the actual check. // // @param _txBytes - transaction bytes // @param _txIndex - transaction's index within the block // @param _siblings - transaction's Merkle siblings // @param _txBlockHeaderBytes - block header containing transaction // @param _txsuperblockHash - superblock containing block header // @return - SHA-256 hash of _txBytes if the transaction is in the block, 0 otherwise // TODO: this can probably be made private function verifyTx( bytes memory _txBytes, uint _txIndex, uint[] memory _siblings, bytes memory _txBlockHeaderBytes, bytes32 _txsuperblockHash ) public returns (uint) { uint txHash = SyscoinMessageLibrary.dblShaFlip(_txBytes); if (_txBytes.length == 64) { // todo: is check 32 also needed? emit VerifyTransaction(bytes32(txHash), ERR_TX_64BYTE); return 0; } if (helperVerifyHash(txHash, _txIndex, _siblings, _txBlockHeaderBytes, _txsuperblockHash) == 1) { return txHash; } else { // log is done via helperVerifyHash return 0; } } // @dev - Checks whether the transaction identified by `_txHash` is in the block identified by `_blockHeaderBytes` // and whether the block is in the Syscoin main chain. Transaction check is done via Merkle proof. // Note: no verification is performed to prevent txHash from just being an // internal hash in the Merkle tree. Thus this helper method should NOT be used // directly and is intended to be private. // // @param _txHash - transaction hash // @param _txIndex - transaction's index within the block // @param _siblings - transaction's Merkle siblings // @param _blockHeaderBytes - block header containing transaction // @param _txsuperblockHash - superblock containing block header // @return - 1 if the transaction is in the block and the block is in the main chain, // 20020 (ERR_CONFIRMATIONS) if the block is not in the main chain, // 20050 (ERR_MERKLE_ROOT) if the block is in the main chain but the Merkle proof fails. function helperVerifyHash( uint256 _txHash, uint _txIndex, uint[] memory _siblings, bytes memory _blockHeaderBytes, bytes32 _txsuperblockHash ) private returns (uint) { //TODO: Verify superblock is in superblock's main chain if (!isApproved(_txsuperblockHash) || !inMainChain(_txsuperblockHash)) { emit VerifyTransaction(bytes32(_txHash), ERR_CHAIN); return (ERR_CHAIN); } // Verify tx Merkle root uint merkle = SyscoinMessageLibrary.getHeaderMerkleRoot(_blockHeaderBytes); if (SyscoinMessageLibrary.computeMerkle(_txHash, _txIndex, _siblings) != merkle) { emit VerifyTransaction(bytes32(_txHash), ERR_MERKLE_ROOT); return (ERR_MERKLE_ROOT); } emit VerifyTransaction(bytes32(_txHash), 1); return (1); } // @dev - Calculate superblock hash from superblock data // // @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock // @param _accumulatedWork Accumulated proof of work of the last block in the superblock // @param _timestamp Timestamp of the last block in the superblock // @param _prevTimestamp Timestamp of the block when the last difficulty adjustment happened (every 360 blocks) // @param _lastHash Hash of the last block in the superblock // @param _lastBits Difficulty bits of the last block in the superblock // @param _parentId Id of the parent superblock // @param _blockHeight Block height of last block in superblock // @return Superblock id function calcSuperblockHash( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, uint32 _blockHeight ) public pure returns (bytes32) { return keccak256(abi.encodePacked( _blocksMerkleRoot, _accumulatedWork, _timestamp, _prevTimestamp, _lastHash, _lastBits, _parentId, _blockHeight )); } // @dev - Returns the confirmed superblock with the most accumulated work // // @return Best superblock hash function getBestSuperblock() public view returns (bytes32) { return bestSuperblock; } // @dev - Returns the superblock data for the supplied superblock hash // // @return { // bytes32 _blocksMerkleRoot, // uint _accumulatedWork, // uint _timestamp, // uint _prevTimestamp, // bytes32 _lastHash, // uint32 _lastBits, // bytes32 _parentId, // address _submitter, // Status _status, // uint32 _blockHeight, // } Superblock data function getSuperblock(bytes32 superblockHash) public view returns ( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, address _submitter, Status _status, uint32 _blockHeight ) { SuperblockInfo storage superblock = superblocks[superblockHash]; return ( superblock.blocksMerkleRoot, superblock.accumulatedWork, superblock.timestamp, superblock.prevTimestamp, superblock.lastHash, superblock.lastBits, superblock.parentId, superblock.submitter, superblock.status, superblock.blockHeight ); } // @dev - Returns superblock height function getSuperblockHeight(bytes32 superblockHash) public view returns (uint32) { return superblocks[superblockHash].height; } // @dev - Returns superblock internal index function getSuperblockIndex(bytes32 superblockHash) public view returns (uint32) { return superblocks[superblockHash].index; } // @dev - Return superblock ancestors' indexes function getSuperblockAncestors(bytes32 superblockHash) public view returns (bytes32) { return superblocks[superblockHash].ancestors; } // @dev - Return superblock blocks' Merkle root function getSuperblockMerkleRoot(bytes32 _superblockHash) public view returns (bytes32) { return superblocks[_superblockHash].blocksMerkleRoot; } // @dev - Return superblock timestamp function getSuperblockTimestamp(bytes32 _superblockHash) public view returns (uint) { return superblocks[_superblockHash].timestamp; } // @dev - Return superblock prevTimestamp function getSuperblockPrevTimestamp(bytes32 _superblockHash) public view returns (uint) { return superblocks[_superblockHash].prevTimestamp; } // @dev - Return superblock last block hash function getSuperblockLastHash(bytes32 _superblockHash) public view returns (bytes32) { return superblocks[_superblockHash].lastHash; } // @dev - Return superblock parent function getSuperblockParentId(bytes32 _superblockHash) public view returns (bytes32) { return superblocks[_superblockHash].parentId; } // @dev - Return superblock accumulated work function getSuperblockAccumulatedWork(bytes32 _superblockHash) public view returns (uint) { return superblocks[_superblockHash].accumulatedWork; } // @dev - Return superblock status function getSuperblockStatus(bytes32 _superblockHash) public view returns (Status) { return superblocks[_superblockHash].status; } // @dev - Return indexNextSuperblock function getIndexNextSuperblock() public view returns (uint32) { return indexNextSuperblock; } // @dev - Calculate Merkle root from Syscoin block hashes function makeMerkle(bytes32[] hashes) public pure returns (bytes32) { return SyscoinMessageLibrary.makeMerkle(hashes); } function isApproved(bytes32 _superblockHash) public view returns (bool) { return (getSuperblockStatus(_superblockHash) == Status.Approved); } function getChainHeight() public view returns (uint) { return superblocks[bestSuperblock].height; } // @dev - write `_fourBytes` into `_word` starting from `_position` // This is useful for writing 32bit ints inside one 32 byte word // // @param _word - information to be partially overwritten // @param _position - position to start writing from // @param _eightBytes - information to be written function writeUint32(bytes32 _word, uint _position, uint32 _fourBytes) private pure returns (bytes32) { bytes32 result; assembly { let pointer := mload(0x40) mstore(pointer, _word) mstore8(add(pointer, _position), byte(28, _fourBytes)) mstore8(add(pointer, add(_position,1)), byte(29, _fourBytes)) mstore8(add(pointer, add(_position,2)), byte(30, _fourBytes)) mstore8(add(pointer, add(_position,3)), byte(31, _fourBytes)) result := mload(pointer) } return result; } uint constant ANCESTOR_STEP = 5; uint constant NUM_ANCESTOR_DEPTHS = 8; // @dev - Update ancestor to the new height function updateAncestors(bytes32 ancestors, uint32 index, uint height) internal pure returns (bytes32) { uint step = ANCESTOR_STEP; ancestors = writeUint32(ancestors, 0, index); uint i = 1; while (i<NUM_ANCESTOR_DEPTHS && (height % step == 1)) { ancestors = writeUint32(ancestors, 4*i, index); step *= ANCESTOR_STEP; ++i; } return ancestors; } // @dev - Returns a list of superblock hashes (9 hashes maximum) that helps an agent find out what // superblocks are missing. // The first position contains bestSuperblock, then // bestSuperblock - 1, // (bestSuperblock-1) - ((bestSuperblock-1) % 5), then // (bestSuperblock-1) - ((bestSuperblock-1) % 25), ... until // (bestSuperblock-1) - ((bestSuperblock-1) % 78125) // // @return - list of up to 9 ancestor supeerblock id function getSuperblockLocator() public view returns (bytes32[9]) { bytes32[9] memory locator; locator[0] = bestSuperblock; bytes32 ancestors = getSuperblockAncestors(bestSuperblock); uint i = NUM_ANCESTOR_DEPTHS; while (i > 0) { locator[i] = indexSuperblock[uint32(ancestors & 0xFFFFFFFF)]; ancestors >>= 32; --i; } return locator; } // @dev - Return ancestor at given index function getSuperblockAncestor(bytes32 superblockHash, uint index) internal view returns (bytes32) { bytes32 ancestors = superblocks[superblockHash].ancestors; uint32 ancestorsIndex = uint32(ancestors[4*index + 0]) * 0x1000000 + uint32(ancestors[4*index + 1]) * 0x10000 + uint32(ancestors[4*index + 2]) * 0x100 + uint32(ancestors[4*index + 3]) * 0x1; return indexSuperblock[ancestorsIndex]; } // dev - returns depth associated with an ancestor index; applies to any superblock // // @param _index - index of ancestor to be looked up; an integer between 0 and 7 // @return - depth corresponding to said index, i.e. 5**index function getAncDepth(uint _index) private pure returns (uint) { return ANCESTOR_STEP**(uint(_index)); } // @dev - return superblock hash at a given height in superblock main chain // // @param _height - superblock height // @return - hash corresponding to block of height _blockHeight function getSuperblockAt(uint _height) public view returns (bytes32) { bytes32 superblockHash = bestSuperblock; uint index = NUM_ANCESTOR_DEPTHS - 1; while (getSuperblockHeight(superblockHash) > _height) { while (getSuperblockHeight(superblockHash) - _height < getAncDepth(index) && index > 0) { index -= 1; } superblockHash = getSuperblockAncestor(superblockHash, index); } return superblockHash; } // @dev - Checks if a superblock is in superblock main chain // // @param _blockHash - hash of the block being searched for in the main chain // @return - true if the block identified by _blockHash is in the main chain, // false otherwise function inMainChain(bytes32 _superblockHash) internal view returns (bool) { uint height = getSuperblockHeight(_superblockHash); if (height == 0) return false; return (getSuperblockAt(height) == _superblockHash); } }
get final position of inputs, outputs and lock time this is a helper function to slice a byte array and hash the inputs, outputs and lock time
function getSlicePos(bytes memory txBytes, uint pos) private pure returns (uint slicePos) { slicePos = skipInputs(txBytes, pos + 4); slicePos = skipOutputs(txBytes, slicePos); }
5,531,909
./partial_match/137/0x83006b5c56F909A97256a5678Fcc54E2b444528d/sources/contracts/STOA.sol
Returns the total available rewards given the current period See _calculateRewardForPeriod();
function getRewardForPeriod() external view returns (uint256 totalRewards) { return _calculateRewardForPeriod(); }
3,522,141
pragma solidity 0.5.16; /* is IERC20 */ interface IERC4626Vault { /// @notice The address of the underlying token used for the Vault uses for accounting, depositing, and withdrawing function asset() external view returns (address assetTokenAddress); /// @notice Total amount of the underlying asset that is “managed” by Vault function totalAssets() external view returns (uint256 totalManagedAssets); /** * @notice The amount of shares that the Vault would exchange for the amount of assets provided, in an ideal scenario where all the conditions are met. * @param assets The amount of underlying assets to be convert to vault shares. * @return shares The amount of vault shares converted from the underlying assets. */ function convertToShares(uint256 assets) external view returns (uint256 shares); /** * @notice The amount of assets that the Vault would exchange for the amount of shares provided, in an ideal scenario where all the conditions are met. * @param shares The amount of vault shares to be converted to the underlying assets. * @return assets The amount of underlying assets converted from the vault shares. */ function convertToAssets(uint256 shares) external view returns (uint256 assets); /** * @notice The maximum number of underlying assets that caller can deposit. * @param caller Account that the assets will be transferred from. * @return maxAssets The maximum amount of underlying assets the caller can deposit. */ function maxDeposit(address caller) external view returns (uint256 maxAssets); /** * @notice Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions. * @param assets The amount of underlying assets to be transferred. * @return shares The amount of vault shares that will be minted. */ function previewDeposit(uint256 assets) external view returns (uint256 shares); /** * @notice Mint vault shares to receiver by transferring exact amount of underlying asset tokens from the caller. * @param assets The amount of underlying assets to be transferred to the vault. * @param receiver The account that the vault shares will be minted to. * @return shares The amount of vault shares that were minted. */ function deposit(uint256 assets, address receiver) external returns (uint256 shares); /** * @notice The maximum number of vault shares that caller can mint. * @param caller Account that the underlying assets will be transferred from. * @return maxShares The maximum amount of vault shares the caller can mint. */ function maxMint(address caller) external view returns (uint256 maxShares); /** * @notice Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given current on-chain conditions. * @param shares The amount of vault shares to be minted. * @return assets The amount of underlying assests that will be transferred from the caller. */ function previewMint(uint256 shares) external view returns (uint256 assets); /** * @notice Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller. * @param shares The amount of vault shares to be minted. * @param receiver The account the vault shares will be minted to. * @return assets The amount of underlying assets that were transferred from the caller. */ function mint(uint256 shares, address receiver) external returns (uint256 assets); /** * @notice The maximum number of underlying assets that owner can withdraw. * @param owner Account that owns the vault shares. * @return maxAssets The maximum amount of underlying assets the owner can withdraw. */ function maxWithdraw(address owner) external view returns (uint256 maxAssets); /** * @notice Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions. * @param assets The amount of underlying assets to be withdrawn. * @return shares The amount of vault shares that will be burnt. */ function previewWithdraw(uint256 assets) external view returns (uint256 shares); /** * @notice Burns enough vault shares from owner and transfers the exact amount of underlying asset tokens to the receiver. * @param assets The amount of underlying assets to be withdrawn from the vault. * @param receiver The account that the underlying assets will be transferred to. * @param owner Account that owns the vault shares to be burnt. * @return shares The amount of vault shares that were burnt. */ function withdraw( uint256 assets, address receiver, address owner ) external returns (uint256 shares); /** * @notice The maximum number of shares an owner can redeem for underlying assets. * @param owner Account that owns the vault shares. * @return maxShares The maximum amount of shares the owner can redeem. */ function maxRedeem(address owner) external view returns (uint256 maxShares); /** * @notice Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, given current on-chain conditions. * @param shares The amount of vault shares to be burnt. * @return assets The amount of underlying assests that will transferred to the receiver. */ function previewRedeem(uint256 shares) external view returns (uint256 assets); /** * @notice Burns exact amount of vault shares from owner and transfers the underlying asset tokens to the receiver. * @param shares The amount of vault shares to be burnt. * @param receiver The account the underlying assets will be transferred to. * @param owner The account that owns the vault shares to be burnt. * @return assets The amount of underlying assets that were transferred to the receiver. */ function redeem( uint256 shares, address receiver, address owner ) external returns (uint256 assets); /*/////////////////////////////////////////////////////////////// Events //////////////////////////////////////////////////////////////*/ /** * @dev Emitted when caller has exchanged assets for shares, and transferred those shares to owner. * * Note It must be emitted when tokens are deposited into the Vault in ERC4626.mint or ERC4626.deposit methods. * */ event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares); /** * @dev Emitted when sender has exchanged shares for assets, and transferred those assets to receiver. * * Note It must be emitted when shares are withdrawn from the Vault in ERC4626.redeem or ERC4626.withdraw methods. * */ event Withdraw( address indexed caller, address indexed receiver, address indexed owner, uint256 assets, uint256 shares ); } interface IUnwrapper { // @dev Get bAssetOut status function getIsBassetOut( address _masset, bool _inputIsCredit, address _output ) external view returns (bool isBassetOut); /// @dev Estimate output function getUnwrapOutput( bool _isBassetOut, address _router, address _input, bool _inputIsCredit, address _output, uint256 _amount ) external view returns (uint256 output); /// @dev Unwrap and send function unwrapAndSend( bool _isBassetOut, address _router, address _input, address _output, uint256 _amount, uint256 _minAmountOut, address _beneficiary ) external returns (uint256 outputQuantity); } interface ISavingsManager { /** @dev Admin privs */ function distributeUnallocatedInterest(address _mAsset) external; /** @dev Liquidator */ function depositLiquidation(address _mAsset, uint256 _liquidation) external; /** @dev Liquidator */ function collectAndStreamInterest(address _mAsset) external; /** @dev Public privs */ function collectAndDistributeInterest(address _mAsset) external; } interface ISavingsContractV1 { function depositInterest(uint256 _amount) external; function depositSavings(uint256 _amount) external returns (uint256 creditsIssued); function redeem(uint256 _amount) external returns (uint256 massetReturned); function exchangeRate() external view returns (uint256); function creditBalances(address) external view returns (uint256); } interface ISavingsContractV4 { // DEPRECATED but still backwards compatible function redeem(uint256 _amount) external returns (uint256 massetReturned); function creditBalances(address) external view returns (uint256); // V1 & V2 (use balanceOf) // -------------------------------------------- function depositInterest(uint256 _amount) external; // V1 & V2 function depositSavings(uint256 _amount) external returns (uint256 creditsIssued); // V1 & V2 function depositSavings(uint256 _amount, address _beneficiary) external returns (uint256 creditsIssued); // V2 function redeemCredits(uint256 _amount) external returns (uint256 underlyingReturned); // V2 function redeemUnderlying(uint256 _amount) external returns (uint256 creditsBurned); // V2 function exchangeRate() external view returns (uint256); // V1 & V2 function balanceOfUnderlying(address _user) external view returns (uint256 balance); // V2 function underlyingToCredits(uint256 _credits) external view returns (uint256 underlying); // V2 function creditsToUnderlying(uint256 _underlying) external view returns (uint256 credits); // V2 // -------------------------------------------- function redeemAndUnwrap( uint256 _amount, bool _isCreditAmt, uint256 _minAmountOut, address _output, address _beneficiary, address _router, bool _isBassetOut ) external returns ( uint256 creditsBurned, uint256 massetRedeemed, uint256 outputQuantity ); function depositSavings( uint256 _underlying, address _beneficiary, address _referrer ) external returns (uint256 creditsIssued); // -------------------------------------------- V4 function deposit( uint256 assets, address receiver, address referrer ) external returns (uint256 shares); function mint( uint256 shares, address receiver, address referrer ) external returns (uint256 assets); } /* * @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. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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); } /** * @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; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public 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 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 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 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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _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 { require(account != address(0), "ERC20: mint to the zero address"); _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 { require(account != address(0), "ERC20: burn from the zero address"); _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 { 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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance") ); } } contract InitializableERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize( string memory nameArg, string memory symbolArg, uint8 decimalsArg ) internal { _name = nameArg; _symbol = symbolArg; _decimals = decimalsArg; } /** * @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. * * 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; } } contract InitializableToken is ERC20, InitializableERC20Detailed { /** * @dev Initialization function for implementing contract * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize(string memory _nameArg, string memory _symbolArg) internal { InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18); } } contract ModuleKeys { // Governance // =========== // keccak256("Governance"); bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d; //keccak256("Staking"); bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034; //keccak256("ProxyAdmin"); bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1; // mStable // ======= // keccak256("OracleHub"); bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040; // keccak256("Manager"); bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f; //keccak256("Recollateraliser"); bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f; //keccak256("MetaToken"); bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2; // keccak256("SavingsManager"); bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1; // keccak256("Liquidator"); bytes32 internal constant KEY_LIQUIDATOR = 0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4; } interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } contract InitializableModule2 is ModuleKeys { INexus public constant nexus = INexus(0xAFcE80b19A8cE13DEc0739a1aaB7A028d6845Eb3); /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { require(msg.sender == _governor(), "Only governor can execute"); _; } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Modifier to allow function calls only from the ProxyAdmin. */ modifier onlyProxyAdmin() { require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute"); _; } /** * @dev Modifier to allow function calls only from the Manager. */ modifier onlyManager() { require(msg.sender == _manager(), "Only manager can execute"); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Staking Module address from the Nexus * @return Address of the Staking Module contract */ function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } /** * @dev Return MetaToken Module address from the Nexus * @return Address of the MetaToken Module contract */ function _metaToken() internal view returns (address) { return nexus.getModule(KEY_META_TOKEN); } /** * @dev Return OracleHub Module address from the Nexus * @return Address of the OracleHub Module contract */ function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); } /** * @dev Return Manager Module address from the Nexus * @return Address of the Manager Module contract */ function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } } interface IConnector { /** * @notice Deposits the mAsset into the connector * @param _amount Units of mAsset to receive and deposit */ function deposit(uint256 _amount) external; /** * @notice Withdraws a specific amount of mAsset from the connector * @param _amount Units of mAsset to withdraw */ function withdraw(uint256 _amount) external; /** * @notice Withdraws all mAsset from the connector */ function withdrawAll() external; /** * @notice Returns the available balance in the connector. In connections * where there is likely to be an initial dip in value due to conservative * exchange rates (e.g. with Curves `get_virtual_price`), it should return * max(deposited, balance) to avoid temporary negative yield. Any negative yield * should be corrected during a withdrawal or over time. * @return Balance of mAsset in the connector */ function checkBalance() external view returns (uint256); } 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; } 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; /** * @notice 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 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 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; } } /** * @title SavingsContract * @author Stability Labs Pty. Ltd. * @notice Savings contract uses the ever increasing "exchangeRate" to increase * the value of the Savers "credits" (ERC20) relative to the amount of additional * underlying collateral that has been deposited into this contract ("interest") * @dev VERSION: 2.1 * DATE: 2021-11-25 */ contract SavingsContract_imusd_mainnet_22 is ISavingsContractV1, ISavingsContractV4, IERC4626Vault, Initializable, InitializableToken, InitializableModule2 { using SafeMath for uint256; using StableMath for uint256; // Core events for depositing and withdrawing event ExchangeRateUpdated(uint256 newExchangeRate, uint256 interestCollected); event SavingsDeposited(address indexed saver, uint256 savingsDeposited, uint256 creditsIssued); event CreditsRedeemed( address indexed redeemer, uint256 creditsRedeemed, uint256 savingsCredited ); event AutomaticInterestCollectionSwitched(bool automationEnabled); // Connector poking event PokerUpdated(address poker); event FractionUpdated(uint256 fraction); event ConnectorUpdated(address connector); event EmergencyUpdate(); event Poked(uint256 oldBalance, uint256 newBalance, uint256 interestDetected); event PokedRaw(); // Tracking events event Referral(address indexed referrer, address beneficiary, uint256 amount); // Rate between 'savings credits' and underlying // e.g. 1 credit (1e17) mulTruncate(exchangeRate) = underlying, starts at 10:1 // exchangeRate increases over time uint256 private constant startingRate = 1e17; uint256 public exchangeRate; // Underlying asset is underlying IERC20 public constant underlying = IERC20(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5); bool private automateInterestCollection; // Yield // Poker is responsible for depositing/withdrawing from connector address public poker; // Last time a poke was made uint256 public lastPoke; // Last known balance of the connector uint256 public lastBalance; // Fraction of capital assigned to the connector (100% = 1e18) uint256 public fraction; // Address of the current connector (all IConnectors are mStable validated) IConnector public connector; // How often do we allow pokes uint256 private constant POKE_CADENCE = 4 hours; // Max APY generated on the capital in the connector uint256 private constant MAX_APY = 4e18; uint256 private constant SECONDS_IN_YEAR = 365 days; // Proxy contract for easy redemption address public constant unwrapper = 0xc1443Cb9ce81915fB914C270d74B0D57D1c87be0; uint256 private constant MAX_INT256 = 2**256 - 1; // Add these constants to bytecode at deploytime function initialize( address _poker, string calldata _nameArg, string calldata _symbolArg ) external initializer { InitializableToken._initialize(_nameArg, _symbolArg); require(_poker != address(0), "Invalid poker address"); poker = _poker; fraction = 2e17; automateInterestCollection = true; exchangeRate = startingRate; } /** @dev Only the savings managaer (pulled from Nexus) can execute this */ modifier onlySavingsManager() { require(msg.sender == _savingsManager(), "Only savings manager can execute"); _; } /*************************************** VIEW - E ****************************************/ /** * @dev Returns the underlying balance of a given user * @param _user Address of the user to check * @return balance Units of underlying owned by the user */ function balanceOfUnderlying(address _user) external view returns (uint256 balance) { (balance, ) = _creditsToUnderlying(balanceOf(_user)); } /** * @dev Converts a given underlying amount into credits * @param _underlying Units of underlying * @return credits Credit units (a.k.a imUSD) */ function underlyingToCredits(uint256 _underlying) external view returns (uint256 credits) { (credits, ) = _underlyingToCredits(_underlying); } /** * @dev Converts a given credit amount into underlying * @param _credits Units of credits * @return amount Corresponding underlying amount */ function creditsToUnderlying(uint256 _credits) external view returns (uint256 amount) { (amount, ) = _creditsToUnderlying(_credits); } // Deprecated in favour of `balanceOf(address)` // Maintained for backwards compatibility // Returns the credit balance of a given user function creditBalances(address _user) external view returns (uint256) { return balanceOf(_user); } /*************************************** INTEREST ****************************************/ /** * @dev Deposit interest (add to savings) and update exchange rate of contract. * Exchange rate is calculated as the ratio between new savings q and credits: * exchange rate = savings / credits * * @param _amount Units of underlying to add to the savings vault */ function depositInterest(uint256 _amount) external onlySavingsManager { require(_amount > 0, "Must deposit something"); // Transfer the interest from sender to here require(underlying.transferFrom(msg.sender, address(this), _amount), "Must receive tokens"); // Calc new exchange rate, protect against initialisation case uint256 totalCredits = totalSupply(); if (totalCredits > 0) { // new exchange rate is relationship between _totalCredits & totalSavings // _totalCredits * exchangeRate = totalSavings // exchangeRate = totalSavings/_totalCredits (uint256 totalCollat, ) = _creditsToUnderlying(totalCredits); uint256 newExchangeRate = _calcExchangeRate(totalCollat.add(_amount), totalCredits); exchangeRate = newExchangeRate; emit ExchangeRateUpdated(newExchangeRate, _amount); } } /** @dev Enable or disable the automation of fee collection during deposit process */ function automateInterestCollectionFlag(bool _enabled) external onlyGovernor { automateInterestCollection = _enabled; emit AutomaticInterestCollectionSwitched(_enabled); } /*************************************** DEPOSIT ****************************************/ /** * @dev During a migration period, allow savers to deposit underlying here before the interest has been redirected * @param _underlying Units of underlying to deposit into savings vault * @param _beneficiary Immediately transfer the imUSD token to this beneficiary address * @return creditsIssued Units of credits (imUSD) issued */ function preDeposit(uint256 _underlying, address _beneficiary) external returns (uint256 creditsIssued) { require(exchangeRate == startingRate, "Can only use this method before streaming begins"); return _deposit(_underlying, _beneficiary, false); } /** * @dev Deposit the senders savings to the vault, and credit them internally with "credits". * Credit amount is calculated as a ratio of deposit amount and exchange rate: * credits = underlying / exchangeRate * We will first update the internal exchange rate by collecting any interest generated on the underlying. * @param _underlying Units of underlying to deposit into savings vault * @return creditsIssued Units of credits (imUSD) issued */ function depositSavings(uint256 _underlying) external returns (uint256 creditsIssued) { return _deposit(_underlying, msg.sender, true); } /** * @dev Deposit the senders savings to the vault, and credit them internally with "credits". * Credit amount is calculated as a ratio of deposit amount and exchange rate: * credits = underlying / exchangeRate * We will first update the internal exchange rate by collecting any interest generated on the underlying. * @param _underlying Units of underlying to deposit into savings vault * @param _beneficiary Immediately transfer the imUSD token to this beneficiary address * @return creditsIssued Units of credits (imUSD) issued */ function depositSavings(uint256 _underlying, address _beneficiary) external returns (uint256 creditsIssued) { return _deposit(_underlying, _beneficiary, true); } /** * @dev Overloaded `depositSavings` method with an optional referrer address. * @param _underlying Units of underlying to deposit into savings vault * @param _beneficiary Immediately transfer the imUSD token to this beneficiary address * @param _referrer Referrer address for this deposit * @return creditsIssued Units of credits (imUSD) issued */ function depositSavings( uint256 _underlying, address _beneficiary, address _referrer ) external returns (uint256 creditsIssued) { emit Referral(_referrer, _beneficiary, _underlying); return _deposit(_underlying, _beneficiary, true); } /** * @dev Internally deposit the _underlying from the sender and credit the beneficiary with new imUSD */ function _deposit( uint256 _underlying, address _beneficiary, bool _collectInterest ) internal returns (uint256 creditsIssued) { creditsIssued = _transferAndMint(_underlying, _beneficiary, _collectInterest); } /*************************************** REDEEM ****************************************/ // Deprecated in favour of redeemCredits // Maintaining backwards compatibility, this fn minimics the old redeem fn, in which // credits are redeemed but the interest from the underlying is not collected. function redeem(uint256 _credits) external returns (uint256 massetReturned) { require(_credits > 0, "Must withdraw something"); (, uint256 payout) = _redeem(_credits, true, true); // Collect recent interest generated by basket and update exchange rate if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } return payout; } /** * @dev Redeem specific number of the senders "credits" in exchange for underlying. * Payout amount is calculated as a ratio of credits and exchange rate: * payout = credits * exchangeRate * @param _credits Amount of credits to redeem * @return massetReturned Units of underlying mAsset paid out */ function redeemCredits(uint256 _credits) external returns (uint256 massetReturned) { require(_credits > 0, "Must withdraw something"); // Collect recent interest generated by basket and update exchange rate if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } (, uint256 payout) = _redeem(_credits, true, true); return payout; } /** * @dev Redeem credits into a specific amount of underlying. * Credits needed to burn is calculated using: * credits = underlying / exchangeRate * @param _underlying Amount of underlying to redeem * @return creditsBurned Units of credits burned from sender */ function redeemUnderlying(uint256 _underlying) external returns (uint256 creditsBurned) { require(_underlying > 0, "Must withdraw something"); // Collect recent interest generated by basket and update exchange rate if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } // Ensure that the payout was sufficient (uint256 credits, uint256 massetReturned) = _redeem(_underlying, false, true); require(massetReturned == _underlying, "Invalid output"); return credits; } /** * @notice Redeem credits into a specific amount of underlying, unwrap * into a selected output asset, and send to a beneficiary * Credits needed to burn is calculated using: * credits = underlying / exchangeRate * @param _amount Units to redeem (either underlying or credit amount). * @param _isCreditAmt `true` if `amount` is in credits. eg imUSD. `false` if `amount` is in underlying. eg mUSD. * @param _minAmountOut Minimum amount of `output` tokens to unwrap for. This is to the same decimal places as the `output` token. * @param _output Asset to receive in exchange for the redeemed mAssets. This can be a bAsset or a fAsset. For example: - bAssets (USDC, DAI, sUSD or USDT) or fAssets (GUSD, BUSD, alUSD, FEI or RAI) for mainnet imUSD Vault. - bAssets (USDC, DAI or USDT) or fAsset FRAX for Polygon imUSD Vault. - bAssets (WBTC, sBTC or renBTC) or fAssets (HBTC or TBTCV2) for mainnet imBTC Vault. * @param _beneficiary Address to send `output` tokens to. * @param _router mAsset address if the output is a bAsset. Feeder Pool address if the output is a fAsset. * @param _isBassetOut `true` if `output` is a bAsset. `false` if `output` is a fAsset. * @return creditsBurned Units of credits burned from sender. eg imUSD or imBTC. * @return massetReturned Units of the underlying mAssets that were redeemed or swapped for the output tokens. eg mUSD or mBTC. * @return outputQuantity Units of `output` tokens sent to the beneficiary. */ function redeemAndUnwrap( uint256 _amount, bool _isCreditAmt, uint256 _minAmountOut, address _output, address _beneficiary, address _router, bool _isBassetOut ) external returns ( uint256 creditsBurned, uint256 massetReturned, uint256 outputQuantity ) { require(_amount > 0, "Must withdraw something"); require(_output != address(0), "Output address is zero"); require(_beneficiary != address(0), "Beneficiary address is zero"); require(_router != address(0), "Router address is zero"); // Collect recent interest generated by basket and update exchange rate if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } // Ensure that the payout was sufficient (creditsBurned, massetReturned) = _redeem(_amount, _isCreditAmt, false); require( _isCreditAmt ? creditsBurned == _amount : massetReturned == _amount, "Invalid output" ); // Approve wrapper to spend contract's underlying; just for this tx underlying.approve(unwrapper, massetReturned); // Unwrap the underlying into `output` and transfer to `beneficiary` outputQuantity = IUnwrapper(unwrapper).unwrapAndSend( _isBassetOut, _router, address(underlying), _output, massetReturned, _minAmountOut, _beneficiary ); } /** * @dev Internally burn the credits and send the underlying to msg.sender */ function _redeem( uint256 _amt, bool _isCreditAmt, bool _transferUnderlying ) internal returns (uint256 creditsBurned, uint256 massetReturned) { // Centralise credit <> underlying calcs and minimise SLOAD count uint256 credits_; uint256 underlying_; uint256 exchangeRate_; // If the input is a credit amt, then calculate underlying payout and cache the exchangeRate if (_isCreditAmt) { credits_ = _amt; (underlying_, exchangeRate_) = _creditsToUnderlying(_amt); } // If the input is in underlying, then calculate credits needed to burn else { underlying_ = _amt; (credits_, exchangeRate_) = _underlyingToCredits(_amt); } _burnTransfer( underlying_, credits_, msg.sender, msg.sender, exchangeRate_, _transferUnderlying ); emit CreditsRedeemed(msg.sender, credits_, underlying_); return (credits_, underlying_); } struct ConnectorStatus { // Limit is the max amount of units allowed in the connector uint256 limit; // Derived balance of the connector uint256 inConnector; } /** * @dev Derives the units of collateral held in the connector * @param _data Struct containing data on balances * @param _exchangeRate Current system exchange rate * @return status Contains max amount of assets allowed in connector */ function _getConnectorStatus(CachedData memory _data, uint256 _exchangeRate) internal pure returns (ConnectorStatus memory) { // Total units of underlying collateralised uint256 totalCollat = _data.totalCredits.mulTruncate(_exchangeRate); // Max amount of underlying that can be held in the connector uint256 limit = totalCollat.mulTruncate(_data.fraction.add(2e17)); // Derives amount of underlying present in the connector uint256 inConnector = _data.rawBalance >= totalCollat ? 0 : totalCollat.sub(_data.rawBalance); return ConnectorStatus(limit, inConnector); } /*************************************** YIELD - E ****************************************/ /** @dev Modifier allowing only the designated poker to execute the fn */ modifier onlyPoker() { require(msg.sender == poker, "Only poker can execute"); _; } /** * @dev External poke function allows for the redistribution of collateral between here and the * current connector, setting the ratio back to the defined optimal. */ function poke() external onlyPoker { CachedData memory cachedData = _cacheData(); _poke(cachedData, false); } /** * @dev Governance action to set the address of a new poker * @param _newPoker Address of the new poker */ function setPoker(address _newPoker) external onlyGovernor { require(_newPoker != address(0) && _newPoker != poker, "Invalid poker"); poker = _newPoker; emit PokerUpdated(_newPoker); } /** * @dev Governance action to set the percentage of assets that should be held * in the connector. * @param _fraction Percentage of assets that should be held there (where 20% == 2e17) */ function setFraction(uint256 _fraction) external onlyGovernor { require(_fraction <= 5e17, "Fraction must be <= 50%"); fraction = _fraction; CachedData memory cachedData = _cacheData(); _poke(cachedData, true); emit FractionUpdated(_fraction); } /** * @dev Governance action to set the address of a new connector, and move funds (if any) across. * @param _newConnector Address of the new connector */ function setConnector(address _newConnector) external onlyGovernor { // Withdraw all from previous by setting target = 0 CachedData memory cachedData = _cacheData(); cachedData.fraction = 0; _poke(cachedData, true); // Set new connector CachedData memory cachedDataNew = _cacheData(); connector = IConnector(_newConnector); _poke(cachedDataNew, true); emit ConnectorUpdated(_newConnector); } /** * @dev Governance action to perform an emergency withdraw of the assets in the connector, * should it be the case that some or all of the liquidity is trapped in. This causes the total * collateral in the system to go down, causing a hard refresh. */ function emergencyWithdraw(uint256 _withdrawAmount) external onlyGovernor { // withdraw _withdrawAmount from connection connector.withdraw(_withdrawAmount); // reset the connector connector = IConnector(address(0)); emit ConnectorUpdated(address(0)); // set fraction to 0 fraction = 0; emit FractionUpdated(0); // check total collateralisation of credits CachedData memory data = _cacheData(); // use rawBalance as the remaining liquidity in the connector is now written off _refreshExchangeRate(data.rawBalance, data.totalCredits, true); emit EmergencyUpdate(); } /*************************************** YIELD - I ****************************************/ /** @dev Internal poke function to keep the balance between connector and raw balance healthy */ function _poke(CachedData memory _data, bool _ignoreCadence) internal { require(_data.totalCredits > 0, "Must have something to poke"); // 1. Verify that poke cadence is valid, unless this is a manual action by governance uint256 currentTime = uint256(now); uint256 timeSinceLastPoke = currentTime.sub(lastPoke); require(_ignoreCadence || timeSinceLastPoke > POKE_CADENCE, "Not enough time elapsed"); lastPoke = currentTime; // If there is a connector, check the balance and settle to the specified fraction % IConnector connector_ = connector; if (address(connector_) != address(0)) { // 2. Check and verify new connector balance uint256 lastBalance_ = lastBalance; uint256 connectorBalance = connector_.checkBalance(); // Always expect the collateral in the connector to increase in value require(connectorBalance >= lastBalance_, "Invalid yield"); if (connectorBalance > 0) { // Validate the collection by ensuring that the APY is not ridiculous _validateCollection( connectorBalance, connectorBalance.sub(lastBalance_), timeSinceLastPoke ); } // 3. Level the assets to Fraction (connector) & 100-fraction (raw) uint256 sum = _data.rawBalance.add(connectorBalance); uint256 ideal = sum.mulTruncate(_data.fraction); // If there is not enough mAsset in the connector, then deposit if (ideal > connectorBalance) { uint256 deposit = ideal.sub(connectorBalance); underlying.approve(address(connector_), deposit); connector_.deposit(deposit); } // Else withdraw, if there is too much mAsset in the connector else if (connectorBalance > ideal) { // If fraction == 0, then withdraw everything if (ideal == 0) { connector_.withdrawAll(); sum = IERC20(underlying).balanceOf(address(this)); } else { connector_.withdraw(connectorBalance.sub(ideal)); } } // Else ideal == connectorBalance (e.g. 0), do nothing require(connector_.checkBalance() >= ideal, "Enforce system invariant"); // 4i. Refresh exchange rate and emit event lastBalance = ideal; _refreshExchangeRate(sum, _data.totalCredits, false); emit Poked(lastBalance_, ideal, connectorBalance.sub(lastBalance_)); } else { // 4ii. Refresh exchange rate and emit event lastBalance = 0; _refreshExchangeRate(_data.rawBalance, _data.totalCredits, false); emit PokedRaw(); } } /** * @dev Internal fn to refresh the exchange rate, based on the sum of collateral and the number of credits * @param _realSum Sum of collateral held by the contract * @param _totalCredits Total number of credits in the system * @param _ignoreValidation This is for use in the emergency situation, and ignores a decreasing exchangeRate */ function _refreshExchangeRate( uint256 _realSum, uint256 _totalCredits, bool _ignoreValidation ) internal { // Based on the current exchange rate, how much underlying is collateralised? (uint256 totalCredited, ) = _creditsToUnderlying(_totalCredits); // Require the amount of capital held to be greater than the previously credited units require(_ignoreValidation || _realSum >= totalCredited, "ExchangeRate must increase"); // Work out the new exchange rate based on the current capital uint256 newExchangeRate = _calcExchangeRate(_realSum, _totalCredits); exchangeRate = newExchangeRate; emit ExchangeRateUpdated( newExchangeRate, _realSum > totalCredited ? _realSum.sub(totalCredited) : 0 ); } /** * FORKED DIRECTLY FROM SAVINGSMANAGER.sol * --------------------------------------- * @dev Validates that an interest collection does not exceed a maximum APY. If last collection * was under 30 mins ago, simply check it does not exceed 10bps * @param _newBalance New balance of the underlying * @param _interest Increase in total supply since last collection * @param _timeSinceLastCollection Seconds since last collection */ function _validateCollection( uint256 _newBalance, uint256 _interest, uint256 _timeSinceLastCollection ) internal pure returns (uint256 extrapolatedAPY) { // Protect against division by 0 uint256 protectedTime = StableMath.max(1, _timeSinceLastCollection); uint256 oldSupply = _newBalance.sub(_interest); uint256 percentageIncrease = _interest.divPrecisely(oldSupply); uint256 yearsSinceLastCollection = protectedTime.divPrecisely(SECONDS_IN_YEAR); extrapolatedAPY = percentageIncrease.divPrecisely(yearsSinceLastCollection); if (protectedTime > 30 minutes) { require(extrapolatedAPY < MAX_APY, "Interest protected from inflating past maxAPY"); } else { require(percentageIncrease < 1e15, "Interest protected from inflating past 10 Bps"); } } /*************************************** VIEW - I ****************************************/ struct CachedData { // SLOAD from 'fraction' uint256 fraction; // ERC20 balance of underlying, held by this contract // underlying.balanceOf(address(this)) uint256 rawBalance; // totalSupply() uint256 totalCredits; } /** * @dev Retrieves generic data to avoid duplicate SLOADs */ function _cacheData() internal view returns (CachedData memory) { uint256 balance = underlying.balanceOf(address(this)); return CachedData(fraction, balance, totalSupply()); } /** * @dev Converts masset amount into credits based on exchange rate * c = (masset / exchangeRate) + 1 */ function _underlyingToCredits(uint256 _underlying) internal view returns (uint256 credits, uint256 exchangeRate_) { // e.g. (1e20 * 1e18) / 1e18 = 1e20 // e.g. (1e20 * 1e18) / 14e17 = 7.1429e19 // e.g. 1 * 1e18 / 1e17 + 1 = 11 => 11 * 1e17 / 1e18 = 1.1e18 / 1e18 = 1 exchangeRate_ = exchangeRate; credits = _underlying.divPrecisely(exchangeRate_).add(1); } /** * @dev Works out a new exchange rate, given an amount of collateral and total credits * e = underlying / (credits-1) */ function _calcExchangeRate(uint256 _totalCollateral, uint256 _totalCredits) internal pure returns (uint256 _exchangeRate) { _exchangeRate = _totalCollateral.divPrecisely(_totalCredits.sub(1)); } /** * @dev Converts credit amount into masset based on exchange rate * m = credits * exchangeRate */ function _creditsToUnderlying(uint256 _credits) internal view returns (uint256 underlyingAmount, uint256 exchangeRate_) { // e.g. (1e20 * 1e18) / 1e18 = 1e20 // e.g. (1e20 * 14e17) / 1e18 = 1.4e20 exchangeRate_ = exchangeRate; underlyingAmount = _credits.mulTruncate(exchangeRate_); } /*/////////////////////////////////////////////////////////////// IERC4626Vault //////////////////////////////////////////////////////////////*/ /** * @notice it must be an ERC-20 token contract. Must not revert. * * @return assetTokenAddress the address of the underlying asset token. eg mUSD or mBTC */ function asset() external view returns (address assetTokenAddress) { return address(underlying); } /** * @return totalManagedAssets the total amount of the underlying asset tokens that is “managed” by Vault. */ function totalAssets() external view returns (uint256 totalManagedAssets) { return underlying.balanceOf(address(this)); } /** * @notice The amount of shares that the Vault would exchange for the amount of assets provided, in an ideal scenario where all the conditions are met. * @param assets The amount of underlying assets to be convert to vault shares. * @return shares The amount of vault shares converted from the underlying assets. */ function convertToShares(uint256 assets) external view returns (uint256 shares) { (shares, ) = _underlyingToCredits(assets); } /** * @notice The amount of assets that the Vault would exchange for the amount of shares provided, in an ideal scenario where all the conditions are met. * @param shares The amount of vault shares to be converted to the underlying assets. * @return assets The amount of underlying assets converted from the vault shares. */ function convertToAssets(uint256 shares) external view returns (uint256 assets) { (assets, ) = _creditsToUnderlying(shares); } /** * @notice The maximum number of underlying assets that caller can deposit. * caller Account that the assets will be transferred from. * @return maxAssets The maximum amount of underlying assets the caller can deposit. */ function maxDeposit( address /** caller **/ ) external view returns (uint256 maxAssets) { maxAssets = MAX_INT256; } /** * @notice Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions. * @param assets The amount of underlying assets to be transferred. * @return shares The amount of vault shares that will be minted. */ function previewDeposit(uint256 assets) external view returns (uint256 shares) { require(assets > 0, "Must deposit something"); (shares, ) = _underlyingToCredits(assets); } /** * @notice Mint vault shares to receiver by transferring exact amount of underlying asset tokens from the caller. * Credit amount is calculated as a ratio of deposit amount and exchange rate: * credits = underlying / exchangeRate * We will first update the internal exchange rate by collecting any interest generated on the underlying. * Emits a {Deposit} event. * @param assets Units of underlying to deposit into savings vault. eg mUSD or mBTC * @param receiver The address to receive the Vault shares. * @return shares Units of credits issued. eg imUSD or imBTC */ function deposit(uint256 assets, address receiver) external returns (uint256 shares) { shares = _transferAndMint(assets, receiver, true); } /** * * @notice Overloaded `deposit` method with an optional referrer address. * @param assets Units of underlying to deposit into savings vault. eg mUSD or mBTC * @param receiver Address to the new credits will be issued to. * @param referrer Referrer address for this deposit. * @return shares Units of credits issued. eg imUSD or imBTC */ function deposit( uint256 assets, address receiver, address referrer ) external returns (uint256 shares) { shares = _transferAndMint(assets, receiver, true); emit Referral(referrer, receiver, assets); } /** * @notice The maximum number of vault shares that caller can mint. * caller Account that the underlying assets will be transferred from. * @return maxShares The maximum amount of vault shares the caller can mint. */ function maxMint( address /* caller */ ) external view returns (uint256 maxShares) { maxShares = MAX_INT256; } /** * @notice Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given current on-chain conditions. * @param shares The amount of vault shares to be minted. * @return assets The amount of underlying assests that will be transferred from the caller. */ function previewMint(uint256 shares) external view returns (uint256 assets) { (assets, ) = _creditsToUnderlying(shares); return assets; } /** * @notice Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller. * Emits a {Deposit} event. * * @param shares The amount of vault shares to be minted. * @param receiver The account the vault shares will be minted to. * @return assets The amount of underlying assets that were transferred from the caller. */ function mint(uint256 shares, address receiver) external returns (uint256 assets) { (assets, ) = _creditsToUnderlying(shares); _transferAndMint(assets, receiver, true); } /** * @notice Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller. * @param shares The amount of vault shares to be minted. * @param receiver The account the vault shares will be minted to. * @param referrer Referrer address for this deposit. * @return assets The amount of underlying assets that were transferred from the caller. * Emits a {Deposit}, {Referral} events */ function mint( uint256 shares, address receiver, address referrer ) external returns (uint256 assets) { (assets, ) = _creditsToUnderlying(shares); _transferAndMint(assets, receiver, true); emit Referral(referrer, receiver, assets); } /** * @notice The maximum number of underlying assets that owner can withdraw. * @param owner Address that owns the underlying assets. * @return maxAssets The maximum amount of underlying assets the owner can withdraw. */ function maxWithdraw(address owner) external view returns (uint256 maxAssets) { (maxAssets, ) = _creditsToUnderlying(balanceOf(owner)); } /** * @notice Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions. * @param assets The amount of underlying assets to be withdrawn. * @return shares The amount of vault shares that will be burnt. */ function previewWithdraw(uint256 assets) external view returns (uint256 shares) { (shares, ) = _underlyingToCredits(assets); } /** * @notice Burns enough vault shares from owner and transfers the exact amount of underlying asset tokens to the receiver. * Emits a {Withdraw} event. * * @param assets The amount of underlying assets to be withdrawn from the vault. * @param receiver The account that the underlying assets will be transferred to. * @param owner Account that owns the vault shares to be burnt. * @return shares The amount of vault shares that were burnt. */ function withdraw( uint256 assets, address receiver, address owner ) external returns (uint256 shares) { require(assets > 0, "Must withdraw something"); uint256 _exchangeRate; if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } (shares, _exchangeRate) = _underlyingToCredits(assets); _burnTransfer(assets, shares, receiver, owner, _exchangeRate, true); } /** * @notice it must return a limited value if owner is subject to some withdrawal limit or timelock. must return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock. MAY be used in the previewRedeem or redeem methods for shares input parameter. must NOT revert. * * @param owner Address that owns the shares. * @return maxShares Total number of shares that owner can redeem. */ function maxRedeem(address owner) external view returns (uint256 maxShares) { maxShares = balanceOf(owner); } /** * @notice Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, given current on-chain conditions. * * @return assets the exact amount of underlying assets that would be withdrawn by the caller if redeeming a given exact amount of Vault shares using the redeem method */ function previewRedeem(uint256 shares) external view returns (uint256 assets) { (assets, ) = _creditsToUnderlying(shares); return assets; } /** * @notice Burns exact amount of vault shares from owner and transfers the underlying asset tokens to the receiver. * Emits a {Withdraw} event. * * @param shares The amount of vault shares to be burnt. * @param receiver The account the underlying assets will be transferred to. * @param owner The account that owns the vault shares to be burnt. * @return assets The amount of underlying assets that were transferred to the receiver. */ function redeem( uint256 shares, address receiver, address owner ) external returns (uint256 assets) { require(shares > 0, "Must withdraw something"); uint256 _exchangeRate; if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } (assets, _exchangeRate) = _creditsToUnderlying(shares); _burnTransfer(assets, shares, receiver, owner, _exchangeRate, true); //transferAssets=true } /*/////////////////////////////////////////////////////////////// INTERNAL DEPOSIT/MINT //////////////////////////////////////////////////////////////*/ function _transferAndMint( uint256 assets, address receiver, bool _collectInterest ) internal returns (uint256 shares) { require(assets > 0, "Must deposit something"); require(receiver != address(0), "Invalid beneficiary address"); // Collect recent interest generated by basket and update exchange rate IERC20 mAsset = underlying; if (_collectInterest) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(mAsset)); } // Transfer tokens from sender to here require(mAsset.transferFrom(msg.sender, address(this), assets), "Must receive tokens"); // Calc how many credits they receive based on currentRatio (shares, ) = _underlyingToCredits(assets); // add credits to ERC20 balances _mint(receiver, shares); emit Deposit(msg.sender, receiver, assets, shares); emit SavingsDeposited(receiver, assets, shares); } /*/////////////////////////////////////////////////////////////// INTERNAL WITHDRAW/REDEEM //////////////////////////////////////////////////////////////*/ function _burnTransfer( uint256 assets, uint256 shares, address receiver, address owner, uint256 _exchangeRate, bool transferAssets ) internal { require(receiver != address(0), "Invalid beneficiary address"); // If caller is not the owner of the shares uint256 allowed = allowance(owner, msg.sender); if (msg.sender != owner && allowed != MAX_INT256) { require(shares <= allowed, "Amount exceeds allowance"); _approve(owner, msg.sender, allowed - shares); } // Burn required shares from the owner FIRST _burn(owner, shares); // Optionally, transfer tokens from here to receiver if (transferAssets) { require(underlying.transfer(receiver, assets), "Must send tokens"); emit Withdraw(msg.sender, receiver, owner, assets, shares); } // If this withdrawal pushes the portion of stored collateral in the `connector` over a certain // threshold (fraction + 20%), then this should trigger a _poke on the connector. This is to avoid // a situation in which there is a rush on withdrawals for some reason, causing the connector // balance to go up and thus having too large an exposure. CachedData memory cachedData = _cacheData(); ConnectorStatus memory status = _getConnectorStatus(cachedData, _exchangeRate); if (status.inConnector > status.limit) { _poke(cachedData, false); } } }
Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller. shares The amount of vault shares to be minted. receiver The account the vault shares will be minted to. referrer Referrer address for this deposit. return assets The amount of underlying assets that were transferred from the caller. Emits a {Deposit}, {Referral} events/
function mint( uint256 shares, address receiver, address referrer ) external returns (uint256 assets) { (assets, ) = _creditsToUnderlying(shares); _transferAndMint(assets, receiver, true); emit Referral(referrer, receiver, assets); }
2,367,698
// contracts/GameToken.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./access/ManagerControl.sol"; import "./access/MinterControl.sol"; contract GameToken is ERC20, ManagerControl, MinterControl { uint8 public constant DECIMALS = 7; uint256 public constant INITIAL_SUPPLY = 1000000000000000; constructor() ERC20("BOSAGORA", "GBOA") { _mint(_msgSender(), INITIAL_SUPPLY); } function decimals() public view virtual override returns (uint8) { return DECIMALS; } /** * @dev See {IERC20-transferFrom}. * * Requirements: * * - the caller must have a minter role. */ function mint(address account, uint256 amount) public onlyRole(MINTER_ROLE) returns (bool) { _mint(account, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Requirements: * * - the caller must have a minter role. */ function burn(address from, uint256 amount) public onlyRole(MINTER_ROLE) returns (bool) { _burn(from, amount); return true; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. * - the manager must be included in the 'caller' or 'to'. */ function transfer(address to, uint256 amount) public virtual override includedManager(MANAGER_ROLE, to) returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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`. * - the manager must be included in the 'from' or 'to'. */ function transferFrom( address from, address to, uint256 amount ) public virtual override includedManager(MANAGER_ROLE, to) returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @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. * - the manager must be included in the 'caller' or 'sender'. */ function approve(address spender, uint256 amount) public virtual override includedManager(MANAGER_ROLE, spender) returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } }
See {IERC20-transferFrom}. Requirements: - the caller must have a minter role./
function burn(address from, uint256 amount) public onlyRole(MINTER_ROLE) returns (bool) { _burn(from, amount); return true; }
12,651,941
./partial_match/1/0x59BC239cAb00CADd9b14f299835ae39E8B4B569c/sources/contracts/protocol/libraries/configuration/ReserveConfiguration.sol
Gets the configuration flags of the reserve from a memory object 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 ); }
15,931,734
./full_match/43113/0xf8BD1920cDD944758771e789474dfb5b5e3F8a0B/sources/contracts/RelayManager2.sol
Send (mint) funds to the receiver to process cross-chain transfer `depositHash = keccak256(abi.encodePacked(senderAddress, tokenAddress, nonce))`/ Mark the depositHash state true to avoid double sending Calculate adminFee Calculate total used gas price for sending Calculate real amount to transfer considering adminFee and gasFee Mint tokens
function send( address receiver, uint256 amount, bytes32 depositHash, uint256 gasPrice ) external nonReentrant onlyOperator { uint256 initialGas = gasleft(); require(receiver != address(0), "RelayManager2: RECEIVER_ZERO_ADDRESS"); require(amount > 0, "RelayManager2: SEND_AMOUNT_INVALID"); bytes32 hash = keccak256(abi.encodePacked(depositHash, address(wIDO), receiver, amount)); require(!processedHashes[hash], "RelayManager2: ALREADY_PROCESSED"); processedHashes[depositHash] = true; uint256 calculatedAdminFee = amount * adminFee / 10000; adminFeeAccumulated += calculatedAdminFee; uint256 totalGasUsed = initialGas - gasleft(); totalGasUsed += baseGas; gasFeeAccumulated += totalGasUsed * gasPrice; uint256 amountToTransfer = amount - calculatedAdminFee - totalGasUsed * gasPrice; wIDO.mint(receiver, amountToTransfer); emit Sent(receiver, amount, amountToTransfer, depositHash); } |_____________________*/
13,168,742
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IUnlockRegistry.sol"; import "../commons/OperationManaged.sol"; contract UnlockRegistry is OperationManaged, IUnlockRegistry { // mapping for liquidity contributors mapping(uint256 => LiquidityInfo) private liquidityContributors; function _removeFromMapping( LiquidityInfo storage t, address _sender ) private { // remove from array uint256 index = t.index[_sender]; // remove last and place it in current deleted item address lastItem = t.senders[t.senders.length - 1]; // set last item in place of deleted t.senders[index] = lastItem; t.senders.pop(); // update index map t.index[lastItem] = index; // delete removed address from index map delete t.index[_msgSender()]; // remove previous contribution t.total -= t.contributions[_sender]; } function _addToMapping( LiquidityInfo storage t, address _sender, uint256 _amount ) private { // save contributor address t.contributions[_sender] = _amount; t.index[_sender] = t.senders.length; // add contributor to senders list t.senders.push(_sender); // add to total t.total += _amount; } function getContributorsFor(uint256 _tokenId) external view override returns (address[] memory) { return liquidityContributors[_tokenId].senders; } function getSenderContributionFor(address _sender, uint256 _tokenId) external view override returns (uint256 contribution) { return liquidityContributors[_tokenId].contributions[_sender]; } function clearContributorsFor(uint256 _tokenId) external override onlyOperationManager { delete liquidityContributors[_tokenId]; } /** * Adds contribution to unlock * @param _tokenId tokenId to liquidate * @param _sender sender of the contribution * @param _amount liquidity provided to contribution * @param _tokenIdMaxAmount min amount fot the asset thats needed to unlock */ function addContribution( uint256 _tokenId, address _sender, uint256 _amount, uint256 _tokenIdMaxAmount ) external override onlyOperationManager returns (uint256, bool) { LiquidityInfo storage t = liquidityContributors[_tokenId]; // refund prev contribution uint256 refund = t.contributions[_sender]; if (refund > 0) { _removeFromMapping(t, _sender); } // checks if total amount > max allowed and refund uint256 postContribution = t.total + _amount; if (postContribution > _tokenIdMaxAmount) { refund += postContribution - _tokenIdMaxAmount; _amount = _tokenIdMaxAmount - t.total; } _addToMapping(t, _sender, _amount); emit LiquidityContribution(_sender, _tokenId, _amount); // return if contribution is completed return (refund, t.total == _tokenIdMaxAmount); } }
Adds contribution to unlock _tokenId tokenId to liquidate _sender sender of the contribution _amount liquidity provided to contribution _tokenIdMaxAmount min amount fot the asset thats needed to unlock/ refund prev contribution
function addContribution( uint256 _tokenId, address _sender, uint256 _amount, uint256 _tokenIdMaxAmount ) external override onlyOperationManager returns (uint256, bool) { LiquidityInfo storage t = liquidityContributors[_tokenId]; uint256 refund = t.contributions[_sender]; if (refund > 0) { _removeFromMapping(t, _sender); } if (postContribution > _tokenIdMaxAmount) { refund += postContribution - _tokenIdMaxAmount; _amount = _tokenIdMaxAmount - t.total; } _addToMapping(t, _sender, _amount); emit LiquidityContribution(_sender, _tokenId, _amount); }
15,820,654
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IMasterChef.sol"; import "./interfaces/IVault.sol"; import "./interfaces/ILockManager.sol"; import "./interfaces/IERC20Extended.sol"; import "./lib/SafeERC20.sol"; import "./lib/ReentrancyGuard.sol"; /** * @title RewardsManager * @dev Controls rewards distribution for network */ contract RewardsManager is ReentrancyGuard { using SafeERC20 for IERC20Extended; /// @notice Current owner of this contract address public owner; /// @notice Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardTokenDebt; // Reward debt for reward token. See explanation below. uint256 sushiRewardDebt; // Reward debt for Sushi rewards. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of reward tokens // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRewardsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accRewardsPerShare` (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. } /// @notice Info of each pool. struct PoolInfo { IERC20Extended token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Reward tokens to distribute per block. uint256 lastRewardBlock; // Last block number where reward tokens were distributed. uint256 accRewardsPerShare; // Accumulated reward tokens per share, times 1e12. See below. uint32 vestingPercent; // Percentage of rewards that vest (measured in bips: 500,000 bips = 50% of rewards) uint16 vestingPeriod; // Vesting period in days for vesting rewards uint16 vestingCliff; // Vesting cliff in days for vesting rewards uint256 totalStaked; // Total amount of token staked via Rewards Manager bool vpForDeposit; // Do users get voting power for deposits of this token? bool vpForVesting; // Do users get voting power for vesting balances? } /// @notice Reward token IERC20Extended public rewardToken; /// @notice SUSHI token IERC20Extended public sushiToken; /// @notice Sushi Master Chef IMasterChef public masterChef; /// @notice Vault for vesting tokens IVault public vault; /// @notice LockManager contract ILockManager public lockManager; /// @notice Reward tokens rewarded per block. uint256 public rewardTokensPerBlock; /// @notice Info of each pool. PoolInfo[] public poolInfo; /// @notice Mapping of Sushi tokens to MasterChef pids mapping (address => uint256) public sushiPools; /// @notice Info of each user that stakes tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; /// @notice Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; /// @notice The block number when rewards start. uint256 public startBlock; /// @notice only owner can call function modifier onlyOwner { require(msg.sender == owner, "not owner"); _; } /// @notice Event emitted when a user deposits funds in the rewards manager event Deposit(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when a user withdraws their original funds + rewards from the rewards manager event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when a user withdraws their original funds from the rewards manager without claiming rewards event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when new pool is added to the rewards manager event PoolAdded(uint256 indexed pid, address indexed token, uint256 allocPoints, uint256 totalAllocPoints, uint256 rewardStartBlock, uint256 sushiPid, bool vpForDeposit, bool vpForVesting); /// @notice Event emitted when pool allocation points are updated event PoolUpdated(uint256 indexed pid, uint256 oldAllocPoints, uint256 newAllocPoints, uint256 newTotalAllocPoints); /// @notice Event emitted when the owner of the rewards manager contract is updated event ChangedOwner(address indexed oldOwner, address indexed newOwner); /// @notice Event emitted when the amount of reward tokens per block is updated event ChangedRewardTokensPerBlock(uint256 indexed oldRewardTokensPerBlock, uint256 indexed newRewardTokensPerBlock); /// @notice Event emitted when the rewards start block is set event SetRewardsStartBlock(uint256 indexed startBlock); /// @notice Event emitted when contract address is changed event ChangedAddress(string indexed addressType, address indexed oldAddress, address indexed newAddress); /** * @notice Create a new Rewards Manager contract * @param _owner owner of contract * @param _lockManager address of LockManager contract * @param _vault address of Vault contract * @param _rewardToken address of token that is being offered as a reward * @param _sushiToken address of SUSHI token * @param _masterChef address of SushiSwap MasterChef contract * @param _startBlock block number when rewards will start * @param _rewardTokensPerBlock initial amount of reward tokens to be distributed per block */ constructor( address _owner, address _lockManager, address _vault, address _rewardToken, address _sushiToken, address _masterChef, uint256 _startBlock, uint256 _rewardTokensPerBlock ) { owner = _owner; emit ChangedOwner(address(0), _owner); lockManager = ILockManager(_lockManager); emit ChangedAddress("LOCK_MANAGER", address(0), _lockManager); vault = IVault(_vault); emit ChangedAddress("VAULT", address(0), _vault); rewardToken = IERC20Extended(_rewardToken); emit ChangedAddress("REWARD_TOKEN", address(0), _rewardToken); sushiToken = IERC20Extended(_sushiToken); emit ChangedAddress("SUSHI_TOKEN", address(0), _sushiToken); masterChef = IMasterChef(_masterChef); emit ChangedAddress("MASTER_CHEF", address(0), _masterChef); startBlock = _startBlock == 0 ? block.number : _startBlock; emit SetRewardsStartBlock(startBlock); rewardTokensPerBlock = _rewardTokensPerBlock; emit ChangedRewardTokensPerBlock(0, _rewardTokensPerBlock); rewardToken.safeIncreaseAllowance(address(vault), type(uint256).max); } /** * @notice View function to see current poolInfo array length * @return pool length */ function poolLength() external view returns (uint256) { return poolInfo.length; } /** * @notice Add a new reward token to the pool * @dev Can only be called by the owner. DO NOT add the same token more than once. Rewards will be messed up if you do. * @param allocPoint Number of allocation points to allot to this token/pool * @param token The token that will be staked for rewards * @param vestingPercent The percentage of rewards from this pool that will vest * @param vestingPeriod The number of days for the vesting period * @param vestingCliff The number of days for the vesting cliff * @param withUpdate if specified, update all pools before adding new pool * @param sushiPid The pid of the Sushiswap pool in the Masterchef contract (if exists, otherwise provide zero) * @param vpForDeposit If true, users get voting power for deposits * @param vpForVesting If true, users get voting power for vesting balances */ function add( uint256 allocPoint, address token, uint32 vestingPercent, uint16 vestingPeriod, uint16 vestingCliff, bool withUpdate, uint256 sushiPid, bool vpForDeposit, bool vpForVesting ) external onlyOwner { if (withUpdate) { massUpdatePools(); } uint256 rewardStartBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + allocPoint; poolInfo.push(PoolInfo({ token: IERC20Extended(token), allocPoint: allocPoint, lastRewardBlock: rewardStartBlock, accRewardsPerShare: 0, vestingPercent: vestingPercent, vestingPeriod: vestingPeriod, vestingCliff: vestingCliff, totalStaked: 0, vpForDeposit: vpForDeposit, vpForVesting: vpForVesting })); if (sushiPid != uint256(0)) { sushiPools[token] = sushiPid; IERC20Extended(token).safeIncreaseAllowance(address(masterChef), type(uint256).max); } IERC20Extended(token).safeIncreaseAllowance(address(vault), type(uint256).max); emit PoolAdded(poolInfo.length - 1, token, allocPoint, totalAllocPoint, rewardStartBlock, sushiPid, vpForDeposit, vpForVesting); } /** * @notice Update the given pool's allocation points * @dev Can only be called by the owner * @param pid The RewardManager pool id * @param allocPoint New number of allocation points for pool * @param withUpdate if specified, update all pools before setting allocation points */ function set( uint256 pid, uint256 allocPoint, bool withUpdate ) external onlyOwner { if (withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[pid].allocPoint + allocPoint; emit PoolUpdated(pid, poolInfo[pid].allocPoint, allocPoint, totalAllocPoint); poolInfo[pid].allocPoint = allocPoint; } /** * @notice Returns true if rewards are actively being accumulated */ function rewardsActive() public view returns (bool) { return block.number >= startBlock && totalAllocPoint > 0 ? true : false; } /** * @notice Return reward multiplier over the given from to to block. * @param from From block number * @param to To block number * @return multiplier */ function getMultiplier(uint256 from, uint256 to) public pure returns (uint256) { return to > from ? to - from : 0; } /** * @notice View function to see pending reward tokens on frontend. * @param pid pool id * @param account user account to check * @return pending rewards */ function pendingRewardTokens(uint256 pid, address account) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][account]; uint256 accRewardsPerShare = pool.accRewardsPerShare; uint256 tokenSupply = pool.totalStaked; if (block.number > pool.lastRewardBlock && tokenSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 totalReward = multiplier * rewardTokensPerBlock * pool.allocPoint / totalAllocPoint; accRewardsPerShare = accRewardsPerShare + totalReward * 1e12 / tokenSupply; } uint256 accumulatedRewards = user.amount * accRewardsPerShare / 1e12; if (accumulatedRewards < user.rewardTokenDebt) { return 0; } return accumulatedRewards - user.rewardTokenDebt; } /** * @notice View function to see pending SUSHI on frontend. * @param pid pool id * @param account user account to check * @return pending SUSHI rewards */ function pendingSushi(uint256 pid, address account) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][account]; uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid == uint256(0)) { return 0; } IMasterChef.PoolInfo memory sushiPool = masterChef.poolInfo(sushiPid); uint256 sushiPerBlock = masterChef.sushiPerBlock(); uint256 totalSushiAllocPoint = masterChef.totalAllocPoint(); uint256 accSushiPerShare = sushiPool.accSushiPerShare; uint256 lpSupply = sushiPool.lpToken.balanceOf(address(masterChef)); if (block.number > sushiPool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = masterChef.getMultiplier(sushiPool.lastRewardBlock, block.number); uint256 sushiReward = multiplier * sushiPerBlock * sushiPool.allocPoint / totalSushiAllocPoint; accSushiPerShare = accSushiPerShare + sushiReward * 1e12 / lpSupply; } uint256 accumulatedSushi = user.amount * accSushiPerShare / 1e12; if (accumulatedSushi < user.sushiRewardDebt) { return 0; } return accumulatedSushi - user.sushiRewardDebt; } /** * @notice Update reward variables for all pools * @dev Be careful of gas spending! */ function massUpdatePools() public { for (uint256 pid = 0; pid < poolInfo.length; ++pid) { updatePool(pid); } } /** * @notice Update reward variables of the given pool to be up-to-date * @param pid pool id */ function updatePool(uint256 pid) public { PoolInfo storage pool = poolInfo[pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 tokenSupply = pool.totalStaked; if (tokenSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 totalReward = multiplier * rewardTokensPerBlock * pool.allocPoint / totalAllocPoint; pool.accRewardsPerShare = pool.accRewardsPerShare + totalReward * 1e12 / tokenSupply; pool.lastRewardBlock = block.number; } /** * @notice Deposit tokens to RewardsManager for rewards allocation. * @param pid pool id * @param amount number of tokens to deposit */ function deposit(uint256 pid, uint256 amount) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _deposit(pid, amount, pool, user); } /** * @notice Deposit tokens to RewardsManager for rewards allocation, using permit for approval * @dev It is up to the frontend developer to ensure the pool token implements permit - otherwise this will fail * @param pid pool id * @param amount number of tokens to deposit * @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 depositWithPermit( uint256 pid, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; pool.token.permit(msg.sender, address(this), amount, deadline, v, r, s); _deposit(pid, amount, pool, user); } /** * @notice Withdraw tokens from RewardsManager, claiming rewards. * @param pid pool id * @param amount number of tokens to withdraw */ function withdraw(uint256 pid, uint256 amount) external nonReentrant { require(amount > 0, "RM::withdraw: amount must be > 0"); PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _withdraw(pid, amount, pool, user); } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. * @param pid pool id */ function emergencyWithdraw(uint256 pid) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; if (user.amount > 0) { uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid != uint256(0)) { masterChef.withdraw(sushiPid, user.amount); } if (pool.vpForDeposit) { lockManager.removeVotingPower(msg.sender, address(pool.token), user.amount); } pool.totalStaked = pool.totalStaked - user.amount; pool.token.safeTransfer(msg.sender, user.amount); emit EmergencyWithdraw(msg.sender, pid, user.amount); user.amount = 0; user.rewardTokenDebt = 0; user.sushiRewardDebt = 0; } } /** * @notice Set approvals for external addresses to use contract tokens * @dev Can only be called by the owner * @param tokensToApprove the tokens to approve * @param approvalAmounts the token approval amounts * @param spender the address to allow spending of token */ function tokenAllow( address[] memory tokensToApprove, uint256[] memory approvalAmounts, address spender ) external onlyOwner { require(tokensToApprove.length == approvalAmounts.length, "RM::tokenAllow: not same length"); for(uint i = 0; i < tokensToApprove.length; i++) { IERC20Extended token = IERC20Extended(tokensToApprove[i]); if (token.allowance(address(this), spender) != type(uint256).max) { token.safeApprove(spender, approvalAmounts[i]); } } } /** * @notice Rescue (withdraw) tokens from the smart contract * @dev Can only be called by the owner * @param tokens the tokens to withdraw * @param amounts the amount of each token to withdraw. If zero, withdraws the maximum allowed amount for each token * @param receiver the address that will receive the tokens */ function rescueTokens( address[] calldata tokens, uint256[] calldata amounts, address receiver ) external onlyOwner { require(tokens.length == amounts.length, "RM::rescueTokens: not same length"); for (uint i = 0; i < tokens.length; i++) { IERC20Extended token = IERC20Extended(tokens[i]); uint256 withdrawalAmount; uint256 tokenBalance = token.balanceOf(address(this)); uint256 tokenAllowance = token.allowance(address(this), receiver); if (amounts[i] == 0) { if (tokenBalance > tokenAllowance) { withdrawalAmount = tokenAllowance; } else { withdrawalAmount = tokenBalance; } } else { require(tokenBalance >= amounts[i], "RM::rescueTokens: contract balance too low"); require(tokenAllowance >= amounts[i], "RM::rescueTokens: increase token allowance"); withdrawalAmount = amounts[i]; } token.safeTransferFrom(address(this), receiver, withdrawalAmount); } } /** * @notice Set new rewards per block * @dev Can only be called by the owner * @param newRewardTokensPerBlock new amount of reward token to reward each block */ function setRewardsPerBlock(uint256 newRewardTokensPerBlock) external onlyOwner { emit ChangedRewardTokensPerBlock(rewardTokensPerBlock, newRewardTokensPerBlock); rewardTokensPerBlock = newRewardTokensPerBlock; } /** * @notice Set new SUSHI token address * @dev Can only be called by the owner * @param newToken address of new SUSHI token */ function setSushiToken(address newToken) external onlyOwner { emit ChangedAddress("SUSHI_TOKEN", address(sushiToken), newToken); sushiToken = IERC20Extended(newToken); } /** * @notice Set new MasterChef address * @dev Can only be called by the owner * @param newAddress address of new MasterChef */ function setMasterChef(address newAddress) external onlyOwner { emit ChangedAddress("MASTER_CHEF", address(masterChef), newAddress); masterChef = IMasterChef(newAddress); } /** * @notice Set new Vault address * @param newAddress address of new Vault */ function setVault(address newAddress) external onlyOwner { emit ChangedAddress("VAULT", address(vault), newAddress); vault = IVault(newAddress); } /** * @notice Set new LockManager address * @param newAddress address of new LockManager */ function setLockManager(address newAddress) external onlyOwner { emit ChangedAddress("LOCK_MANAGER", address(lockManager), newAddress); lockManager = ILockManager(newAddress); } /** * @notice Change owner of Rewards Manager contract * @dev Can only be called by the owner * @param newOwner New owner address */ function changeOwner(address newOwner) external onlyOwner { require(newOwner != address(0) && newOwner != address(this), "RM::changeOwner: not valid address"); emit ChangedOwner(owner, newOwner); owner = newOwner; } /** * @notice Internal implementation of deposit * @param pid pool id * @param amount number of tokens to deposit * @param pool the pool info * @param user the user info */ function _deposit( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { updatePool(pid); uint256 sushiPid = sushiPools[address(pool.token)]; uint256 pendingSushiTokens = 0; if (user.amount > 0) { uint256 pendingRewards = user.amount * pool.accRewardsPerShare / 1e12 - user.rewardTokenDebt; if (pendingRewards > 0) { _distributeRewards(msg.sender, pendingRewards, pool.vestingPercent, pool.vestingPeriod, pool.vestingCliff, pool.vpForVesting); } if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); pendingSushiTokens = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12 - user.sushiRewardDebt; } } pool.token.safeTransferFrom(msg.sender, address(this), amount); pool.totalStaked = pool.totalStaked + amount; user.amount = user.amount + amount; user.rewardTokenDebt = user.amount * pool.accRewardsPerShare / 1e12; if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); user.sushiRewardDebt = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12; masterChef.deposit(sushiPid, amount); } if (amount > 0 && pool.vpForDeposit) { lockManager.grantVotingPower(msg.sender, address(pool.token), amount); } if (pendingSushiTokens > 0) { _safeSushiTransfer(msg.sender, pendingSushiTokens); } emit Deposit(msg.sender, pid, amount); } /** * @notice Internal implementation of withdraw * @param pid pool id * @param amount number of tokens to withdraw * @param pool the pool info * @param user the user info */ function _withdraw( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { require(user.amount >= amount, "RM::_withdraw: amount > user balance"); updatePool(pid); uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); uint256 pendingSushiTokens = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12 - user.sushiRewardDebt; masterChef.withdraw(sushiPid, amount); user.sushiRewardDebt = (user.amount - amount) * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12; if (pendingSushiTokens > 0) { _safeSushiTransfer(msg.sender, pendingSushiTokens); } } uint256 pendingRewards = user.amount * pool.accRewardsPerShare / 1e12 - user.rewardTokenDebt; user.amount = user.amount - amount; user.rewardTokenDebt = user.amount * pool.accRewardsPerShare / 1e12; if (pendingRewards > 0) { _distributeRewards(msg.sender, pendingRewards, pool.vestingPercent, pool.vestingPeriod, pool.vestingCliff, pool.vpForVesting); } if (pool.vpForDeposit) { lockManager.removeVotingPower(msg.sender, address(pool.token), amount); } pool.totalStaked = pool.totalStaked - amount; pool.token.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, pid, amount); } /** * @notice Internal function used to distribute rewards, optionally vesting a % * @param account account that is due rewards * @param rewardAmount amount of rewards to distribute * @param vestingPercent percent of rewards to vest in bips * @param vestingPeriod number of days over which to vest rewards * @param vestingCliff number of days for vesting cliff * @param vestingVotingPower if true, grant voting power for vesting balance */ function _distributeRewards( address account, uint256 rewardAmount, uint32 vestingPercent, uint16 vestingPeriod, uint16 vestingCliff, bool vestingVotingPower ) internal { rewardToken.mint(address(this), rewardAmount); uint256 vestingRewards = rewardAmount * vestingPercent / 1000000; if(vestingRewards > 0) { vault.lockTokens(address(rewardToken), address(this), account, 0, vestingRewards, vestingPeriod, vestingCliff, vestingVotingPower); } rewardToken.safeTransfer(msg.sender, rewardAmount - vestingRewards); } /** * @notice Safe SUSHI transfer function, just in case if rounding error causes pool to not have enough SUSHI. * @param to account that is receiving SUSHI * @param amount amount of SUSHI to send */ function _safeSushiTransfer(address to, uint256 amount) internal { uint256 sushiBalance = sushiToken.balanceOf(address(this)); if (amount > sushiBalance) { sushiToken.safeTransfer(to, sushiBalance); } else { sushiToken.safeTransfer(to, amount); } } } // 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"; interface IERC20Burnable is IERC20 { function burn(uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Metadata.sol"; import "./IERC20Mintable.sol"; import "./IERC20Burnable.sol"; import "./IERC20Permit.sol"; import "./IERC20TransferWithAuth.sol"; import "./IERC20SafeAllowance.sol"; interface IERC20Extended is IERC20Metadata, IERC20Mintable, IERC20Burnable, IERC20Permit, IERC20TransferWithAuth, IERC20SafeAllowance {} // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; 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"; interface IERC20Mintable is IERC20 { function mint(address dst, uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20Permit is IERC20 { function getDomainSeparator() external view returns (bytes32); function DOMAIN_TYPEHASH() external view returns (bytes32); function VERSION_HASH() external view returns (bytes32); function PERMIT_TYPEHASH() external view returns (bytes32); function nonces(address) external view returns (uint); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20SafeAllowance is IERC20 { function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20TransferWithAuth is IERC20 { function transferWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external; function receiveWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external; function TRANSFER_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32); function RECEIVE_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32); event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ILockManager { struct LockedStake { uint256 amount; uint256 votingPower; } function getAmountStaked(address staker, address stakedToken) external view returns (uint256); function getStake(address staker, address stakedToken) external view returns (LockedStake memory); function calculateVotingPower(address token, uint256 amount) external view returns (uint256); function grantVotingPower(address receiver, address token, uint256 tokenAmount) external returns (uint256 votingPowerGranted); function removeVotingPower(address receiver, address token, uint256 tokenAmount) external returns (uint256 votingPowerRemoved); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IMasterChef { struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. } function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function poolInfo(uint256 _pid) external view returns (PoolInfo memory); function pendingSushi(uint256 _pid, address _user) external view returns (uint256); function updatePool(uint256 _pid) external; function sushiPerBlock() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IVault { struct Lock { address token; address receiver; uint48 startTime; uint16 vestingDurationInDays; uint16 cliffDurationInDays; uint256 amount; uint256 amountClaimed; uint256 votingPower; } struct LockBalance { uint256 id; uint256 claimableAmount; Lock lock; } struct TokenBalance { uint256 totalAmount; uint256 claimableAmount; uint256 claimedAmount; uint256 votingPower; } function lockTokens(address token, address locker, address receiver, uint48 startTime, uint256 amount, uint16 lockDurationInDays, uint16 cliffDurationInDays, bool grantVotingPower) external; function lockTokensWithPermit(address token, address locker, address receiver, uint48 startTime, uint256 amount, uint16 lockDurationInDays, uint16 cliffDurationInDays, bool grantVotingPower, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function claimUnlockedTokenAmounts(uint256[] memory lockIds, uint256[] memory amounts) external; function claimAllUnlockedTokens(uint256[] memory lockIds) external; function tokenLocks(uint256 lockId) external view returns(Lock memory); function allActiveLockIds() external view returns(uint256[] memory); function allActiveLocks() external view returns(Lock[] memory); function allActiveLockBalances() external view returns(LockBalance[] memory); function activeLockIds(address receiver) external view returns(uint256[] memory); function allLocks(address receiver) external view returns(Lock[] memory); function activeLocks(address receiver) external view returns(Lock[] memory); function activeLockBalances(address receiver) external view returns(LockBalance[] memory); function totalTokenBalance(address token) external view returns(TokenBalance memory balance); function tokenBalance(address token, address receiver) external view returns(TokenBalance memory balance); function lockBalance(uint256 lockId) external view returns (LockBalance memory); function claimableBalance(uint256 lockId) external view returns (uint256); function extendLock(uint256 lockId, uint16 vestingDaysToAdd, uint16 cliffDaysToAdd) external; } // 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; /** * @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 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.8.0; import "../interfaces/IERC20.sol"; import "./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
interface IMasterChef { function getAmountStaked(address staker, address stakedToken) external view returns (uint256); function getStake(address staker, address stakedToken) external view returns (LockedStake memory); function calculateVotingPower(address token, uint256 amount) external view returns (uint256); function grantVotingPower(address receiver, address token, uint256 tokenAmount) external returns (uint256 votingPowerGranted); function removeVotingPower(address receiver, address token, uint256 tokenAmount) external returns (uint256 votingPowerRemoved); } pragma solidity ^0.8.0; import "./IERC20.sol"; struct PoolInfo { } }
13,001,335
pragma solidity ^0.6.1; pragma experimental ABIEncoderV2; import "./ISellerAdmin.sol"; import "./IAddressRegistry.sol"; import "./IBusinessPartnerStorage.sol"; import "./IPurchasing.sol"; import "./IFunding.sol"; import "./Ownable.sol"; import "./Bindable.sol"; import "./StringConvertible.sol"; /// @title SellerAdmin contract SellerAdmin is ISellerAdmin, Ownable, Bindable, StringConvertible { // Global data (shared by all eShops) IBusinessPartnerStorage public businessPartnerStorageGlobal; // Local data (for this Seller) bytes32 public sellerId; bool public isConfigured; constructor (string memory sellerIdString) public { isConfigured = false; sellerId = stringToBytes32(sellerIdString); } modifier onlyConfigured { require(isConfigured == true, "Contract needs configured first"); _; } function configure(address businessPartnerStorageAddressGlobal) override external onlyOwner { businessPartnerStorageGlobal = IBusinessPartnerStorage(businessPartnerStorageAddressGlobal); // Check master data is correct IPoTypes.Seller memory seller = businessPartnerStorageGlobal.getSeller(sellerId); require(seller.sellerId.length > 0, "Seller has no master data"); require(seller.adminContractAddress != address(0), "Seller has no admin contract address"); require(seller.isActive == true, "Seller is inactive"); isConfigured = true; } // Purchasing /// @notice This function can only be called by the eShop (Purchasing.sol) for the given PO, which means: /// 1) SellerAdmin owner must have bound (whitelisted) the Purchasing.sol contract when they registered with the eShop /// 2) msg.sender must match the PO's eShop's purchasing contract address retrieved from global storage function emitEventForNewPo(IPoTypes.Po calldata po) override external onlyConfigured onlyRegisteredCaller { IPoTypes.Eshop memory eShop = getAndValidateEshop(po.eShopId); require(eShop.purchasingContractAddress == msg.sender, "Function can only be called by eShop"); emit QuoteConvertedToPoLog(po.eShopId, po.quoteId, po.buyerWalletAddress); } function getPo(string calldata eShopIdString, uint poNumber) override external view onlyConfigured returns (IPoTypes.Po memory po) { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); return purchasing.getPo(poNumber); } function getPoByEshopIdAndQuote(string calldata eShopIdString, uint quoteId) override external view onlyConfigured returns (IPoTypes.Po memory po) { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); return purchasing.getPoByQuote(quoteId); } function setPoItemAccepted(string calldata eShopIdString, uint poNumber, uint8 poItemNumber, bytes32 soNumber, bytes32 soItemNumber) override external onlyConfigured onlyRegisteredCaller { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemAccepted(poNumber, poItemNumber, soNumber, soItemNumber); } function setPoItemRejected(string calldata eShopIdString, uint poNumber, uint8 poItemNumber) override external onlyConfigured onlyRegisteredCaller { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemRejected(poNumber, poItemNumber); } function setPoItemReadyForGoodsIssue(string calldata eShopIdString, uint poNumber, uint8 poItemNumber) override external onlyConfigured onlyRegisteredCaller { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemReadyForGoodsIssue(poNumber, poItemNumber); } function setPoItemGoodsIssued(string calldata eShopIdString, uint poNumber, uint8 poItemNumber) override external onlyConfigured onlyRegisteredCaller { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemGoodsIssued(poNumber, poItemNumber); } function setPoItemGoodsReceived(string calldata eShopIdString, uint poNumber, uint8 poItemNumber) override external onlyConfigured onlyRegisteredCaller { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemGoodsReceivedSeller(poNumber, poItemNumber); } function setPoItemCompleted(string calldata eShopIdString, uint poNumber, uint8 poItemNumber) override external onlyConfigured onlyRegisteredCaller { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemCompleted(poNumber, poItemNumber); } function getAndValidateEshop(bytes32 eShopId) private view returns (IPoTypes.Eshop memory validShop) { IPoTypes.Eshop memory eShop = businessPartnerStorageGlobal.getEshop(eShopId); require(eShop.purchasingContractAddress != address(0), "eShop has no purchasing address"); require(eShop.quoteSignerCount > 0, "No quote signers found for eShop"); return eShop; } }
Get and validate eShop
function setPoItemAccepted(string calldata eShopIdString, uint poNumber, uint8 poItemNumber, bytes32 soNumber, bytes32 soItemNumber) override external onlyConfigured onlyRegisteredCaller { bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemAccepted(poNumber, poItemNumber, soNumber, soItemNumber); }
13,115,646
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import {Hevm} from "../test/utils/Hevm.sol"; import {DSTest} from "ds-test/test.sol"; import {MockProvider} from "@cleanunicorn/mockprovider/src/MockProvider.sol"; import {Caller} from "../test/utils/Caller.sol"; import {Guarded} from "../guarded/Guarded.sol"; import {ICollybus} from "./ICollybus.sol"; import {Relayer} from "./Relayer.sol"; import {IRelayer} from "./IRelayer.sol"; import {IOracle} from "../oracle/IOracle.sol"; import {ChainlinkValueProvider} from "../oracle_implementations/spot_price/Chainlink/ChainlinkValueProvider.sol"; import {IChainlinkAggregatorV3Interface} from "../oracle_implementations/spot_price/Chainlink/ChainlinkAggregatorV3Interface.sol"; import {CheatCodes} from "../test/utils/CheatCodes.sol"; contract TestCollybus is ICollybus { mapping(bytes32 => uint256) public valueForToken; function updateDiscountRate(uint256 tokenId_, uint256 rate_) external override(ICollybus) { valueForToken[bytes32(uint256(tokenId_))] = rate_; } function updateSpot(address tokenAddress_, uint256 spot_) external override(ICollybus) { valueForToken[bytes32(uint256(uint160(tokenAddress_)))] = spot_; } } contract RelayerTest is DSTest { CheatCodes internal cheatCodes = CheatCodes(HEVM_ADDRESS); Relayer internal relayer; TestCollybus internal collybus; IRelayer.RelayerType internal relayerType = IRelayer.RelayerType.DiscountRate; MockProvider internal oracle; bytes32 private _mockTokenId; uint256 private _mockMinThreshold = 1; int256 private _oracleValue = 100 * 10**18; function setUp() public { collybus = new TestCollybus(); oracle = new MockProvider(); _mockTokenId = bytes32(uint256(1)); // Set the value returned by the Oracle. oracle.givenQueryReturnResponse( abi.encodePacked(IOracle.value.selector), MockProvider.ReturnData({ success: true, data: abi.encode(_oracleValue, true) }), false ); // We can use the same value as the nextValue oracle.givenQueryReturnResponse( abi.encodePacked(IOracle.nextValue.selector), MockProvider.ReturnData({ success: true, data: abi.encode(_oracleValue, true) }), false ); oracle.givenSelectorReturnResponse( Guarded.canCall.selector, MockProvider.ReturnData({success: true, data: abi.encode(true)}), false ); // Set update to return a boolean oracle.givenQueryReturnResponse( abi.encodePacked(IOracle.update.selector), MockProvider.ReturnData({success: true, data: abi.encode(true)}), true ); relayer = new Relayer( address(collybus), relayerType, address(oracle), _mockTokenId, _mockMinThreshold ); } function test_deploy() public { assertTrue( address(relayer) != address(0), "Relayer should be deployed" ); } function test_check_collybus() public { assertEq(relayer.collybus(), address(collybus)); } function test_check_relayerType() public { assertTrue(relayer.relayerType() == relayerType, "Invalid relayerType"); } function test_check_oracle() public { assertTrue( relayer.oracle() == address(oracle), "Invalid oracle address" ); } function test_check_encodedTokenId() public { assertTrue( relayer.encodedTokenId() == _mockTokenId, "Invalid encoded token id" ); } function test_check_minimumPercentageDeltaValue() public { assertTrue( relayer.minimumPercentageDeltaValue() == _mockMinThreshold, "Invalid minimumPercentageDeltaValue" ); } function test_canSetParam_minimumPercentageDeltaValue() public { // Set the minimumPercentageDeltaValue relayer.setParam("minimumPercentageDeltaValue", 10_00); // Check the minimumPercentageDeltaValue assertEq(relayer.minimumPercentageDeltaValue(), 10_00); } function testFail_shouldNotBeAbleToSet_invalidParam() public { relayer.setParam("invalidParam", 100_00); } function test_executeCalls_updateOnOracle() public { // Execute must call update on all oracles before pushing the values to Collybus relayer.execute(); // Update was called for both oracles MockProvider.CallData memory cd = oracle.getCallData(0); assertTrue(cd.functionSelector == IOracle.update.selector); } function test_execute_updateDiscountRateInCollybus() public { relayer.execute(); assertTrue( collybus.valueForToken(_mockTokenId) == uint256(_oracleValue), "Invalid discount rate relayer rate value" ); } function test_execute_updateSpotPriceInCollybus() public { // Create a spot price relayer and check the spot prices in the Collybus bytes32 mockSpotTokenAddress = bytes32(uint256(1)); Relayer spotPriceRelayer = new Relayer( address(collybus), IRelayer.RelayerType.SpotPrice, address(oracle), mockSpotTokenAddress, _mockMinThreshold ); // Update the rates in collybus spotPriceRelayer.execute(); assertTrue( collybus.valueForToken(mockSpotTokenAddress) == uint256(_oracleValue), "Invalid spot price relayer spot value" ); } function test_execute_doesNotUpdatesRatesInCollybusWhenDeltaIsBelowThreshold() public { // Threshold percentage uint256 thresholdPercentage = 50_00; // 50% relayer.setParam("minimumPercentageDeltaValue", thresholdPercentage); // Set the value returned by the Oracle. int256 initialValue = 100; oracle.givenQueryReturnResponse( abi.encodePacked(IOracle.value.selector), MockProvider.ReturnData({ success: true, data: abi.encode(initialValue, true) }), false ); // Make sure the values are updated, start clean relayer.execute(); // The initial value is the value we just defined assertEq( collybus.valueForToken(_mockTokenId), uint256(initialValue), "We should have the initial value" ); // Update the oracle with a new value under the threshold limit int256 secondValue = initialValue + (initialValue * int256(thresholdPercentage)) / 100_00 - 1; oracle.givenQueryReturnResponse( abi.encodePacked(IOracle.value.selector), MockProvider.ReturnData({ success: true, data: abi.encode(secondValue, true) }), false ); // Execute the relayer relayer.execute(); // Make sure the new value was not pushed into Collybus assertEq( collybus.valueForToken(_mockTokenId), uint256(initialValue), "Collybus should not have been updated" ); } function test_execute_updatesRatesInCollybusWhenDeltaIsAboveThreshold() public { // Threshold percentage uint256 thresholdPercentage = 50_00; // 50% relayer.setParam("minimumPercentageDeltaValue", thresholdPercentage); // Set the value returned by the Oracle. int256 initialValue = 100; oracle.givenQueryReturnResponse( abi.encodePacked(IOracle.value.selector), MockProvider.ReturnData({ success: true, data: abi.encode(initialValue, true) }), false ); // Make sure the values are updated, start from `initialValue` relayer.execute(); // The initial value is the value we just defined assertEq( collybus.valueForToken(_mockTokenId), uint256(initialValue), "We should have the initial value" ); // Update the oracle with a new value above the threshold limit int256 secondValue = initialValue + (initialValue * int256(thresholdPercentage)) / 100_00 + 1; oracle.givenQueryReturnResponse( abi.encodePacked(IOracle.value.selector), MockProvider.ReturnData({ success: true, data: abi.encode(secondValue, true) }), false ); // Execute the relayer relayer.execute(); // Make sure the new value was pushed into Collybus assertEq( collybus.valueForToken(_mockTokenId), uint256(secondValue), "Collybus should have the new value" ); } function test_executeWithRevert() public { // Call should not revert relayer.executeWithRevert(); } function test_execute_returnsTrue_whenCollybusIsUpdated() public { bool executed; executed = relayer.execute(); assertTrue(executed, "The relayer should return true"); } function test_execute_returnsFalse_whenCollybusIsNotUpdated() public { bool executed; // The first execute should return true executed = relayer.execute(); assertTrue(executed, "The relayer's execute() should return true"); // The second execute should return false because the Collybus will not be updated executed = relayer.execute(); assertTrue( executed == false, "The relayer execute() should return false" ); } function test_execute_returnsFalse_whenOracleIsNotUpdated() public { // Set `update` to return `false` oracle.givenQueryReturnResponse( abi.encodePacked(IOracle.update.selector), MockProvider.ReturnData({success: true, data: abi.encode(false)}), true ); // When the oracle's `update` returns `false`, the relayer's `execute` should return `false` bool executeReturnedValue = relayer.execute(); assertTrue( executeReturnedValue == false, "The relayer execute() should return false" ); } function test_executeWithRevert_shouldBeSuccessful_onFirstExecution() public { // Call should not revert relayer.executeWithRevert(); } function testFail_executeWithRevert_shouldNotBeSuccessful_whenCollybusIsNotUpdated() public { relayer.execute(); // Call should revert relayer.executeWithRevert(); } function setChainlinkMockReturnedValue( MockProvider mockChainlinkAggregator, int256 value ) internal { mockChainlinkAggregator.givenQueryReturnResponse( abi.encodeWithSelector( IChainlinkAggregatorV3Interface.latestRoundData.selector ), MockProvider.ReturnData({ success: true, data: abi.encode( uint80(0), // roundId value, // answer uint256(0), // startedAt uint256(0), // updatedAt uint80(0) // answeredInRound ) }), false ); } function test_executeWithRevert_canBeUpdatedByKeepers() public { // For this test we will simulate an external actor that must be able to successfully update // the Relayer via multiple `executeWithRevert()` calls. We will do this by providing multiple // mocked Chainlink values and making sure that each value is properly validated and used. int256 firstValue = 1e18; int256 secondValue = 2e18; uint256 timeUpdateWindow = 100; // Test setup, create the mockChainlinkAggregator that will provide data for the Oracle MockProvider mockChainlinkAggregator = new MockProvider(); mockChainlinkAggregator.givenQueryReturnResponse( abi.encodeWithSelector( IChainlinkAggregatorV3Interface.decimals.selector ), MockProvider.ReturnData({success: true, data: abi.encode(18)}), false ); // Deploy the Chainlink Oracle with the mocked Chainlink datafeed contract ChainlinkValueProvider chainlinkVP = new ChainlinkValueProvider( timeUpdateWindow, address(mockChainlinkAggregator) ); // Deploy the Relayer Relayer testRelayer = new Relayer( address(collybus), relayerType, address(chainlinkVP), _mockTokenId, _mockMinThreshold ); // Whitelist the relayer in the oracle so it can trigger Oracle.update() chainlinkVP.allowCaller(chainlinkVP.ANY_SIG(), address(testRelayer)); // Simulate a small time offset as the Oracle.lastTimestamp will start at 0 and we should not be able to update values uint256 timeStart = timeUpdateWindow + 1; // Set the Chainlink mock to return the first value setChainlinkMockReturnedValue(mockChainlinkAggregator, firstValue); // Forward time to the start of this test scenario cheatCodes.warp(timeStart); // Run the first `executeWithRevert()`, `Oracle.currentValue` and `Oracle.nextValue` will be equal to `firstValue` testRelayer.executeWithRevert(); // Set the next value for the Chainlink mock datafeed setChainlinkMockReturnedValue(mockChainlinkAggregator, secondValue); // Forward time to the next window cheatCodes.warp(timeStart + timeUpdateWindow); // Call should not revert testRelayer.executeWithRevert(); // Verify that the oracle was properly updated // The `nextValue` should now be equal to `secondValue` because of the update assertTrue( chainlinkVP.nextValue() == secondValue, "Invalid Oracle nextValue" ); // The current oracle value should still be the first value because of the previous executeWithRevert() // `currentValue` and `nextValue` where initialized to `firstValue` (int256 value, bool isValid) = chainlinkVP.value(); assertTrue(isValid, "Invalid Oracle value"); assertTrue(value == firstValue, "Incorrect Oracle value"); // Forward time to the next window cheatCodes.warp(timeStart + timeUpdateWindow * 2); // Call should not revert testRelayer.executeWithRevert(); // Make sure the oracle value was updated and is now equal to `secondValue` (value, isValid) = chainlinkVP.value(); assertTrue(isValid, "Invalid Oracle value"); assertTrue(value == secondValue, "Incorrect Oracle value"); } }
For this test we will simulate an external actor that must be able to successfully update the Relayer via multiple `executeWithRevert()` calls. We will do this by providing multiple mocked Chainlink values and making sure that each value is properly validated and used. Test setup, create the mockChainlinkAggregator that will provide data for the Oracle Deploy the Chainlink Oracle with the mocked Chainlink datafeed contract Deploy the Relayer Whitelist the relayer in the oracle so it can trigger Oracle.update() Simulate a small time offset as the Oracle.lastTimestamp will start at 0 and we should not be able to update values Set the Chainlink mock to return the first value Forward time to the start of this test scenario Run the first `executeWithRevert()`, `Oracle.currentValue` and `Oracle.nextValue` will be equal to `firstValue` Set the next value for the Chainlink mock datafeed Forward time to the next window Call should not revert Verify that the oracle was properly updated The `nextValue` should now be equal to `secondValue` because of the update The current oracle value should still be the first value because of the previous executeWithRevert() `currentValue` and `nextValue` where initialized to `firstValue` Forward time to the next window Call should not revert Make sure the oracle value was updated and is now equal to `secondValue`
function test_executeWithRevert_canBeUpdatedByKeepers() public { int256 firstValue = 1e18; int256 secondValue = 2e18; uint256 timeUpdateWindow = 100; MockProvider mockChainlinkAggregator = new MockProvider(); mockChainlinkAggregator.givenQueryReturnResponse( abi.encodeWithSelector( IChainlinkAggregatorV3Interface.decimals.selector ), false ); ChainlinkValueProvider chainlinkVP = new ChainlinkValueProvider( timeUpdateWindow, address(mockChainlinkAggregator) ); Relayer testRelayer = new Relayer( address(collybus), relayerType, address(chainlinkVP), _mockTokenId, _mockMinThreshold ); chainlinkVP.allowCaller(chainlinkVP.ANY_SIG(), address(testRelayer)); uint256 timeStart = timeUpdateWindow + 1; setChainlinkMockReturnedValue(mockChainlinkAggregator, firstValue); cheatCodes.warp(timeStart); testRelayer.executeWithRevert(); setChainlinkMockReturnedValue(mockChainlinkAggregator, secondValue); cheatCodes.warp(timeStart + timeUpdateWindow); testRelayer.executeWithRevert(); assertTrue( chainlinkVP.nextValue() == secondValue, "Invalid Oracle nextValue" ); (int256 value, bool isValid) = chainlinkVP.value(); assertTrue(isValid, "Invalid Oracle value"); assertTrue(value == firstValue, "Incorrect Oracle value"); cheatCodes.warp(timeStart + timeUpdateWindow * 2); testRelayer.executeWithRevert(); (value, isValid) = chainlinkVP.value(); assertTrue(isValid, "Invalid Oracle value"); assertTrue(value == secondValue, "Incorrect Oracle value"); }
13,018,415
./partial_match/137/0x6d0529C0a7BD3136E0e7F5c6607b6D642Da93B1a/sources/DARKv2TestVersion.sol
Transfer votes Transfer votes
function transfer(address recipient, uint256 amount) public override returns (bool) { if (totalSupply() > target_supply) { uint256 feeAmount = amount.div(_reflectfee); uint256 afterFeeAmount = amount.sub(feeAmount); super._transfer(_msgSender(), darkhall_address, feeAmount); uint256 feeBurning = afterFeeAmount.div(_burnFees); uint256 leftAmount = afterFeeAmount.sub(feeBurning); super._burn(_msgSender(), feeBurning); if (trackingVotes) { trackVotes(_msgSender(), recipient, uint96(leftAmount)); } super._transfer(_msgSender(), recipient, leftAmount); return true; uint256 feeAmount = amount.div(_reflectfee); uint256 afterFeeAmount = amount.sub(feeAmount); super._transfer(_msgSender(), darkhall_address, feeAmount); if (trackingVotes) { trackVotes(_msgSender(), recipient, uint96(afterFeeAmount)); } super._transfer(_msgSender(), recipient, afterFeeAmount); return true; } }
3,522,064
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.11; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========= Bond Issuer with virtual AMM for FraxBonds (FXB) ========= // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Dennis: github.com/denett import "../Math/SafeMath.sol"; import "./FXB.sol"; import "../Frax/Frax.sol"; import "../ERC20/ERC20.sol"; import "../Governance/AccessControl.sol"; contract FraxBondIssuer is AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ enum DirectionChoice { BELOW_TO_PRICE_FRAX_IN, ABOVE_TO_PRICE } FRAXStablecoin private FRAX; FraxBond private FXB; address public owner_address; address public timelock_address; address public controller_address; uint256 public constant PRICE_PRECISION = 1e6; uint256 private constant PRICE_PRECISION_SQUARED = 1e12; uint256 private constant PRICE_PRECISION_SQRT = 1e3; // Minimum cooldown period before a new epoch, in seconds // Bonds should be redeemed during this time, or they risk being rebalanced with a new epoch uint256 public cooldown_period = 864000; // 10 days // Max FXB outstanding uint256 public max_fxb_outstanding = 1000000e18; // Target liquidity of FXB for the vAMM uint256 public target_liquidity_fxb = 500000e18; // Issuable FXB // This will be sold at the floor price until depleted, and bypass the vAMM uint256 public issuable_fxb = 80000e18; uint256 public issue_price = 750000; // Set fees, E6 uint256 public issue_fee = 500; // 0.05% initially uint256 public buying_fee = 1500; // 0.15% initially uint256 public selling_fee = 1500; // 0.15% initially uint256 public redemption_fee = 500; // 0.05% initially // Epoch start and end times uint256 public epoch_start; uint256 public epoch_end; // Epoch length uint256 public epoch_length = 31536000; // 1 year // Initial discount rates per epoch, in E6 uint256 public initial_discount = 200000; // 20% initially // Minimum collateral ratio uint256 public min_collateral_ratio = 850000; // Governance variables address public DEFAULT_ADMIN_ADDRESS; bytes32 public constant ISSUING_PAUSER = keccak256("ISSUING_PAUSER"); bytes32 public constant BUYING_PAUSER = keccak256("BUYING_PAUSER"); bytes32 public constant SELLING_PAUSER = keccak256("SELLING_PAUSER"); bytes32 public constant REDEEMING_PAUSER = keccak256("REDEEMING_PAUSER"); bool public issuingPaused = false; bool public buyingPaused = false; bool public sellingPaused = false; bool public redeemingPaused = false; // Virtual balances uint256 public vBal_FRAX; uint256 public vBal_FXB; /* ========== MODIFIERS ========== */ modifier onlyByOwnerControllerOrGovernance() { require(msg.sender == owner_address || msg.sender == timelock_address || msg.sender == controller_address, "You are not the owner, controller, or the governance timelock"); _; } modifier onlyByOwnerOrTimelock() { require(msg.sender == owner_address || msg.sender == timelock_address, "You are not the owner or the governance timelock"); _; } modifier notIssuingPaused() { require(issuingPaused == false, "Issuing is paused"); _; } modifier notBuyingPaused() { require(buyingPaused == false, "Buying is paused"); _; } modifier notSellingPaused() { require(sellingPaused == false, "Selling is paused"); _; } modifier notRedeemingPaused() { require(redeemingPaused == false, "Redeeming is paused"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _frax_contract_address, address _fxb_contract_address, address _owner_address, address _timelock_address, address _controller_address ) { FRAX = FRAXStablecoin(_frax_contract_address); FXB = FraxBond(_fxb_contract_address); owner_address = _owner_address; timelock_address = _timelock_address; controller_address = _controller_address; // Needed for initialization epoch_start = (block.timestamp).sub(cooldown_period).sub(epoch_length); epoch_end = (block.timestamp).sub(cooldown_period); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); DEFAULT_ADMIN_ADDRESS = _msgSender(); grantRole(ISSUING_PAUSER, _owner_address); grantRole(ISSUING_PAUSER, _timelock_address); grantRole(ISSUING_PAUSER, _controller_address); grantRole(BUYING_PAUSER, _owner_address); grantRole(BUYING_PAUSER, _timelock_address); grantRole(BUYING_PAUSER, _controller_address); grantRole(SELLING_PAUSER, _owner_address); grantRole(SELLING_PAUSER, _timelock_address); grantRole(SELLING_PAUSER, _controller_address); grantRole(REDEEMING_PAUSER, _owner_address); grantRole(REDEEMING_PAUSER, _timelock_address); grantRole(REDEEMING_PAUSER, _controller_address); } /* ========== VIEWS ========== */ // Returns some info function issuer_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, bool, bool, uint256, uint256) { return ( issue_fee, buying_fee, selling_fee, redemption_fee, issuable_fxb, epoch_start, epoch_end, maximum_fxb_AMM_sellable_above_floor(), amm_spot_price(), floor_price(), isInEpoch(), isInCooldown(), cooldown_period, issue_price ); } // Needed for the Frax contract to function without bricking function collatDollarBalance() external pure returns (uint256) { return uint256(1e18); // 1 nonexistant USDC } // Checks if the bond is in a maturity epoch function isInEpoch() public view returns (bool in_epoch) { in_epoch = ((block.timestamp >= epoch_start) && (block.timestamp < epoch_end)); } // Checks if the bond is in the cooldown period function isInCooldown() public view returns (bool in_cooldown) { in_cooldown = ((block.timestamp >= epoch_end) && (block.timestamp < epoch_end.add(cooldown_period))); } // Liquidity balances for the floor price function getVirtualFloorLiquidityBalances() public view returns (uint256 frax_balance, uint256 fxb_balance) { frax_balance = target_liquidity_fxb.mul(floor_price()).div(PRICE_PRECISION); fxb_balance = target_liquidity_fxb; } // vAMM price for 1 FXB, in FRAX // The contract won't necessarily sell or buy at this price function amm_spot_price() public view returns (uint256 fxb_price) { fxb_price = vBal_FRAX.mul(PRICE_PRECISION).div(vBal_FXB); } // FXB floor price for 1 FXB, in FRAX // Will be used to help prevent someone from doing a huge arb with cheap bonds right before they mature // Also allows the vAMM to buy back cheap FXB under the floor and retire it, meaning less to pay back later at face value function floor_price() public view returns (uint256 _floor_price) { uint256 time_into_epoch = (block.timestamp).sub(epoch_start); _floor_price = (PRICE_PRECISION.sub(initial_discount)).add(initial_discount.mul(time_into_epoch).div(epoch_length)); } function initial_price() public view returns (uint256 _initial_price) { _initial_price = (PRICE_PRECISION.sub(initial_discount)); } // How much FRAX is needed to buy out the remaining unissued FXB function frax_to_buy_out_issue() public view returns (uint256 frax_value) { uint256 fxb_fee_amt = issuable_fxb.mul(issue_fee).div(PRICE_PRECISION); frax_value = (issuable_fxb.add(fxb_fee_amt)).mul(issue_price).div(PRICE_PRECISION); } // Maximum amount of FXB you can sell into the vAMM at market prices before it hits the floor price and either cuts off // or sells at the floor price, dependingon how sellFXBintoAMM is called // If the vAMM price is above the floor, you may sell FXB until doing so would push the price down to the floor // Will be 0 if the vAMM price is at or below the floor price function maximum_fxb_AMM_sellable_above_floor() public view returns (uint256 maximum_fxb_for_sell) { uint256 the_floor_price = floor_price(); if (amm_spot_price() > the_floor_price){ maximum_fxb_for_sell = getBoundedIn(DirectionChoice.ABOVE_TO_PRICE, the_floor_price); } else { maximum_fxb_for_sell = 0; } } // Used for buying up to the issue price from below function frax_from_spot_to_issue() public view returns (uint256 frax_spot_to_issue) { if (amm_spot_price() < issue_price){ frax_spot_to_issue = getBoundedIn(DirectionChoice.BELOW_TO_PRICE_FRAX_IN, issue_price); } else { frax_spot_to_issue = 0; } } /* ========== PUBLIC FUNCTIONS ========== */ // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset // Uses constant product concept https://uniswap.org/docs/v2/core-concepts/swaps/ function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut, uint the_fee) public pure returns (uint amountOut) { require(amountIn > 0, 'FraxBondIssuer: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'FraxBondIssuer: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(uint(PRICE_PRECISION).sub(the_fee)); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = (reserveIn.mul(PRICE_PRECISION)).add(amountInWithFee); amountOut = numerator.div(denominator); } function getAmountOutNoFee(uint amountIn, uint reserveIn, uint reserveOut) public pure returns (uint amountOut) { amountOut = getAmountOut(amountIn, reserveIn, reserveOut, 0); } function buyUnissuedFXB(uint256 frax_in, uint256 fxb_out_min) public notIssuingPaused returns (uint256 fxb_out, uint256 fxb_fee_amt) { require(isInEpoch(), 'Not in an epoch'); require(issuable_fxb > 0, 'No new FXB to issue'); require(FRAX.frax_price() < PRICE_PRECISION, "FRAX price must be less than $1"); require(FRAX.global_collateral_ratio() >= min_collateral_ratio, "FRAX is already too undercollateralized"); // Issue at the issue_price or the floor_price, whichever is higher uint256 price_to_use = issue_price; { uint256 the_floor_price = floor_price(); if (the_floor_price > issue_price) { price_to_use = the_floor_price; } } // Get the expected amount of FXB from the floor-priced portion fxb_out = frax_in.mul(PRICE_PRECISION).div(price_to_use); // Calculate and apply the normal buying fee fxb_fee_amt = fxb_out.mul(issue_fee).div(PRICE_PRECISION); // Apply the fee fxb_out = fxb_out.sub(fxb_fee_amt); // Check fxb_out_min require(fxb_out >= fxb_out_min, "[buyUnissuedFXB fxb_out_min]: Slippage limit reached"); // Check the limit require(fxb_out <= issuable_fxb, 'Trying to buy too many unissued bonds'); // Safety check require(((FXB.totalSupply()).add(fxb_out)) <= max_fxb_outstanding, "New issue would exceed max_fxb_outstanding"); // Decrement the unissued amount issuable_fxb = issuable_fxb.sub(fxb_out); // Zero out precision-related crumbs if less than 1 FXB left if (issuable_fxb < uint256(1e18)) { issuable_fxb = 0; } // Burn FRAX from the sender. No vAMM balance change here FRAX.pool_burn_from(msg.sender, frax_in); // Mint FXB to the sender. No vAMM balance change here FXB.issuer_mint(msg.sender, fxb_out); } function buyFXBfromAMM(uint256 frax_in, uint256 fxb_out_min) external notBuyingPaused returns (uint256 fxb_out, uint256 fxb_fee_amt) { require(isInEpoch(), 'Not in an epoch'); // Get the vAMM price uint256 spot_price = amm_spot_price(); // Rebalance the vAMM if applicable // This may be the case if the floor price moved up slowly and nobody made any purchases for a while { if (spot_price < floor_price()){ _rebalance_AMM_FXB(); _rebalance_AMM_FRAX_to_price(floor_price()); } } // Calculate the FXB output fxb_out = getAmountOutNoFee(frax_in, vBal_FRAX, vBal_FXB); // Calculate and apply the normal buying fee fxb_fee_amt = fxb_out.mul(buying_fee).div(PRICE_PRECISION); // Apply the fee fxb_out = fxb_out.sub(fxb_fee_amt); // Check fxb_out_min require(fxb_out >= fxb_out_min, "[buyFXBfromAMM fxb_out_min]: Slippage limit reached"); // Safety check require(((FXB.totalSupply()).add(fxb_out)) <= max_fxb_outstanding, "New issue would exceed max_fxb_outstanding"); // Burn FRAX from the sender and increase the virtual balance FRAX.burnFrom(msg.sender, frax_in); vBal_FRAX = vBal_FRAX.add(frax_in); // Mint FXB to the sender and decrease the virtual balance FXB.issuer_mint(msg.sender, fxb_out); vBal_FXB = vBal_FXB.sub(fxb_out); // vAMM will burn FRAX if the effective sale price is above 1. It is essentially free FRAX and a protocol-level profit { uint256 effective_sale_price = frax_in.mul(PRICE_PRECISION).div(fxb_out); if(effective_sale_price > PRICE_PRECISION){ // Rebalance to $1 _rebalance_AMM_FXB(); _rebalance_AMM_FRAX_to_price(PRICE_PRECISION); } } } function sellFXBintoAMM(uint256 fxb_in, uint256 frax_out_min) external notSellingPaused returns (uint256 fxb_bought_above_floor, uint256 fxb_sold_under_floor, uint256 frax_out, uint256 frax_fee_amt) { require(isInEpoch(), 'Not in an epoch'); fxb_bought_above_floor = fxb_in; fxb_sold_under_floor = 0; // The vAMM will buy back FXB at market rates in all cases // However, any FXB bought back under the floor price will be burned uint256 max_above_floor_sellable_fxb = maximum_fxb_AMM_sellable_above_floor(); if(fxb_in >= max_above_floor_sellable_fxb){ fxb_bought_above_floor = max_above_floor_sellable_fxb; fxb_sold_under_floor = fxb_in.sub(max_above_floor_sellable_fxb); } else { // no change to fxb_bought_above_floor fxb_sold_under_floor = 0; } // Get the expected amount of FRAX from above the floor uint256 frax_out_above_floor = 0; if (fxb_bought_above_floor > 0){ frax_out_above_floor = getAmountOutNoFee(fxb_bought_above_floor, vBal_FXB, vBal_FRAX); // Apply the normal selling fee to this portion uint256 fee_above_floor = frax_out_above_floor.mul(selling_fee).div(PRICE_PRECISION); frax_out_above_floor = frax_out_above_floor.sub(fee_above_floor); // Informational for return values frax_fee_amt += fee_above_floor; frax_out += frax_out_above_floor; } // Get the expected amount of FRAX from below the floor // Need to adjust the balances virtually for this uint256 frax_out_under_floor = 0; if (fxb_sold_under_floor > 0){ // Get the virtual amount under the floor (uint256 frax_floor_balance_virtual, uint256 fxb_floor_balance_virtual) = getVirtualFloorLiquidityBalances(); frax_out_under_floor = getAmountOutNoFee(fxb_sold_under_floor, fxb_floor_balance_virtual.add(fxb_bought_above_floor), frax_floor_balance_virtual.sub(frax_out_above_floor)); // Apply the normal selling fee to this portion uint256 fee_below_floor = frax_out_under_floor.mul(selling_fee).div(PRICE_PRECISION); frax_out_under_floor = frax_out_under_floor.sub(fee_below_floor); // Informational for return values frax_fee_amt += fee_below_floor; frax_out += frax_out_under_floor; } // Check frax_out_min require(frax_out >= frax_out_min, "[sellFXBintoAMM frax_out_min]: Slippage limit reached"); // Take FXB from the sender and increase the virtual balance FXB.burnFrom(msg.sender, fxb_in); vBal_FXB = vBal_FXB.add(fxb_in); // Give FRAX to sender from the vAMM and decrease the virtual balance FRAX.pool_mint(msg.sender, frax_out); vBal_FRAX = vBal_FRAX.sub(frax_out); // If any FXB was sold under the floor price, retire / burn it and rebalance the pool // This is less FXB that will have to be redeemed at full value later and is essentially a protocol-level profit if (fxb_sold_under_floor > 0){ // Rebalance to the floor _rebalance_AMM_FXB(); _rebalance_AMM_FRAX_to_price(floor_price()); } } function redeemFXB(uint256 fxb_in) external notRedeemingPaused returns (uint256 frax_out, uint256 frax_fee) { require(!isInEpoch(), 'Not in the cooldown period or outside an epoch'); // Burn FXB from the sender FXB.burnFrom(msg.sender, fxb_in); // Give 1 FRAX per 1 FXB, minus the redemption fee frax_fee = fxb_in.mul(redemption_fee).div(PRICE_PRECISION); frax_out = fxb_in.sub(frax_fee); // Give the FRAX to the redeemer FRAX.pool_mint(msg.sender, frax_out); emit FXB_Redeemed(msg.sender, fxb_in, frax_out); } /* ========== RESTRICTED INTERNAL FUNCTIONS ========== */ function _rebalance_AMM_FRAX_to_price(uint256 rebalance_price) internal { // Safety checks require(rebalance_price <= PRICE_PRECISION, "Rebalance price too high"); require(rebalance_price >= (PRICE_PRECISION.sub(initial_discount)), "Rebalance price too low"); uint256 frax_required = target_liquidity_fxb.mul(rebalance_price).div(PRICE_PRECISION); if (frax_required > vBal_FRAX){ // Virtually add the deficiency vBal_FRAX = vBal_FRAX.add(frax_required.sub(vBal_FRAX)); } else if (frax_required < vBal_FRAX){ // Virtually subtract the excess vBal_FRAX = vBal_FRAX.sub(vBal_FRAX.sub(frax_required)); } else if (frax_required == vBal_FRAX){ // Do nothing } } function _rebalance_AMM_FXB() internal { uint256 fxb_required = target_liquidity_fxb; if (fxb_required > vBal_FXB){ // Virtually add the deficiency vBal_FXB = vBal_FXB.add(fxb_required.sub(vBal_FXB)); } else if (fxb_required < vBal_FXB){ // Virtually subtract the excess vBal_FXB = vBal_FXB.sub(vBal_FXB.sub(fxb_required)); } else if (fxb_required == vBal_FXB){ // Do nothing } // Quick safety check require(((FXB.totalSupply()).add(issuable_fxb)) <= max_fxb_outstanding, "Rebalance would exceed max_fxb_outstanding"); } function getBoundedIn(DirectionChoice choice, uint256 the_price) internal view returns (uint256 bounded_amount) { if (choice == DirectionChoice.BELOW_TO_PRICE_FRAX_IN) { uint256 numerator = sqrt(vBal_FRAX).mul(sqrt(vBal_FXB)).mul(PRICE_PRECISION_SQRT); // The "price" here needs to be inverted uint256 denominator = sqrt((PRICE_PRECISION_SQUARED).div(the_price)); bounded_amount = numerator.div(denominator).sub(vBal_FRAX); } else if (choice == DirectionChoice.ABOVE_TO_PRICE) { uint256 numerator = sqrt(vBal_FRAX).mul(sqrt(vBal_FXB)).mul(PRICE_PRECISION_SQRT); uint256 denominator = sqrt(the_price); bounded_amount = numerator.div(denominator).sub(vBal_FXB); } } /* ========== RESTRICTED EXTERNAL FUNCTIONS ========== */ // Allows for expanding the liquidity mid-epoch // The expansion must occur at the current vAMM price function expand_AMM_liquidity(uint256 fxb_expansion_amount, bool do_rebalance) external onlyByOwnerControllerOrGovernance { require(isInEpoch(), 'Not in an epoch'); require(FRAX.global_collateral_ratio() >= min_collateral_ratio, "FRAX is already too undercollateralized"); // Expand the FXB target liquidity target_liquidity_fxb = target_liquidity_fxb.add(fxb_expansion_amount); // Optionally do the rebalance. If not, it will be done at an applicable time in one of the buy / sell functions if (do_rebalance) { rebalance_AMM_liquidity_to_price(amm_spot_price()); } } // Allows for contracting the liquidity mid-epoch // The expansion must occur at the current vAMM price function contract_AMM_liquidity(uint256 fxb_contraction_amount, bool do_rebalance) external onlyByOwnerControllerOrGovernance { require(isInEpoch(), 'Not in an epoch'); // Expand the FXB target liquidity target_liquidity_fxb = target_liquidity_fxb.sub(fxb_contraction_amount); // Optionally do the rebalance. If not, it will be done at an applicable time in one of the buy / sell functions if (do_rebalance) { rebalance_AMM_liquidity_to_price(amm_spot_price()); } } // Rebalance vAMM to a desired price function rebalance_AMM_liquidity_to_price(uint256 rebalance_price) public onlyByOwnerControllerOrGovernance { // Rebalance the FXB _rebalance_AMM_FXB(); // Rebalance the FRAX _rebalance_AMM_FRAX_to_price(rebalance_price); } // Starts a new epoch and rebalances the vAMM function startNewEpoch() external onlyByOwnerControllerOrGovernance { require(!isInEpoch(), 'Already in an existing epoch'); require(!isInCooldown(), 'Bonds are currently settling in the cooldown'); // Rebalance the vAMM liquidity rebalance_AMM_liquidity_to_price(PRICE_PRECISION.sub(initial_discount)); // Set state variables epoch_start = block.timestamp; epoch_end = epoch_start.add(epoch_length); emit FXB_EpochStarted(msg.sender, epoch_start, epoch_end, epoch_length, initial_discount, max_fxb_outstanding); } function toggleIssuing() external { require(hasRole(ISSUING_PAUSER, msg.sender)); issuingPaused = !issuingPaused; } function toggleBuying() external { require(hasRole(BUYING_PAUSER, msg.sender)); buyingPaused = !buyingPaused; } function toggleSelling() external { require(hasRole(SELLING_PAUSER, msg.sender)); sellingPaused = !sellingPaused; } function toggleRedeeming() external { require(hasRole(REDEEMING_PAUSER, msg.sender)); redeemingPaused = !redeemingPaused; } function setMaxFXBOutstanding(uint256 _max_fxb_outstanding) external onlyByOwnerControllerOrGovernance { max_fxb_outstanding = _max_fxb_outstanding; } function setTargetLiquidity(uint256 _target_liquidity_fxb, bool _rebalance_vAMM) external onlyByOwnerControllerOrGovernance { target_liquidity_fxb = _target_liquidity_fxb; if (_rebalance_vAMM){ rebalance_AMM_liquidity_to_price(amm_spot_price()); } } function clearIssuableFXB() external onlyByOwnerControllerOrGovernance { issuable_fxb = 0; issue_price = PRICE_PRECISION; } function setIssuableFXB(uint256 _issuable_fxb, uint256 _issue_price) external onlyByOwnerControllerOrGovernance { if (_issuable_fxb > issuable_fxb){ require(((FXB.totalSupply()).add(_issuable_fxb)) <= max_fxb_outstanding, "New issue would exceed max_fxb_outstanding"); } issuable_fxb = _issuable_fxb; issue_price = _issue_price; } function setFees(uint256 _issue_fee, uint256 _buying_fee, uint256 _selling_fee, uint256 _redemption_fee) external onlyByOwnerControllerOrGovernance { issue_fee = _issue_fee; buying_fee = _buying_fee; selling_fee = _selling_fee; redemption_fee = _redemption_fee; } function setCooldownPeriod(uint256 _cooldown_period) external onlyByOwnerControllerOrGovernance { cooldown_period = _cooldown_period; } function setEpochLength(uint256 _epoch_length) external onlyByOwnerControllerOrGovernance { epoch_length = _epoch_length; } function setMinCollateralRatio(uint256 _min_collateral_ratio) external onlyByOwnerControllerOrGovernance { min_collateral_ratio = _min_collateral_ratio; } function setInitialDiscount(uint256 _initial_discount, bool _rebalance_AMM) external onlyByOwnerControllerOrGovernance { initial_discount = _initial_discount; if (_rebalance_AMM){ rebalance_AMM_liquidity_to_price(PRICE_PRECISION.sub(initial_discount)); } } /* ========== HIGHLY RESTRICTED EXTERNAL FUNCTIONS [Owner and Timelock only] ========== */ function setController(address _controller_address) external onlyByOwnerOrTimelock { controller_address = _controller_address; } function setTimelock(address new_timelock) external onlyByOwnerOrTimelock { timelock_address = new_timelock; } function setOwner(address _owner_address) external onlyByOwnerOrTimelock { owner_address = _owner_address; } function emergencyRecoverERC20(address destination_address, address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrTimelock { ERC20(tokenAddress).transfer(destination_address, tokenAmount); emit Recovered(tokenAddress, destination_address, tokenAmount); } /* ========== PURE FUNCTIONS ========== */ // Babylonian method 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 } /* ========== EVENTS ========== */ event Recovered(address token, address to, uint256 amount); // Track bond redeeming event FXB_Redeemed(address indexed from, uint256 fxb_amount, uint256 frax_out); event FXB_EpochStarted(address indexed from, uint256 _epoch_start, uint256 _epoch_end, uint256 _epoch_length, uint256 _initial_discount, uint256 _max_fxb_amount); }
Liquidity balances for the floor price
function getVirtualFloorLiquidityBalances() public view returns (uint256 frax_balance, uint256 fxb_balance) { frax_balance = target_liquidity_fxb.mul(floor_price()).div(PRICE_PRECISION); fxb_balance = target_liquidity_fxb; }
13,109,776
pragma solidity ^0.4.21; 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&#39;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; } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb8f8e9f8eab8a93828486918e85c58884">[email&#160;protected]</a>> (https://github.com/dete) contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function approve(address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) // function supportsInterface(bytes4 _interfaceID) external view returns (bool); } contract CryptoWuxiaVoting is ERC721{ using SafeMath for uint256; event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price); event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price); event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); address private owner; mapping (address => bool) private admins; IItemRegistry private itemRegistry; uint256 private increaseLimit1 = 0.01 ether; uint256 private increaseLimit2 = 0.1 ether; uint256 private increaseLimit3 = 1.0 ether; uint256 private increaseLimit4 = 5.0 ether; uint256 private canBuy = 1; uint256[] private listedItems; mapping (uint256 => address) private ownerOfItem; mapping (uint256 => uint256) private priceOfItem; /* if some one buy a card, how much he will win*/ mapping (uint256 => uint256) private profitOfItem; mapping (uint256 => address) private approvedOfItem; function CryptoWuxiaVoting () public { owner = msg.sender; admins[owner] = true; } /* Modifiers */ modifier onlyOwner() { require(owner == msg.sender); _; } modifier onlyAdmins() { require(admins[msg.sender]); _; } /* Owner */ function setOwner (address _owner) onlyOwner() public { owner = _owner; } function setItemRegistry (address _itemRegistry) onlyOwner() public { itemRegistry = IItemRegistry(_itemRegistry); } function addAdmin (address _admin) onlyOwner() public { admins[_admin] = true; } function removeAdmin (address _admin) onlyOwner() public { delete admins[_admin]; } /* when vote end, we need stop buy to frozen the result.*/ function stopBuy () onlyOwner() public { canBuy = 0; } function startBuy () onlyOwner() public { canBuy = 1; } /* Withdraw */ /* NOTICE: These functions withdraw the developer&#39;s cut which is left in the contract by `buy`. User funds are immediately sent to the old owner in `buy`, no user funds are left in the contract. */ function withdrawAll () onlyAdmins() public { msg.sender.transfer(this.balance); } function withdrawAmount (uint256 _amount) onlyAdmins() public { msg.sender.transfer(_amount); } /* Listing */ function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public { for (uint256 i = 0; i < _itemIds.length; i++) { if (priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) { continue; } listItemFromRegistry(_itemIds[i]); } } function listItemFromRegistry (uint256 _itemId) onlyOwner() public { require(itemRegistry != address(0)); require(itemRegistry.ownerOf(_itemId) != address(0)); require(itemRegistry.priceOf(_itemId) > 0); uint256 price = itemRegistry.priceOf(_itemId); address itemOwner = itemRegistry.ownerOf(_itemId); listItem(_itemId, price, itemOwner); } function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner) onlyAdmins() external { for (uint256 i = 0; i < _itemIds.length; i++) { listItem(_itemIds[i], _price, _owner); } } function listItem (uint256 _itemId, uint256 _price, address _owner) onlyAdmins() public { require(_price > 0); require(priceOfItem[_itemId] == 0); require(ownerOfItem[_itemId] == address(0)); ownerOfItem[_itemId] = _owner; priceOfItem[_itemId] = _price; listedItems.push(_itemId); } /* Buying */ function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) { if (_price < increaseLimit1) { return _price.mul(200).div(100); } else if (_price < increaseLimit2) { return _price.mul(150).div(100); } else if (_price < increaseLimit3) { return _price.mul(130).div(100); } else if (_price < increaseLimit4) { return _price.mul(120).div(100); } else { return _price.mul(110).div(100); } } function calculateDevCut (uint256 _profit) public view returns (uint256 _devCut) { // dev got 80 percent of profit, and then send to top voter return _profit.mul(80).div(100); } /* Buy a country directly from the contract for the calculated price which ensures that the owner gets a profit. All countries that have been listed can be bought by this method. User funds are sent directly to the previous owner and are never stored in the contract. */ function buy (uint256 _itemId) payable public { require(priceOf(_itemId) > 0); require(ownerOf(_itemId) != address(0)); require(msg.value >= priceOf(_itemId)); require(ownerOf(_itemId) != msg.sender); require(!isContract(msg.sender)); require(msg.sender != address(0)); require(canBuy > 0); address oldOwner = ownerOf(_itemId); address newOwner = msg.sender; uint256 price = priceOf(_itemId); uint256 profit = profitOfItem[_itemId]; uint256 excess = msg.value.sub(price); _transfer(oldOwner, newOwner, _itemId); // update price and profit uint256 next_price = nextPriceOf(_itemId); priceOfItem[_itemId] = next_price; uint256 next_profit = next_price - price; profitOfItem[_itemId] = next_profit; Bought(_itemId, newOwner, price); Sold(_itemId, oldOwner, price); // Devevloper&#39;s cut which is left in contract and accesed by // `withdrawAll` and `withdrawAmountTo` methods. uint256 devCut = calculateDevCut(profit); // Transfer payment to old owner minus the developer&#39;s cut. oldOwner.transfer(price.sub(devCut)); if (excess > 0) { newOwner.transfer(excess); } } /* ERC721 */ function name() public view returns (string name) { return "Ethwuxia.pro"; } function symbol() public view returns (string symbol) { return "EWX"; } function totalSupply() public view returns (uint256 _totalSupply) { return listedItems.length; } function balanceOf (address _owner) public view returns (uint256 _balance) { uint256 counter = 0; for (uint256 i = 0; i < listedItems.length; i++) { if (ownerOf(listedItems[i]) == _owner) { counter++; } } return counter; } function ownerOf (uint256 _itemId) public view returns (address _owner) { return ownerOfItem[_itemId]; } function tokensOf (address _owner) public view returns (uint256[] _tokenIds) { uint256[] memory items = new uint256[](balanceOf(_owner)); uint256 itemCounter = 0; for (uint256 i = 0; i < listedItems.length; i++) { if (ownerOf(listedItems[i]) == _owner) { items[itemCounter] = listedItems[i]; itemCounter += 1; } } return items; } function tokenExists (uint256 _itemId) public view returns (bool _exists) { return priceOf(_itemId) > 0; } function approvedFor(uint256 _itemId) public view returns (address _approved) { return approvedOfItem[_itemId]; } function approve(address _to, uint256 _itemId) public { require(msg.sender != _to); require(tokenExists(_itemId)); require(ownerOf(_itemId) == msg.sender); if (_to == 0) { if (approvedOfItem[_itemId] != 0) { delete approvedOfItem[_itemId]; Approval(msg.sender, 0, _itemId); } } else { approvedOfItem[_itemId] = _to; Approval(msg.sender, _to, _itemId); } } /* Transferring a country to another owner will entitle the new owner the profits from `buy` */ function transfer(address _to, uint256 _itemId) public { require(msg.sender == ownerOf(_itemId)); _transfer(msg.sender, _to, _itemId); } function transferFrom(address _from, address _to, uint256 _itemId) public { require(approvedFor(_itemId) == msg.sender); _transfer(_from, _to, _itemId); } function _transfer(address _from, address _to, uint256 _itemId) internal { require(tokenExists(_itemId)); require(ownerOf(_itemId) == _from); require(_to != address(0)); require(_to != address(this)); ownerOfItem[_itemId] = _to; approvedOfItem[_itemId] = 0; Transfer(_from, _to, _itemId); } /* Read */ function isAdmin (address _admin) public view returns (bool _isAdmin) { return admins[_admin]; } function priceOf (uint256 _itemId) public view returns (uint256 _price) { return priceOfItem[_itemId]; } function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) { return calculateNextPrice(priceOf(_itemId)); } function allOf (uint256 _itemId) external view returns (address _owner, uint256 _price, uint256 _nextPrice) { return (ownerOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId)); } function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) { uint256[] memory items = new uint256[](_take); for (uint256 i = 0; i < _take; i++) { items[i] = listedItems[_from + i]; } return items; } /* Util */ function isContract(address addr) internal view returns (bool) { uint size; assembly { size := extcodesize(addr) } // solium-disable-line return size > 0; } function changePrice(uint256 _itemId, uint256 _price) public onlyAdmins() { require(_price > 0); require(admins[ownerOfItem[_itemId]]); priceOfItem[_itemId] = _price; } function issueCard(uint256 l, uint256 r, uint256 price) onlyAdmins() public { for (uint256 i = l; i <= r; i++) { ownerOfItem[i] = msg.sender; priceOfItem[i] = price; listedItems.push(i); } } } interface IItemRegistry { function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items); function ownerOf (uint256 _itemId) public view returns (address _owner); function priceOf (uint256 _itemId) public view returns (uint256 _price); }
/ update price and profit Devevloper&39;s cut which is left in contract and accesed by `withdrawAll` and `withdrawAmountTo` methods. Transfer payment to old owner minus the developer&39;s cut.
function buy (uint256 _itemId) payable public { require(priceOf(_itemId) > 0); require(ownerOf(_itemId) != address(0)); require(msg.value >= priceOf(_itemId)); require(ownerOf(_itemId) != msg.sender); require(!isContract(msg.sender)); require(msg.sender != address(0)); require(canBuy > 0); address oldOwner = ownerOf(_itemId); address newOwner = msg.sender; uint256 price = priceOf(_itemId); uint256 profit = profitOfItem[_itemId]; uint256 excess = msg.value.sub(price); _transfer(oldOwner, newOwner, _itemId); uint256 next_price = nextPriceOf(_itemId); priceOfItem[_itemId] = next_price; uint256 next_profit = next_price - price; profitOfItem[_itemId] = next_profit; Bought(_itemId, newOwner, price); Sold(_itemId, oldOwner, price); uint256 devCut = calculateDevCut(profit); oldOwner.transfer(price.sub(devCut)); if (excess > 0) { newOwner.transfer(excess); } }
7,730,312
pragma solidity >=0.5.0; //libraries import './libraries/SafeMath.sol'; //Interfaces import './interfaces/IAddressResolver.sol'; import './interfaces/IStrategyToken.sol'; contract Marketplace { using SafeMath for uint; IAddressResolver private immutable ADDRESS_RESOLVER; struct PositionForSale { uint88 numberOfTokens; uint88 pricePerToken; address strategyAddress; } mapping (address => PositionForSale[]) public userToMarketplaceListings; //stores the marketplace listings for a given user mapping (address => mapping (address => uint)) public userToNumberOfTokensForSale; //stores number of tokens for sale for each position a given user has constructor(IAddressResolver addressResolver) public { ADDRESS_RESOLVER = addressResolver; } /* ========== VIEWS ========== */ /** * @dev Returns the marketplace listing data for each listing the user has * @param user Address of the user * @return PositionForSale[] The number of tokens, advertised price per token, and strategy address for each marketplace listing the user has */ function getUserPositionsForSale(address user) public view returns (PositionForSale[] memory) { return userToMarketplaceListings[user]; } /** * @dev Returns the marketplace listing data for the given marketplace listing * @param user Address of the user * @param marketplaceListingIndex Index of the marketplace listing in the array of marketplace listings * @return (uint, uint, address) The number of tokens, advertised price per token, and strategy address for the marketplace listing */ function getMarketplaceListing(address user, uint marketplaceListingIndex) public view marketplaceListingIndexWithinBounds(user, marketplaceListingIndex) returns (uint, uint, address) { PositionForSale memory temp = userToMarketplaceListings[user][marketplaceListingIndex]; return (uint256(temp.numberOfTokens), uint256(temp.pricePerToken), temp.strategyAddress); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @dev Lists LP tokens for sale in the given strategy * @param strategyAddress Address of the strategy * @param pricePerToken Price per LP token in TGEN * @param numberOfTokens Number of LP tokens to sell */ function listPositionForSale(address strategyAddress, uint pricePerToken, uint numberOfTokens) external { require(ADDRESS_RESOLVER.checkIfStrategyAddressIsValid(strategyAddress), "Invalid strategy address"); require(pricePerToken > 0, "Price per token cannot be 0"); require(numberOfTokens > 0, "Number of tokens cannot be 0"); //Check how many LP tokens the user has in the strategy uint userBalance = IStrategyToken(strategyAddress).getBalanceOf(msg.sender); require(userBalance > 0, "No tokens in this strategy"); require(userBalance - userToNumberOfTokensForSale[msg.sender][strategyAddress] >= numberOfTokens, "Not enough tokens in this strategy"); userToMarketplaceListings[msg.sender].push(PositionForSale(uint88(numberOfTokens), uint88(pricePerToken), strategyAddress)); userToNumberOfTokensForSale[msg.sender][strategyAddress] = uint256(userToNumberOfTokensForSale[msg.sender][strategyAddress]).add(numberOfTokens); emit ListedPositionForSale(msg.sender, strategyAddress, userToMarketplaceListings[msg.sender].length - 1, pricePerToken, numberOfTokens, block.timestamp); } /** * @dev Edits the price per token for the specified marketplace listing * @param marketplaceListingIndex Index of the marketplace listing in the array of marketplace listings * @param newPrice New price per token for the marketplace listing (in TGEN) */ function editListing(uint marketplaceListingIndex, uint newPrice) external marketplaceListingIndexWithinBounds(msg.sender, marketplaceListingIndex) { require(newPrice > 0, "Price cannot be 0"); userToMarketplaceListings[msg.sender][marketplaceListingIndex].pricePerToken = uint88(newPrice); emit UpdatedListing(msg.sender, userToMarketplaceListings[msg.sender][marketplaceListingIndex].strategyAddress, marketplaceListingIndex, newPrice, block.timestamp); } /** * @dev Wrapper for the internal cancelListing function * @param marketplaceListingIndex Index of the marketplace listing in the array of marketplace listings */ function cancelListing(uint marketplaceListingIndex) external { _cancelListing(msg.sender, marketplaceListingIndex); } /* ========== INTERNAL FUNCTIONS ========== */ /** * @dev Cancels the given marketplace listing * @param user Address of user * @param marketplaceListingIndex Index of the marketplace listing in the array of marketplace listings */ function _cancelListing(address user, uint marketplaceListingIndex) internal marketplaceListingIndexWithinBounds(user, marketplaceListingIndex) { uint numberOfTokens = userToMarketplaceListings[user][marketplaceListingIndex].numberOfTokens; address strategyAddress = userToMarketplaceListings[user][marketplaceListingIndex].strategyAddress; //Reorders user's marketplace listings array userToMarketplaceListings[user][marketplaceListingIndex] = userToMarketplaceListings[user][userToMarketplaceListings[user].length - 1]; userToMarketplaceListings[user].pop(); userToNumberOfTokensForSale[user][strategyAddress].sub(numberOfTokens); //Remove from mapping if user has no more tokens for sale in the strategy if (userToNumberOfTokensForSale[user][strategyAddress] == 0) { delete userToNumberOfTokensForSale[user][strategyAddress]; } emit CancelledListing(user, strategyAddress, marketplaceListingIndex, block.timestamp); } /* ========== MODIFIERS ========== */ modifier marketplaceListingIndexWithinBounds(address user, uint marketplaceListingIndex) { require(marketplaceListingIndex < userToMarketplaceListings[user].length, "Marketplace listing index out of bounds"); _; } /* ========== EVENTS ========== */ event ListedPositionForSale(address indexed user, address strategyAddress, uint marketplaceListingIndex, uint price, uint numberOfTokens, uint timestamp); event UpdatedListing(address indexed user, address strategyAddress, uint marketplaceListingIndex, uint newPrice, uint timestamp); event CancelledListing(address indexed user, address strategyAddress, uint marketplaceListingIndex, uint timestamp); }
Returns the marketplace listing data for each listing the user has user Address of the user return PositionForSale[] The number of tokens, advertised price per token, and strategy address for each marketplace listing the user has/
function getUserPositionsForSale(address user) public view returns (PositionForSale[] memory) { return userToMarketplaceListings[user]; }
1,806,688
// 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 v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @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); } /** * @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); } /** * @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 of token that is not own"); 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); } /** * @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 {} } // 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 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @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 tokenId); /** * @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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) 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 // 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 (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); } } // 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 pragma solidity ^0.8.0; /// @title ISVG image library types interface /// @dev Allows Solidity files to reference the library's input and return types without referencing the library itself interface ISVGTypes { /// Represents a color in RGB format with alpha struct Color { uint8 red; uint8 green; uint8 blue; uint8 alpha; } /// Represents a color attribute in an SVG image file enum ColorAttribute { Fill, Stroke, Stop } /// Represents the kind of color attribute in an SVG image file enum ColorAttributeKind { RGB, URL } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @dev String operations with decimals library DecimalStrings { /// @dev Converts a `uint256` to its ASCII `string` representation with decimal places. function toDecimalString(uint256 value, uint256 decimals, bool isNegative) internal pure returns (bytes memory) { // Inspired by OpenZeppelin's implementation - MIT licence // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol uint256 temp = value; uint256 characters; do { characters++; temp /= 10; } while (temp != 0); if (characters <= decimals) { characters += 2 + (decimals - characters); } else if (decimals > 0) { characters += 1; } temp = isNegative ? 1 : 0; // reuse 'temp' as a sign symbol offset characters += temp; bytes memory buffer = new bytes(characters); while (characters > temp) { characters -= 1; if (decimals > 0 && (buffer.length - characters - 1) == decimals) { buffer[characters] = bytes1(uint8(46)); decimals = 0; // Cut off any further checks for the decimal place } else if (value != 0) { buffer[characters] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } else { buffer[characters] = bytes1(uint8(48)); } } if (isNegative) { buffer[0] = bytes1(uint8(45)); } return buffer; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "base64-sol/base64.sol"; /// @title OnChain metadata support library /** * @dev These methods are best suited towards view/pure only function calls (ALL the way through the call stack). * Do not waste gas using these methods in functions that also update state, unless your need requires it. */ library OnChain { /// Returns the prefix needed for a base64-encoded on chain svg image function baseSvgImageURI() internal pure returns (bytes memory) { return "data:image/svg+xml;base64,"; } /// Returns the prefix needed for a base64-encoded on chain nft metadata function baseURI() internal pure returns (bytes memory) { return "data:application/json;base64,"; } /// Returns the contents joined with a comma between them /// @param contents1 The first content to join /// @param contents2 The second content to join /// @return A collection of bytes that represent all contents joined with a comma function commaSeparated(bytes memory contents1, bytes memory contents2) internal pure returns (bytes memory) { return abi.encodePacked(contents1, continuesWith(contents2)); } /// Returns the contents joined with commas between them /// @param contents1 The first content to join /// @param contents2 The second content to join /// @param contents3 The third content to join /// @return A collection of bytes that represent all contents joined with commas function commaSeparated(bytes memory contents1, bytes memory contents2, bytes memory contents3) internal pure returns (bytes memory) { return abi.encodePacked(commaSeparated(contents1, contents2), continuesWith(contents3)); } /// Returns the contents joined with commas between them /// @param contents1 The first content to join /// @param contents2 The second content to join /// @param contents3 The third content to join /// @param contents4 The fourth content to join /// @return A collection of bytes that represent all contents joined with commas function commaSeparated(bytes memory contents1, bytes memory contents2, bytes memory contents3, bytes memory contents4) internal pure returns (bytes memory) { return abi.encodePacked(commaSeparated(contents1, contents2, contents3), continuesWith(contents4)); } /// Returns the contents joined with commas between them /// @param contents1 The first content to join /// @param contents2 The second content to join /// @param contents3 The third content to join /// @param contents4 The fourth content to join /// @param contents5 The fifth content to join /// @return A collection of bytes that represent all contents joined with commas function commaSeparated(bytes memory contents1, bytes memory contents2, bytes memory contents3, bytes memory contents4, bytes memory contents5) internal pure returns (bytes memory) { return abi.encodePacked(commaSeparated(contents1, contents2, contents3, contents4), continuesWith(contents5)); } /// Returns the contents joined with commas between them /// @param contents1 The first content to join /// @param contents2 The second content to join /// @param contents3 The third content to join /// @param contents4 The fourth content to join /// @param contents5 The fifth content to join /// @param contents6 The sixth content to join /// @return A collection of bytes that represent all contents joined with commas function commaSeparated(bytes memory contents1, bytes memory contents2, bytes memory contents3, bytes memory contents4, bytes memory contents5, bytes memory contents6) internal pure returns (bytes memory) { return abi.encodePacked(commaSeparated(contents1, contents2, contents3, contents4, contents5), continuesWith(contents6)); } /// Returns the contents prefixed by a comma /// @dev This is used to append multiple attributes into the json /// @param contents The contents with which to prefix /// @return A bytes collection of the contents prefixed with a comma function continuesWith(bytes memory contents) internal pure returns (bytes memory) { return abi.encodePacked(",", contents); } /// Returns the contents wrapped in a json dictionary /// @param contents The contents with which to wrap /// @return A bytes collection of the contents wrapped as a json dictionary function dictionary(bytes memory contents) internal pure returns (bytes memory) { return abi.encodePacked("{", contents, "}"); } /// Returns an unwrapped key/value pair where the value is an array /// @param key The name of the key used in the pair /// @param value The value of pair, as an array /// @return A bytes collection that is suitable for inclusion in a larger dictionary function keyValueArray(string memory key, bytes memory value) internal pure returns (bytes memory) { return abi.encodePacked("\"", key, "\":[", value, "]"); } /// Returns an unwrapped key/value pair where the value is a string /// @param key The name of the key used in the pair /// @param value The value of pair, as a string /// @return A bytes collection that is suitable for inclusion in a larger dictionary function keyValueString(string memory key, bytes memory value) internal pure returns (bytes memory) { return abi.encodePacked("\"", key, "\":\"", value, "\""); } /// Encodes an SVG as base64 and prefixes it with a URI scheme suitable for on-chain data /// @param svg The contents of the svg /// @return A bytes collection that may be added to the "image" key/value pair in ERC-721 or ERC-1155 metadata function svgImageURI(bytes memory svg) internal pure returns (bytes memory) { return abi.encodePacked(baseSvgImageURI(), Base64.encode(svg)); } /// Encodes json as base64 and prefixes it with a URI scheme suitable for on-chain data /// @param metadata The contents of the metadata /// @return A bytes collection that may be returned as the tokenURI in a ERC-721 or ERC-1155 contract function tokenURI(bytes memory metadata) internal pure returns (bytes memory) { return abi.encodePacked(baseURI(), Base64.encode(metadata)); } /// Returns the json dictionary of a single trait attribute for an ERC-721 or ERC-1155 NFT /// @param name The name of the trait /// @param value The value of the trait /// @return A collection of bytes that can be embedded within a larger array of attributes function traitAttribute(string memory name, bytes memory value) internal pure returns (bytes memory) { return dictionary(commaSeparated( keyValueString("trait_type", bytes(name)), keyValueString("value", value) )); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./RandomizationErrors.sol"; /// @title Randomization library /// @dev Lightweight library used for basic randomization capabilities for ERC-721 tokens when an Oracle is not available library Randomization { /// Returns a value based on the spread of a random uint8 seed and provided percentages /// @dev The last percentage is assumed if the sum of all elements do not add up to 100, in which case the length of the array is returned /// @param random A uint8 random value /// @param percentages An array of percentages /// @return The index in which the random seed falls, which can be the length of the input array if the values do not add up to 100 function randomIndex(uint8 random, uint8[] memory percentages) internal pure returns (uint256) { uint256 spread = (3921 * uint256(random) / 10000) % 100; // 0-255 needs to be balanced to evenly spread with % 100 uint256 remainingPercent = 100; for (uint256 i = 0; i < percentages.length; i++) { uint256 nextPercentage = percentages[i]; if (remainingPercent < nextPercentage) revert PercentagesGreaterThan100(); remainingPercent -= nextPercentage; if (spread >= remainingPercent) { return i; } } return percentages.length; } /// Returns a random seed suitable for ERC-721 attribute generation when an Oracle such as Chainlink VRF is not available to a contract /// @dev Not suitable for mission-critical code. Always be sure to perform an analysis of your randomization before deploying to production /// @param initialSeed A uint256 that seeds the randomization function /// @return A seed that can be used for attribute generation, which may also be used as the `initialSeed` for a future call function randomSeed(uint256 initialSeed) internal view returns (uint256) { // Unit tests should confirm that this provides a more-or-less even spread of randomness return uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), msg.sender, initialSeed >> 1))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @dev When the percentages array sum up to more than 100 error PercentagesGreaterThan100(); // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/ISVGTypes.sol"; import "./OnChain.sol"; import "./SVGErrors.sol"; /// @title SVG image library /** * @dev These methods are best suited towards view/pure only function calls (ALL the way through the call stack). * Do not waste gas using these methods in functions that also update state, unless your need requires it. */ library SVG { using Strings for uint256; /// Returns a named element based on the supplied attributes and contents /// @dev attributes and contents is usually generated from abi.encodePacked, attributes is expecting a leading space /// @param name The name of the element /// @param attributes The attributes of the element, as bytes, with a leading space /// @param contents The contents of the element, as bytes /// @return a bytes collection representing the whole element function createElement(string memory name, bytes memory attributes, bytes memory contents) internal pure returns (bytes memory) { return abi.encodePacked( "<", attributes.length == 0 ? bytes(name) : abi.encodePacked(name, attributes), contents.length == 0 ? bytes("/>") : abi.encodePacked(">", contents, "</", name, ">") ); } /// Returns the root SVG attributes based on the supplied width and height /// @dev includes necessary leading space for createElement's `attributes` parameter /// @param width The width of the SVG view box /// @param height The height of the SVG view box /// @return a bytes collection representing the root SVG attributes, including a leading space function svgAttributes(uint256 width, uint256 height) internal pure returns (bytes memory) { return abi.encodePacked(" viewBox='0 0 ", width.toString(), " ", height.toString(), "' xmlns='http://www.w3.org/2000/svg'"); } /// Returns an RGB bytes collection suitable as an attribute for SVG elements based on the supplied Color and ColorType /// @dev includes necessary leading space for all types _except_ None /// @param attribute The `ISVGTypes.ColorAttribute` of the desired attribute /// @param value The converted color value as bytes /// @return a bytes collection representing a color attribute in an SVG element function colorAttribute(ISVGTypes.ColorAttribute attribute, bytes memory value) internal pure returns (bytes memory) { if (attribute == ISVGTypes.ColorAttribute.Fill) return _attribute("fill", value); if (attribute == ISVGTypes.ColorAttribute.Stop) return _attribute("stop-color", value); return _attribute("stroke", value); // Fallback to Stroke } /// Returns an RGB color attribute value /// @param color The `ISVGTypes.Color` of the color /// @return a bytes collection representing the url attribute value function colorAttributeRGBValue(ISVGTypes.Color memory color) internal pure returns (bytes memory) { return _colorValue(ISVGTypes.ColorAttributeKind.RGB, OnChain.commaSeparated( bytes(uint256(color.red).toString()), bytes(uint256(color.green).toString()), bytes(uint256(color.blue).toString()) )); } /// Returns a URL color attribute value /// @param url The url to the color /// @return a bytes collection representing the url attribute value function colorAttributeURLValue(bytes memory url) internal pure returns (bytes memory) { return _colorValue(ISVGTypes.ColorAttributeKind.URL, url); } /// Returns an `ISVGTypes.Color` that is brightened by the provided percentage /// @param source The `ISVGTypes.Color` to brighten /// @param percentage The percentage of brightness to apply /// @param minimumBump A minimum increase for each channel to ensure dark Colors also brighten /// @return color the brightened `ISVGTypes.Color` function brightenColor(ISVGTypes.Color memory source, uint32 percentage, uint8 minimumBump) internal pure returns (ISVGTypes.Color memory color) { color.red = _brightenComponent(source.red, percentage, minimumBump); color.green = _brightenComponent(source.green, percentage, minimumBump); color.blue = _brightenComponent(source.blue, percentage, minimumBump); color.alpha = source.alpha; } /// Returns an `ISVGTypes.Color` based on a packed representation of r, g, and b /// @notice Useful for code where you want to utilize rgb hex values provided by a designer (e.g. #835525) /// @dev Alpha will be hard-coded to 100% opacity /// @param packedColor The `ISVGTypes.Color` to convert, e.g. 0x835525 /// @return color representing the packed input function fromPackedColor(uint24 packedColor) internal pure returns (ISVGTypes.Color memory color) { color.red = uint8(packedColor >> 16); color.green = uint8(packedColor >> 8); color.blue = uint8(packedColor); color.alpha = 0xFF; } /// Returns a mixed Color by balancing the ratio of `color1` over `color2`, with a total percentage (for overmixing and undermixing outside the source bounds) /// @dev Reverts with `RatioInvalid()` if `ratioPercentage` is > 100 /// @param color1 The first `ISVGTypes.Color` to mix /// @param color2 The second `ISVGTypes.Color` to mix /// @param ratioPercentage The percentage ratio of `color1` over `color2` (e.g. 60 = 60% first, 40% second) /// @param totalPercentage The total percentage after mixing (for overmixing and undermixing outside the input colors) /// @return color representing the result of the mixture function mixColors(ISVGTypes.Color memory color1, ISVGTypes.Color memory color2, uint32 ratioPercentage, uint32 totalPercentage) internal pure returns (ISVGTypes.Color memory color) { if (ratioPercentage > 100) revert RatioInvalid(); color.red = _mixComponents(color1.red, color2.red, ratioPercentage, totalPercentage); color.green = _mixComponents(color1.green, color2.green, ratioPercentage, totalPercentage); color.blue = _mixComponents(color1.blue, color2.blue, ratioPercentage, totalPercentage); color.alpha = _mixComponents(color1.alpha, color2.alpha, ratioPercentage, totalPercentage); } /// Returns a proportionally-randomized Color between the start and stop colors using a random Color seed /// @dev Each component (r,g,b) will move proportionally together in the direction from start to stop /// @param start The starting bound of the `ISVGTypes.Color` to randomize /// @param stop The stopping bound of the `ISVGTypes.Color` to randomize /// @param random An `ISVGTypes.Color` to use as a seed for randomization /// @return color representing the result of the randomization function randomizeColors(ISVGTypes.Color memory start, ISVGTypes.Color memory stop, ISVGTypes.Color memory random) internal pure returns (ISVGTypes.Color memory color) { uint16 percent = uint16((1320 * (uint(random.red) + uint(random.green) + uint(random.blue)) / 10000) % 101); // Range is from 0-100 color.red = _randomizeComponent(start.red, stop.red, random.red, percent); color.green = _randomizeComponent(start.green, stop.green, random.green, percent); color.blue = _randomizeComponent(start.blue, stop.blue, random.blue, percent); color.alpha = 0xFF; } function _attribute(bytes memory name, bytes memory contents) private pure returns (bytes memory) { return abi.encodePacked(" ", name, "='", contents, "'"); } function _brightenComponent(uint8 component, uint32 percentage, uint8 minimumBump) private pure returns (uint8 result) { uint32 wideComponent = uint32(component); uint32 brightenedComponent = wideComponent * (percentage + 100) / 100; uint32 wideMinimumBump = uint32(minimumBump); if (brightenedComponent - wideComponent < wideMinimumBump) { brightenedComponent = wideComponent + wideMinimumBump; } if (brightenedComponent > 0xFF) { result = 0xFF; // Clamp to 8 bits } else { result = uint8(brightenedComponent); } } function _colorValue(ISVGTypes.ColorAttributeKind attributeKind, bytes memory contents) private pure returns (bytes memory) { return abi.encodePacked(attributeKind == ISVGTypes.ColorAttributeKind.RGB ? "rgb(" : "url(#", contents, ")"); } function _mixComponents(uint8 component1, uint8 component2, uint32 ratioPercentage, uint32 totalPercentage) private pure returns (uint8 component) { uint32 mixedComponent = (uint32(component1) * ratioPercentage + uint32(component2) * (100 - ratioPercentage)) * totalPercentage / 10000; if (mixedComponent > 0xFF) { component = 0xFF; // Clamp to 8 bits } else { component = uint8(mixedComponent); } } function _randomizeComponent(uint8 start, uint8 stop, uint8 random, uint16 percent) private pure returns (uint8 component) { if (start == stop) { component = start; } else { // This is the standard case (uint8 floor, uint8 ceiling) = start < stop ? (start, stop) : (stop, start); component = floor + uint8(uint16(ceiling - (random & 0x01) - floor) * percent / uint16(100)); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @dev When the ratio percentage provided to a function is > 100 error RatioInvalid(); // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides functions for encoding/decoding base64 library Base64 { string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000" hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000" hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000" hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } function decode(string memory _data) internal pure returns (bytes memory) { bytes memory data = bytes(_data); if (data.length == 0) return new bytes(0); require(data.length % 4 == 0, "invalid base64 decoder input"); // load the table into memory bytes memory table = TABLE_DECODE; // every 4 characters represent 3 bytes uint256 decodedLen = (data.length / 4) * 3; // add some extra buffer at the end required for the writing bytes memory result = new bytes(decodedLen + 32); assembly { // padding with '=' let lastBytes := mload(add(data, mload(data))) if eq(and(lastBytes, 0xFF), 0x3d) { decodedLen := sub(decodedLen, 1) if eq(and(lastBytes, 0xFFFF), 0x3d3d) { decodedLen := sub(decodedLen, 1) } } // set the actual output length mstore(result, decodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 4 characters at a time for {} lt(dataPtr, endPtr) {} { // read 4 characters dataPtr := add(dataPtr, 4) let input := mload(dataPtr) // write 3 bytes let output := add( add( shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)), shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))), add( shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)), and(mload(add(tablePtr, and( input , 0xFF))), 0xFF) ) ) mstore(resultPtr, shl(232, output)) resultPtr := add(resultPtr, 3) } } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IBear3Traits.sol"; /// @title Gen 3 TwoBitBear traits provider /// @notice Provides IBear3Traits to the blockchain interface IBear3TraitProvider{ /// Returns the traits associated with a given token ID /// @dev Throws if the token ID is not valid /// @param tokenId The ID of the token that represents the Bear /// @return traits memory function bearTraits(uint256 tokenId) external view returns (IBear3Traits.Traits memory); /// Returns whether a Gen 2 Bear (TwoBitCubs) has breeded a Gen 3 TwoBitBear /// @dev Does not throw if the tokenId is not valid /// @param tokenId The token ID of the Gen 2 bear /// @return Returns whether the Gen 2 Bear has mated function hasGen2Mated(uint256 tokenId) external view returns (bool); /// Returns whether a Gen 3 Bear has produced a Gen 4 TwoBitBear /// @dev Throws if the token ID is not valid /// @param tokenId The token ID of the Gen 3 bear /// @return Returns whether the Gen 3 Bear has been used for Gen 4 minting function generation4Claimed(uint256 tokenId) external view returns (bool); /// Returns the scar colors of a given token Id /// @dev Throws if the token ID is not valid or if not revealed /// @param tokenId The token ID of the Gen 3 bear /// @return Returns the scar colors function scarColors(uint256 tokenId) external view returns (IBear3Traits.ScarColor[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Gen 3 TwoBitBear traits /// @notice Describes the traits of a Gen 3 TwoBitBear interface IBear3Traits { /// Represents the backgrounds of a Gen 3 TwoBitBear enum BackgroundType { White, Green, Blue } /// Represents the scars of a Gen 3 TwoBitBear enum ScarColor { None, Blue, Magenta, Gold } /// Represents the species of a Gen 3 TwoBitBear enum SpeciesType { Brown, Black, Polar, Panda } /// Represents the mood of a Gen 3 TwoBitBear enum MoodType { Happy, Hungry, Sleepy, Grumpy, Cheerful, Excited, Snuggly, Confused, Ravenous, Ferocious, Hangry, Drowsy, Cranky, Furious } /// Represents the traits of a Gen 3 TwoBitBear struct Traits { BackgroundType background; MoodType mood; SpeciesType species; bool gen4Claimed; uint8 nameIndex; uint8 familyIndex; uint16 firstParentTokenId; uint16 secondParentTokenId; uint176 genes; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IBear3Traits.sol"; /// @title Main Tech for Gen 3 TwoBitBear rendering /// @dev Supports the ERC-721 contract interface IBearRenderTech { /// Returns the text of a background based on the supplied type /// @param background The BackgroundType /// @return The background text function backgroundForType(IBear3Traits.BackgroundType background) external pure returns (string memory); /// Creates the SVG for a Gen 3 TwoBitBear given its IBear3Traits.Traits and Token Id /// @dev Passes rendering on to a specific species' IBearRenderer /// @param traits The Bear's traits structure /// @param tokenId The Bear's Token Id /// @return The raw xml as bytes function createSvg(IBear3Traits.Traits memory traits, uint256 tokenId) external view returns (bytes memory); /// Returns the family of a Gen 3 TwoBitBear as a string /// @param traits The Bear's traits structure /// @return The family text function familyForTraits(IBear3Traits.Traits memory traits) external view returns (string memory); /// @dev Returns the ERC-721 for a Gen 3 TwoBitBear given its IBear3Traits.Traits and Token Id /// @param traits The Bear's traits structure /// @param tokenId The Bear's Token Id /// @return The raw json as bytes function metadata(IBear3Traits.Traits memory traits, uint256 tokenId) external view returns (bytes memory); /// Returns the text of a mood based on the supplied type /// @param mood The MoodType /// @return The mood text function moodForType(IBear3Traits.MoodType mood) external pure returns (string memory); /// Returns the name of a Gen 3 TwoBitBear as a string /// @param traits The Bear's traits structure /// @return The name text function nameForTraits(IBear3Traits.Traits memory traits) external view returns (string memory); /// Returns the scar colors of a bear with the provided traits /// @param traits The Bear's traits structure /// @return The array of scar colors function scarsForTraits(IBear3Traits.Traits memory traits) external view returns (IBear3Traits.ScarColor[] memory); /// Returns the text of a scar based on the supplied color /// @param scarColor The ScarColor /// @return The scar color text function scarForType(IBear3Traits.ScarColor scarColor) external pure returns (string memory); /// Returns the text of a species based on the supplied type /// @param species The SpeciesType /// @return The species text function speciesForType(IBear3Traits.SpeciesType species) external pure returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IBear3Traits.sol"; /// @title Bear RenderTech provider /// @dev Provides IBearRenderTech to an IBearRenderer interface IBearRenderTechProvider { /// Represents a point substitution struct Substitution { uint matchingX; uint matchingY; uint replacementX; uint replacementY; } /// Generates an SVG <polygon> element based on a points array and fill color /// @param points The encoded points array /// @param fill The fill attribute /// @param substitutions An array of point substitutions /// @return A <polygon> element as bytes function dynamicPolygonElement(bytes memory points, bytes memory fill, Substitution[] memory substitutions) external view returns (bytes memory); /// Generates an SVG <linearGradient> element based on a points array and stop colors /// @param id The id of the linear gradient /// @param points The encoded points array /// @param stop1 The first stop attribute /// @param stop2 The second stop attribute /// @return A <linearGradient> element as bytes function linearGradient(bytes memory id, bytes memory points, bytes memory stop1, bytes memory stop2) external view returns (bytes memory); /// Generates an SVG <path> element based on a points array and fill color /// @param path The encoded path array /// @param fill The fill attribute /// @return A <path> segment as bytes function pathElement(bytes memory path, bytes memory fill) external view returns (bytes memory); /// Generates an SVG <polygon> segment based on a points array and fill colors /// @param points The encoded points array /// @param fill The fill attribute /// @return A <polygon> segment as bytes function polygonElement(bytes memory points, bytes memory fill) external view returns (bytes memory); /// Generates an SVG <rect> element based on a points array and fill color /// @param widthPercentage The width expressed as a percentage of its container /// @param heightPercentage The height expressed as a percentage of its container /// @param attributes Additional attributes for the <rect> element /// @return A <rect> element as bytes function rectElement(uint256 widthPercentage, uint256 heightPercentage, bytes memory attributes) external view returns (bytes memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@theappstudio/solidity/contracts/interfaces/ISVGTypes.sol"; import "./IBear3Traits.sol"; import "./ICubTraits.sol"; /// @title Gen 3 TwoBitBear Renderer /// @dev Renders a specific species of a Gen 3 TwoBitBear interface IBearRenderer { /// The eye ratio to apply based on the genes and token id /// @param genes The Bear's genes /// @param eyeColor The Bear's eye color /// @param scars Zero, One, or Two ScarColors /// @param tokenId The Bear's Token Id /// @return The eye ratio as a uint8 function customDefs(uint176 genes, ISVGTypes.Color memory eyeColor, IBear3Traits.ScarColor[] memory scars, uint256 tokenId) external view returns (bytes memory); /// Influences the eye color given the dominant parent /// @param dominantParent The Dominant parent bear /// @return The eye color function customEyeColor(ICubTraits.TraitsV1 memory dominantParent) external view returns (ISVGTypes.Color memory); /// The eye ratio to apply based on the genes and token id /// @param genes The Bear's genes /// @param eyeColor The Bear's eye color /// @param tokenId The Bear's Token Id /// @return The eye ratio as a uint8 function customSurfaces(uint176 genes, ISVGTypes.Color memory eyeColor, uint256 tokenId) external view returns (bytes memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ICubTraits.sol"; /// @title TwoBitCubs NFT Interface for provided ICubTraits interface ICubTraitProvider{ /// Returns the family of a TwoBitCub as a string /// @param traits The traits of the Cub /// @return The family text function familyForTraits(ICubTraits.TraitsV1 memory traits) external pure returns (string memory); /// Returns the text of a mood based on the supplied type /// @param moodType The CubMoodType /// @return The mood text function moodForType(ICubTraits.CubMoodType moodType) external pure returns (string memory); /// Returns the mood of a TwoBitCub based on its TwoBitBear parents /// @param firstParentTokenId The ID of the token that represents the first parent /// @param secondParentTokenId The ID of the token that represents the second parent /// @return The mood type function moodFromParents(uint256 firstParentTokenId, uint256 secondParentTokenId) external view returns (ICubTraits.CubMoodType); /// Returns the name of a TwoBitCub as a string /// @param traits The traits of the Cub /// @return The name text function nameForTraits(ICubTraits.TraitsV1 memory traits) external pure returns (string memory); /// Returns the text of a species based on the supplied type /// @param speciesType The CubSpeciesType /// @return The species text function speciesForType(ICubTraits.CubSpeciesType speciesType) external pure returns (string memory); /// Returns the v1 traits associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the Cub /// @return traits memory function traitsV1(uint256 tokenId) external view returns (ICubTraits.TraitsV1 memory traits); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@theappstudio/solidity/contracts/interfaces/ISVGTypes.sol"; /// @title ICubTraits interface interface ICubTraits { /// Represents the species of a TwoBitCub enum CubSpeciesType { Brown, Black, Polar, Panda } /// Represents the mood of a TwoBitCub enum CubMoodType { Happy, Hungry, Sleepy, Grumpy, Cheerful, Excited, Snuggly, Confused, Ravenous, Ferocious, Hangry, Drowsy, Cranky, Furious } /// Represents the DNA for a TwoBitCub /// @dev organized to fit within 256 bits and consume the least amount of resources struct DNA { uint16 firstParentTokenId; uint16 secondParentTokenId; uint224 genes; } /// Represents the v1 traits of a TwoBitCub struct TraitsV1 { uint256 age; ISVGTypes.Color topColor; ISVGTypes.Color bottomColor; uint8 nameIndex; uint8 familyIndex; CubMoodType mood; CubSpeciesType species; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@theappstudio/solidity/contracts/utils/OnChain.sol"; import "@theappstudio/solidity/contracts/utils/Randomization.sol"; import "../interfaces/IBear3TraitProvider.sol"; import "../interfaces/ICubTraitProvider.sol"; import "../utils/BearRenderTech.sol"; import "../utils/TwoBitBears3Errors.sol"; import "./TwoBitCubs.sol"; /// @title TwoBitBears3 contract TwoBitBears3 is ERC721, IBear3TraitProvider, IERC721Enumerable, Ownable { /// @dev Reference to the BearRenderTech contract IBearRenderTech private immutable _bearRenderTech; /// @dev Stores the cubs Adult Age so that it doesn't need to be queried for every mint uint256 private immutable _cubAdultAge; /// @dev Precalculated eligibility for cubs uint256[] private _cubEligibility; /// @dev Stores bear token ids that have already minted gen 4 mapping(uint256 => bool) private _generation4Claims; /// @dev The contract for Gen 4 address private _gen4Contract; /// @dev Stores cub token ids that have already mated mapping(uint256 => bool) private _matedCubs; /// @dev Seed for randomness uint256 private _seed; /// @dev Array of TokenIds to DNA uint256[] private _tokenIdsToDNA; /// @dev Reference to the TwoBitCubs contract TwoBitCubs private immutable _twoBitCubs; /// Look...at these...Bears constructor(uint256 seed, address renderTech, address twoBitCubs) ERC721("TwoBitBears3", "TB3") { _seed = seed; _bearRenderTech = IBearRenderTech(renderTech); _twoBitCubs = TwoBitCubs(twoBitCubs); _cubAdultAge = _twoBitCubs.ADULT_AGE(); } /// Applies calculated slots of gen 2 eligibility to reduce gas function applySlots(uint256[] calldata slotIndices, uint256[] calldata slotValues) external onlyOwner { for (uint i = 0; i < slotIndices.length; i++) { uint slotIndex = slotIndices[i]; uint slotValue = slotValues[i]; if (slotIndex >= _cubEligibility.length) { while (slotIndex > _cubEligibility.length) { _cubEligibility.push(0); } _cubEligibility.push(slotValue); } else if (_cubEligibility[slotIndex] != slotValue) { _cubEligibility[slotIndex] = slotValue; } } } /// Assigns the Gen 4 contract address for message caller verification function assignGen4(address gen4Contract) external onlyOwner { if (gen4Contract == address(0)) revert InvalidAddress(); _gen4Contract = gen4Contract; } /// @inheritdoc IBear3TraitProvider function bearTraits(uint256 tokenId) external view onlyWhenExists(tokenId) returns (IBear3Traits.Traits memory) { return _traitsForToken(tokenId); } /// Calculates the current values for a slot function calculateSlot(uint256 slotIndex, uint256 totalTokens) external view onlyOwner returns (uint256 slotValue) { uint tokenStart = slotIndex * 32; uint tokenId = tokenStart + 32; if (tokenId > totalTokens) { tokenId = totalTokens; } uint adults = 0; do { tokenId -= 1; slotValue = (slotValue << 8) | _getEligibility(tokenId); if (slotValue >= 0x80) { adults++; } } while (tokenId > tokenStart); if (adults == 0 || (slotIndex < _cubEligibility.length && slotValue == _cubEligibility[slotIndex])) { slotValue = 0; // Reset because there's nothing worth writing } } /// Marks the Gen 3 Bear as having minted a Gen 4 Bear function claimGen4(uint256 tokenId) external onlyWhenExists(tokenId) { if (_gen4Contract == address(0) || _msgSender() != _gen4Contract) revert InvalidCaller(); _generation4Claims[tokenId] = true; } /// @notice For easy import into MetaMask function decimals() external pure returns (uint256) { return 0; } /// @inheritdoc IBear3TraitProvider function hasGen2Mated(uint256 tokenId) external view returns (bool) { return _matedCubs[tokenId]; } /// @inheritdoc IBear3TraitProvider function generation4Claimed(uint256 tokenId) external view onlyWhenExists(tokenId) returns (bool) { return _generation4Claims[tokenId]; } function slotParameters() external view onlyOwner returns (uint256 totalSlots, uint256 totalTokens) { totalTokens = _twoBitCubs.totalSupply(); totalSlots = 1 + totalTokens / 32; } /// Exposes the raw image SVG to the world, for any applications that can take advantage function imageSVG(uint256 tokenId) external view returns (string memory) { return string(_imageBytes(tokenId)); } /// Exposes the image URI to the world, for any applications that can take advantage function imageURI(uint256 tokenId) external view returns (string memory) { return string(OnChain.svgImageURI(_imageBytes(tokenId))); } /// Mints the provided quantity of TwoBitBear3 tokens /// @param parentOne The first gen 2 bear parent, which also determines the mood /// @param parentTwo The second gen 2 bear parent function mateBears(uint256 parentOne, uint256 parentTwo) external { // Check eligibility if (_matedCubs[parentOne]) revert ParentAlreadyMated(parentOne); if (_matedCubs[parentTwo]) revert ParentAlreadyMated(parentTwo); if (_twoBitCubs.ownerOf(parentOne) != _msgSender()) revert ParentNotOwned(parentOne); if (_twoBitCubs.ownerOf(parentTwo) != _msgSender()) revert ParentNotOwned(parentTwo); uint parentOneInfo = _getEligibility(parentOne); uint parentTwoInfo = _getEligibility(parentTwo); uint parentOneSpecies = parentOneInfo & 0x03; if (parentOne == parentTwo || parentOneSpecies != (parentTwoInfo & 0x03)) revert InvalidParentCombination(); if (parentOneInfo < 0x80) revert ParentTooYoung(parentOne); if (parentTwoInfo < 0x80) revert ParentTooYoung(parentTwo); // Prepare mint _matedCubs[parentOne] = true; _matedCubs[parentTwo] = true; uint seed = Randomization.randomSeed(_seed); // seed (208) | parent one (16) | parent two (16) | species (8) | mood (8) uint rawDna = (seed << 48) | (parentOne << 32) | (parentTwo << 16) | (parentOneSpecies << 8) | ((parentOneInfo & 0x7F) >> 2); uint tokenId = _tokenIdsToDNA.length; _tokenIdsToDNA.push(rawDna); _seed = seed; _safeMint(_msgSender(), tokenId, ""); // Reentrancy is possible here } /// @notice Returns expected gas usage based on selected parents, with a small buffer for safety /// @dev Does not check for ownership or whether parents have already mated function matingGas(address minter, uint256 parentOne, uint256 parentTwo) external view returns (uint256 result) { result = 146000; // Lowest gas cost to mint if (_tokenIdsToDNA.length == 0) { result += 16500; } if (balanceOf(minter) == 0) { result += 17500; } // Fetching eligibility of parents will cost additional gas uint fetchCount = 0; if (_eligibility(parentOne) < 0x80) { result += 47000; if (uint(_twoBitCubs.traitsV1(parentOne).mood) >= 4) { result += 33500; } fetchCount += 1; } if (_eligibility(parentTwo) < 0x80) { result += 47000; if (uint(_twoBitCubs.traitsV1(parentTwo).mood) >= 4) { result += 33500; } fetchCount += 1; } // There's some overhead for a single fetch if (fetchCount == 1) { result += 10000; } } /// Prevents a function from executing if the tokenId does not exist modifier onlyWhenExists(uint256 tokenId) { if (!_exists(tokenId)) revert InvalidTokenId(); _; } /// @inheritdoc IBear3TraitProvider function scarColors(uint256 tokenId) external view onlyWhenExists(tokenId) returns (IBear3Traits.ScarColor[] memory) { IBear3Traits.Traits memory traits = _traitsForToken(tokenId); return _bearRenderTech.scarsForTraits(traits); } /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /// @inheritdoc IERC721Enumerable function tokenByIndex(uint256 index) external view returns (uint256) { require(index < this.totalSupply(), "global index out of bounds"); return index; // Burning is not exposed by this contract so we can simply return the index } /// @inheritdoc IERC721Enumerable /// @dev This implementation is for the benefit of web3 sites -- it is extremely expensive for contracts to call on-chain function tokenOfOwnerByIndex(address owner_, uint256 index) external view returns (uint256 tokenId) { require(index < ERC721.balanceOf(owner_), "owner index out of bounds"); for (uint tokenIndex = 0; tokenIndex < _tokenIdsToDNA.length; tokenIndex++) { // Use _exists() to avoid a possible revert when accessing OpenZeppelin's ownerOf(), despite not exposing _burn() if (_exists(tokenIndex) && ownerOf(tokenIndex) == owner_) { if (index == 0) { tokenId = tokenIndex; break; } index--; } } } /// @inheritdoc IERC721Metadata function tokenURI(uint256 tokenId) public view override onlyWhenExists(tokenId) returns (string memory) { IBear3Traits.Traits memory traits = _traitsForToken(tokenId); return string(OnChain.tokenURI(_bearRenderTech.metadata(traits, tokenId))); } /// @inheritdoc IERC721Enumerable function totalSupply() external view returns (uint256) { return _tokenIdsToDNA.length; // We don't expose _burn() so the .length suffices } function _eligibility(uint256 parent) private view returns (uint8 result) { uint slotIndex = parent / 32; if (slotIndex < _cubEligibility.length) { result = uint8(_cubEligibility[slotIndex] >> ((parent % 32) * 8)); } } function _getEligibility(uint256 parent) private view returns (uint8 result) { // Check the precalculated eligibility result = _eligibility(parent); if (result < 0x80) { // We need to go get the latest information from the Cubs contract result = _packedInfo(_twoBitCubs.traitsV1(parent)); } } function _imageBytes(uint256 tokenId) private view onlyWhenExists(tokenId) returns (bytes memory) { IBear3Traits.Traits memory traits = _traitsForToken(tokenId); return _bearRenderTech.createSvg(traits, tokenId); } function _traitsForToken(uint256 tokenId) private view returns (IBear3Traits.Traits memory traits) { uint dna = _tokenIdsToDNA[tokenId]; traits.mood = IBear3Traits.MoodType(dna & 0xFF); traits.species = IBear3Traits.SpeciesType((dna >> 8) & 0xFF); traits.firstParentTokenId = uint16(dna >> 16) & 0xFFFF; traits.secondParentTokenId = uint16(dna >> 32) & 0xFFFF; traits.nameIndex = uint8((dna >> 48) & 0xFF); traits.familyIndex = uint8((dna >> 56) & 0xFF); traits.background = IBear3Traits.BackgroundType(((dna >> 64) & 0xFF) % 3); traits.gen4Claimed = _generation4Claims[tokenId]; traits.genes = uint176(dna >> 80); } function _packedInfo(ICubTraits.TraitsV1 memory traits) private view returns (uint8 info) { info |= uint8(traits.species); info |= uint8(traits.mood) << 2; if (traits.age >= _cubAdultAge) { info |= 0x80; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "../interfaces/ICubTraitProvider.sol"; /// @title TwoBitCubs abstract contract TwoBitCubs is IERC721Enumerable, ICubTraitProvider { /// @dev The number of blocks until a growing cub becomes an adult (roughly 1 week) uint256 public constant ADULT_AGE = 44000; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@theappstudio/solidity/contracts/utils/DecimalStrings.sol"; import "@theappstudio/solidity/contracts/utils/OnChain.sol"; import "@theappstudio/solidity/contracts/utils/Randomization.sol"; import "@theappstudio/solidity/contracts/utils/SVG.sol"; import "./BearRenderTechErrors.sol"; import "../interfaces/ICubTraits.sol"; import "../interfaces/IBear3Traits.sol"; import "../interfaces/IBearRenderer.sol"; import "../interfaces/IBearRenderTech.sol"; import "../interfaces/IBearRenderTechProvider.sol"; import "../tokens/TwoBitCubs.sol"; /// @title BearRendering3 contract BearRenderTech is Ownable, IBearRenderTech, IBearRenderTechProvider { using Strings for uint256; using DecimalStrings for uint256; /// Represents an encoding of a number struct NumberEncoding { uint8 bytesPerPoint; uint8 decimals; bool signed; } /// @dev The Black Bear SVG renderer IBearRenderer private _blackBearRenderer; /// @dev The Brown Bear SVG renderer IBearRenderer private _brownBearRenderer; /// @dev The Panda Bear SVG renderer IBearRenderer private _pandaBearRenderer; /// @dev The Polar Bear SVG renderer IBearRenderer private _polarBearRenderer; /// @dev Reference to the TwoBitCubs contract TwoBitCubs private immutable _twoBitCubs; /// @dev Controls the reveal bool private _wenReveal; /// Look...at these...Bears constructor(address twoBitCubs) { _twoBitCubs = TwoBitCubs(twoBitCubs); } /// Applies the four IBearRenderers /// @param blackRenderer The Black Bear renderer /// @param brownRenderer The Brown Bear renderer /// @param pandaRenderer The Panda Bear renderer /// @param polarRenderer The Polar Bear renderer function applyRenderers(address blackRenderer, address brownRenderer, address pandaRenderer, address polarRenderer) external onlyOwner { if (address(_blackBearRenderer) != address(0) || address(_brownBearRenderer) != address(0) || address(_pandaBearRenderer) != address(0) || address(_polarBearRenderer) != address(0)) revert AlreadyConfigured(); _blackBearRenderer = IBearRenderer(blackRenderer); _brownBearRenderer = IBearRenderer(brownRenderer); _pandaBearRenderer = IBearRenderer(pandaRenderer); _polarBearRenderer = IBearRenderer(polarRenderer); } function backgroundForType(IBear3Traits.BackgroundType background) public pure returns (string memory) { string[3] memory backgrounds = ["White Tundra", "Green Forest", "Blue Shore"]; return backgrounds[uint(background)]; } /// @inheritdoc IBearRenderTech function createSvg(IBear3Traits.Traits memory traits, uint256 tokenId) public view onlyWenRevealed returns (bytes memory) { IBearRenderer renderer = _rendererForTraits(traits); ISVGTypes.Color memory eyeColor = renderer.customEyeColor(_twoBitCubs.traitsV1(traits.firstParentTokenId)); return SVG.createElement("svg", SVG.svgAttributes(447, 447), abi.encodePacked( _defs(renderer, traits, eyeColor, tokenId), this.rectElement(100, 100, " fill='url(#background)'"), this.pathElement(hex'224d76126b084c81747bfb4381f57cdd821c7de981df7ee74381a37fe5810880c2802f81514c5b3b99a8435a359a5459049aaf57cc9ab0569ab04356939ab055619a55545b99a94c2f678151432e8e80c22df37fe52db77ee7432d7b7de92da17cdd2e227bfb4c39846b0a4c57ca6b0a566b084c76126b085a', "url(#chest)"), this.polygonElement(hex'1207160d0408bc0da20a620d040c0a0a9b08bc0a9b056e0a9b', "url(#neck)"), renderer.customSurfaces(traits.genes, eyeColor, tokenId) )); } /// @inheritdoc IBearRenderTechProvider function dynamicPolygonElement(bytes memory points, bytes memory fill, Substitution[] memory substitutions) external view onlyRenderer returns (bytes memory) { return SVG.createElement("polygon", abi.encodePacked(" points='", _polygonPoints(points, substitutions), "' fill='", fill, "'"), ""); } /// @inheritdoc IBearRenderTech function familyForTraits(IBear3Traits.Traits memory traits) public view override onlyWenRevealed returns (string memory) { string[18] memory families = ["Hirst", "Stark", "xCopy", "Watkinson", "Davis", "Evan Dennis", "Anderson", "Pak", "Greenawalt", "Capacity", "Hobbs", "Deafbeef", "Rainaud", "Snowfro", "Winkelmann", "Fairey", "Nines", "Maeda"]; return families[(uint(uint8(bytes22(traits.genes)[1])) + uint(traits.familyIndex)) % 18]; } /// @inheritdoc IBearRenderTechProvider function linearGradient(bytes memory id, bytes memory points, bytes memory stop1, bytes memory stop2) external view onlyRenderer returns (bytes memory) { string memory stop = "stop"; NumberEncoding memory encoding = _readEncoding(points); bytes memory attributes = abi.encodePacked( " id='", id, "' x1='", _decimalStringFromBytes(points, 1, encoding), "' x2='", _decimalStringFromBytes(points, 1 + encoding.bytesPerPoint, encoding), "' y1='", _decimalStringFromBytes(points, 1 + 2 * encoding.bytesPerPoint, encoding), "' y2='", _decimalStringFromBytes(points, 1 + 3 * encoding.bytesPerPoint, encoding), "'" ); return SVG.createElement("linearGradient", attributes, abi.encodePacked( SVG.createElement(stop, stop1, ""), SVG.createElement(stop, stop2, "") )); } /// @inheritdoc IBearRenderTech function metadata(IBear3Traits.Traits memory traits, uint256 tokenId) external view returns (bytes memory) { string memory token = tokenId.toString(); if (_wenReveal) { return OnChain.dictionary(OnChain.commaSeparated( OnChain.keyValueString("name", abi.encodePacked(nameForTraits(traits), " ", familyForTraits(traits), " the ", moodForType(traits.mood), " ", speciesForType(traits.species), " Bear ", token)), OnChain.keyValueArray("attributes", _attributesFromTraits(traits)), OnChain.keyValueString("image", OnChain.svgImageURI(bytes(createSvg(traits, tokenId)))) )); } return OnChain.dictionary(OnChain.commaSeparated( OnChain.keyValueString("name", abi.encodePacked("Rendering Bear ", token)), OnChain.keyValueString("image", "ipfs://QmUZ3ojSLv3rbu8egkS5brb4ETkNXXmcgCFG66HeFBXn54") )); } /// @inheritdoc IBearRenderTech function moodForType(IBear3Traits.MoodType mood) public pure override returns (string memory) { string[14] memory moods = ["Happy", "Hungry", "Sleepy", "Grumpy", "Cheerful", "Excited", "Snuggly", "Confused", "Ravenous", "Ferocious", "Hangry", "Drowsy", "Cranky", "Furious"]; return moods[uint256(mood)]; } /// @inheritdoc IBearRenderTech function nameForTraits(IBear3Traits.Traits memory traits) public view override onlyWenRevealed returns (string memory) { string[50] memory names = ["Cophi", "Trace", "Abel", "Ekko", "Goomba", "Milk", "Arth", "Roeleman", "Adjudicator", "Kelly", "Tropo", "Type3", "Jak", "Srsly", "Triggity", "SNR", "Drogate", "Scott", "Timm", "Nutsaw", "Rugged", "Vaypor", "XeR0", "Toasty", "BN3", "Dunks", "JFH", "Eallen", "Aspen", "Krueger", "Nouside", "Fonky", "Ian", "Metal", "Bones", "Cruz", "Daniel", "Buz", "Bliargh", "Strada", "Lanky", "Westwood", "Rie", "Moon", "Mango", "Hammer", "Pizza", "Java", "Gremlin", "Hash"]; return names[(uint(uint8(bytes22(traits.genes)[0])) + uint(traits.nameIndex)) % 50]; } /// Prevents a function from executing if not called by an authorized party modifier onlyRenderer() { if (_msgSender() != address(_blackBearRenderer) && _msgSender() != address(_brownBearRenderer) && _msgSender() != address(_pandaBearRenderer) && _msgSender() != address(_polarBearRenderer) && _msgSender() != address(this)) revert OnlyRenderer(); _; } /// Prevents a function from executing until wenReveal is set modifier onlyWenRevealed() { if (!_wenReveal) revert NotYetRevealed(); _; } /// @inheritdoc IBearRenderTechProvider function pathElement(bytes memory path, bytes memory fill) external view onlyRenderer returns (bytes memory result) { NumberEncoding memory encoding = _readEncoding(path); bytes memory attributes = " d='"; uint index = 1; while (index < path.length) { bytes1 control = path[index++]; attributes = abi.encodePacked(attributes, control); if (control == "C") { attributes = abi.encodePacked(attributes, _readNext(path, encoding, 6, index)); index += 6 * encoding.bytesPerPoint; } else if (control == "H") { // Not used by any IBearRenderers anymore attributes = abi.encodePacked(attributes, _readNext(path, encoding, 1, index)); index += encoding.bytesPerPoint; } else if (control == "L") { attributes = abi.encodePacked(attributes, _readNext(path, encoding, 2, index)); index += 2 * encoding.bytesPerPoint; } else if (control == "M") { attributes = abi.encodePacked(attributes, _readNext(path, encoding, 2, index)); index += 2 * encoding.bytesPerPoint; } else if (control == "V") { attributes = abi.encodePacked(attributes, _readNext(path, encoding, 1, index)); index += encoding.bytesPerPoint; } } return SVG.createElement("path", abi.encodePacked(attributes, "' fill='", fill, "'"), ""); } /// @inheritdoc IBearRenderTechProvider function polygonElement(bytes memory points, bytes memory fill) external view onlyRenderer returns (bytes memory) { return SVG.createElement("polygon", abi.encodePacked(" points='", _polygonPoints(points, new Substitution[](0)), "' fill='", fill, "'"), ""); } /// @inheritdoc IBearRenderTechProvider function rectElement(uint256 widthPercentage, uint256 heightPercentage, bytes memory attributes) external view onlyRenderer returns (bytes memory) { return abi.encodePacked("<rect width='", widthPercentage.toString(), "%' height='", heightPercentage.toString(), "%'", attributes, "/>"); } /// Wen the world is ready /// @dev Only the contract owner can invoke this function revealBears() external onlyOwner { _wenReveal = true; } /// @inheritdoc IBearRenderTech function scarsForTraits(IBear3Traits.Traits memory traits) public view onlyWenRevealed returns (IBear3Traits.ScarColor[] memory) { bytes22 geneBytes = bytes22(traits.genes); uint8 scarCountProvider = uint8(geneBytes[18]); uint scarCount = Randomization.randomIndex(scarCountProvider, _scarCountPercentages()); IBear3Traits.ScarColor[] memory scars = new IBear3Traits.ScarColor[](scarCount == 0 ? 1 : scarCount); if (scarCount == 0) { scars[0] = IBear3Traits.ScarColor.None; } else { uint8 scarColorProvider = uint8(geneBytes[17]); uint scarColor = Randomization.randomIndex(scarColorProvider, _scarColorPercentages()); for (uint scar = 0; scar < scarCount; scar++) { scars[scar] = IBear3Traits.ScarColor(scarColor+1); } } return scars; } /// @inheritdoc IBearRenderTech function scarForType(IBear3Traits.ScarColor scarColor) public pure override returns (string memory) { string[4] memory scarColors = ["None", "Blue", "Magenta", "Gold"]; return scarColors[uint256(scarColor)]; } /// @inheritdoc IBearRenderTech function speciesForType(IBear3Traits.SpeciesType species) public pure override returns (string memory) { string[4] memory specieses = ["Brown", "Black", "Polar", "Panda"]; return specieses[uint256(species)]; } function _attributesFromTraits(IBear3Traits.Traits memory traits) private view returns (bytes memory) { bytes memory attributes = OnChain.commaSeparated( OnChain.traitAttribute("Species", bytes(speciesForType(traits.species))), OnChain.traitAttribute("Mood", bytes(moodForType(traits.mood))), OnChain.traitAttribute("Background", bytes(backgroundForType(traits.background))), OnChain.traitAttribute("First Name", bytes(nameForTraits(traits))), OnChain.traitAttribute("Last Name (Gen 4 Scene)", bytes(familyForTraits(traits))), OnChain.traitAttribute("Parents", abi.encodePacked("#", uint(traits.firstParentTokenId).toString(), " & #", uint(traits.secondParentTokenId).toString())) ); bytes memory scarAttributes = OnChain.traitAttribute("Scars", _scarDescription(scarsForTraits(traits))); attributes = abi.encodePacked(attributes, OnChain.continuesWith(scarAttributes)); bytes memory gen4Attributes = OnChain.traitAttribute("Gen 4 Claim Status", bytes(traits.gen4Claimed ? "Claimed" : "Unclaimed")); return abi.encodePacked(attributes, OnChain.continuesWith(gen4Attributes)); } function _decimalStringFromBytes(bytes memory encoded, uint startIndex, NumberEncoding memory encoding) private pure returns (bytes memory) { (uint value, bool isNegative) = _uintFromBytes(encoded, startIndex, encoding); return value.toDecimalString(encoding.decimals, isNegative); } function _defs(IBearRenderer renderer, IBear3Traits.Traits memory traits, ISVGTypes.Color memory eyeColor, uint256 tokenId) private view returns (bytes memory) { string[3] memory firstStop = ["#fff", "#F3FCEE", "#EAF4F9"]; string[3] memory lastStop = ["#9C9C9C", "#A6B39E", "#98ADB5"]; return SVG.createElement("defs", "", abi.encodePacked( this.linearGradient("background", hex'32000003ea000003e6', abi.encodePacked(" offset='0.44521' stop-color='", firstStop[uint(traits.background)], "'"), abi.encodePacked(" offset='0.986697' stop-color='", lastStop[uint(traits.background)], "'") ), renderer.customDefs(traits.genes, eyeColor, scarsForTraits(traits), tokenId) )); } function _polygonCoordinateFromBytes(bytes memory encoded, uint startIndex, NumberEncoding memory encoding, Substitution[] memory substitutions) private pure returns (bytes memory) { (uint x, bool xIsNegative) = _uintFromBytes(encoded, startIndex, encoding); (uint y, bool yIsNegative) = _uintFromBytes(encoded, startIndex + encoding.bytesPerPoint, encoding); for (uint index = 0; index < substitutions.length; index++) { if (x == substitutions[index].matchingX && y == substitutions[index].matchingY) { x = substitutions[index].replacementX; y = substitutions[index].replacementY; break; } } return OnChain.commaSeparated(x.toDecimalString(encoding.decimals, xIsNegative), y.toDecimalString(encoding.decimals, yIsNegative)); } function _polygonPoints(bytes memory points, Substitution[] memory substitutions) private pure returns (bytes memory pointsValue) { NumberEncoding memory encoding = _readEncoding(points); pointsValue = abi.encodePacked(_polygonCoordinateFromBytes(points, 1, encoding, substitutions)); uint bytesPerIteration = encoding.bytesPerPoint << 1; // Double because this method processes 2 points at a time for (uint byteIndex = 1 + bytesPerIteration; byteIndex < points.length; byteIndex += bytesPerIteration) { pointsValue = abi.encodePacked(pointsValue, " ", _polygonCoordinateFromBytes(points, byteIndex, encoding, substitutions)); } } function _readEncoding(bytes memory encoded) private pure returns (NumberEncoding memory encoding) { encoding.decimals = uint8(encoded[0] >> 4) & 0xF; encoding.bytesPerPoint = uint8(encoded[0]) & 0x7; encoding.signed = uint8(encoded[0]) & 0x8 == 0x8; } function _readNext(bytes memory encoded, NumberEncoding memory encoding, uint numbers, uint startIndex) private pure returns (bytes memory result) { result = _decimalStringFromBytes(encoded, startIndex, encoding); for (uint index = startIndex + encoding.bytesPerPoint; index < startIndex + (numbers * encoding.bytesPerPoint); index += encoding.bytesPerPoint) { result = abi.encodePacked(result, " ", _decimalStringFromBytes(encoded, index, encoding)); } } function _rendererForTraits(IBear3Traits.Traits memory traits) private view returns (IBearRenderer) { if (traits.species == IBear3Traits.SpeciesType.Black) { return _blackBearRenderer; } else if (traits.species == IBear3Traits.SpeciesType.Brown) { return _brownBearRenderer; } else if (traits.species == IBear3Traits.SpeciesType.Panda) { return _pandaBearRenderer; } else /* if (traits.species == IBear3Traits.SpeciesType.Polar) */ { return _polarBearRenderer; } } function _scarColorPercentages() private pure returns (uint8[] memory percentages) { uint8[] memory array = new uint8[](2); array[0] = 60; // 60% Blue array[1] = 30; // 30% Magenta return array; // 10% Gold } function _scarCountPercentages() private pure returns (uint8[] memory percentages) { uint8[] memory array = new uint8[](2); array[0] = 70; // 70% None array[1] = 20; // 20% One return array; // 10% Two } function _scarDescription(IBear3Traits.ScarColor[] memory scarColors) private pure returns (bytes memory) { if (scarColors.length == 0 || scarColors[0] == IBear3Traits.ScarColor.None) { return bytes(scarForType(IBear3Traits.ScarColor.None)); } else { return abi.encodePacked(scarColors.length.toString(), " ", scarForType(scarColors[0])); } } function _uintFromBytes(bytes memory encoded, uint startIndex, NumberEncoding memory encoding) private pure returns (uint result, bool isNegative) { result = uint8(encoded[startIndex]); if (encoding.signed) { isNegative = result & 0x80 == 0x80; result &= 0x7F; } uint stopIndex = startIndex + encoding.bytesPerPoint; for (uint index = startIndex + 1; index < stopIndex; index++) { result = (result << 8) + uint(uint8(encoded[index])); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @dev When the renderers are already configured error AlreadyConfigured(); /// @dev When Reveal is false error NotYetRevealed(); /// @dev Only the Renderer can make these calls error OnlyRenderer(); // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @dev The address passed in is not allowed error InvalidAddress(); /// @dev The caller of the method is not allowed error InvalidCaller(); /// @dev When the parent identifiers are not unique or not of the same species error InvalidParentCombination(); /// @dev When the TwoBitBear3 tokenId does not exist error InvalidTokenId(); /// @dev When the parent has already mated error ParentAlreadyMated(uint256 tokenId); /// @dev When the parent is not owned by the caller error ParentNotOwned(uint256 tokenId); /// @dev When the parent is not yet an adult error ParentTooYoung(uint256 tokenId);
Returns a mixed Color by balancing the ratio of `color1` over `color2`, with a total percentage (for overmixing and undermixing outside the source bounds) Reverts with `RatioInvalid()` if `ratioPercentage` is > 100 color1 The first `ISVGTypes.Color` to mix color2 The second `ISVGTypes.Color` to mix ratioPercentage The percentage ratio of `color1` over `color2` (e.g. 60 = 60% first, 40% second) totalPercentage The total percentage after mixing (for overmixing and undermixing outside the input colors) return color representing the result of the mixture
function mixColors(ISVGTypes.Color memory color1, ISVGTypes.Color memory color2, uint32 ratioPercentage, uint32 totalPercentage) internal pure returns (ISVGTypes.Color memory color) { if (ratioPercentage > 100) revert RatioInvalid(); color.red = _mixComponents(color1.red, color2.red, ratioPercentage, totalPercentage); color.green = _mixComponents(color1.green, color2.green, ratioPercentage, totalPercentage); color.blue = _mixComponents(color1.blue, color2.blue, ratioPercentage, totalPercentage); color.alpha = _mixComponents(color1.alpha, color2.alpha, ratioPercentage, totalPercentage); }
1,010,220
pragma solidity ^0.4.19; contract ERC20 { // We want to be able to recover & donate any tokens sent to the contract. function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); } contract theCyberInterface { // The utility contract can call the following methods of theCyber. function newMember(uint8 _memberId, bytes32 _memberName, address _memberAddress) public; function proclaimInactive(uint8 _memberId) public; function heartbeat() public; function revokeMembership(uint8 _memberId) public; function getMembershipStatus(address _memberAddress) public view returns (bool member, uint8 memberId); function getMemberInformation(uint8 _memberId) public view returns (bytes32 memberName, string memberKey, uint64 memberSince, uint64 inactiveSince, address memberAddress); function maxMembers() public pure returns(uint16); function inactivityTimeout() public pure returns(uint64); function donationAddress() public pure returns(address); } contract theCyberMemberUtilities { // This contract provides a set of helper functions that members of theCyber // may call in order to perform more advanced operations. In order to interact // with theCyber, the contract must first be assigned as a member. event MembershipStatusSet(bool isMember, uint8 memberId); event FundsDonated(uint256 value); event TokensDonated(address tokenContractAddress, uint256 value); // Set the address and interface of theCyber. address private constant THECYBERADDRESS_ = 0x97A99C819544AD0617F48379840941eFbe1bfAE1; theCyberInterface theCyber = theCyberInterface(THECYBERADDRESS_); // Set up variables for checking the contract's membership status. bool private isMember_; uint8 private memberId_; // The max members, inactivity timeout, and the donation address are pulled // from theCyber inside the constructor function. uint16 private maxMembers_; uint64 private inactivityTimeout_; address private donationAddress_; // Batch operations on all members utilize incrementing member ids. uint8 private nextInactiveMemberIndex_; uint8 private nextRevokedMemberIndex_; // Methods of the utility contract can only be called by a valid member. modifier membersOnly() { // Only allow transactions originating from a valid member address. bool member; (member,) = theCyber.getMembershipStatus(msg.sender); require(member); _; } // In the constructor function, set up the max members, the inactivity // timeout, and the donation address. function theCyberMemberUtilities() public { // Set the maximum number of members. maxMembers_ = theCyber.maxMembers(); // Set the inactivity timeout. inactivityTimeout_ = theCyber.inactivityTimeout(); // Set the donation address. donationAddress_ = theCyber.donationAddress(); // Set the initial membership status to false. isMember_ = false; // Start the inactive member index at 0. nextInactiveMemberIndex_ = 0; // Start the revoked member index at 0. nextRevokedMemberIndex_ = 0; } // Set the member id of the utility contract prior to calling batch methods. function setMembershipStatus() public membersOnly { // Set the membership status and member id of the utility contract. (isMember_,memberId_) = theCyber.getMembershipStatus(this); // Log the membership status of the utility contract. MembershipStatusSet(isMember_, memberId_); } // The utility contract must be able to heartbeat if it is marked as inactive. function heartbeat() public membersOnly { // Heartbeat the utility contract. theCyber.heartbeat(); } // Revoke a membership and immediately assign the membership to a new member. function revokeAndSetNewMember(uint8 _memberId, bytes32 _memberName, address _memberAddress) public membersOnly { // Revoke the membership (provided it has been inactive for long enough). theCyber.revokeMembership(_memberId); // Assign a new member to the membership (provided the new member is valid). theCyber.newMember(_memberId, _memberName, _memberAddress); } // Mark all members (except this contract & msg.sender) as inactive. function proclaimAllInactive() public membersOnly returns (bool complete) { // The utility contract must be a member (and therefore have a member id). require(isMember_); // Get the memberId of the calling member. uint8 callingMemberId; (,callingMemberId) = theCyber.getMembershipStatus(msg.sender); // Initialize variables for checking the status of each membership. uint64 inactiveSince; address memberAddress; // Pick up where the function last left off in assigning new members. uint8 i = nextInactiveMemberIndex_; // make sure that the loop triggers at least once. require(msg.gas > 175000); // Loop through members as long as sufficient gas remains. while (msg.gas > 170000) { // Make sure that the target membership is owned and active. (,,,inactiveSince,memberAddress) = theCyber.getMemberInformation(i); if ((i != memberId_) && (i != callingMemberId) && (memberAddress != address(0)) && (inactiveSince == 0)) { // Mark the member as inactive. theCyber.proclaimInactive(i); } // Increment the index to point to the next member id. i++; // exit once the index overflows. if (i == 0) { break; } } // Set the index where the function left off. nextInactiveMemberIndex_ = i; return (i == 0); } // Allow members to circumvent the safety measure against self-inactivation. function inactivateSelf() public membersOnly { // Get the memberId of the calling member. uint8 memberId; (,memberId) = theCyber.getMembershipStatus(msg.sender); // Inactivate the membership (provided it is not already marked inactive). theCyber.proclaimInactive(memberId); } // Revoke all members that have been inactive for longer than the timeout. function revokeAllVulnerable() public membersOnly returns (bool complete) { // The utility contract must be a member (and therefore have a member id). require(isMember_); // Get the memberId of the calling member. uint8 callingMemberId; (,callingMemberId) = theCyber.getMembershipStatus(msg.sender); // Initialize variables for checking the status of each membership. uint64 inactiveSince; address memberAddress; // Pick up where the function last left off in assigning new members. uint8 i = nextRevokedMemberIndex_; // make sure that the loop triggers at least once. require(msg.gas > 175000); // Loop through members as long as sufficient gas remains. while (msg.gas > 175000) { // Make sure that the target membership is owned and inactive long enough. (,,,inactiveSince,memberAddress) = theCyber.getMemberInformation(i); if ((i != memberId_) && (i != callingMemberId) && (memberAddress != address(0)) && (inactiveSince != 0) && (now >= inactiveSince + inactivityTimeout_)) { // Revoke the member. theCyber.revokeMembership(i); } // Increment the index to point to the next member id. i++; // exit once the index overflows. if (i == 0) { break; } } // Set the index where the function left off. nextRevokedMemberIndex_ = i; return (i == 0); } // Allow members to circumvent the safety measure against self-revokation. function revokeSelf() public membersOnly { // Get the memberId of the calling member. uint8 memberId; (,memberId) = theCyber.getMembershipStatus(msg.sender); // Revoke the membership (provided it has been inactive for long enough). theCyber.revokeMembership(memberId); } // The contract is not payable by design, but could end up with a balance as // a recipient of a selfdestruct / coinbase of a mined block. function donateFunds() public membersOnly { // Log the donation of any funds that have made their way into the contract. FundsDonated(this.balance); // Send all available funds to the donation address. donationAddress_.transfer(this.balance); } // We also want to be able to access any tokens that are sent to the contract. function donateTokens(address _tokenContractAddress) public membersOnly { // Make sure that we didn't pass in the current contract address by mistake. require(_tokenContractAddress != address(this)); // Log the donation of any tokens that have been sent into the contract. TokensDonated(_tokenContractAddress, ERC20(_tokenContractAddress).balanceOf(this)); // Send all available tokens at the given contract to the donation address. ERC20(_tokenContractAddress).transfer(donationAddress_, ERC20(_tokenContractAddress).balanceOf(this)); } // The donation address for lost ether / ERC20 tokens should match theCyber's. function donationAddress() public view returns(address) { return donationAddress_; } }
The donation address for lost ether / ERC20 tokens should match theCyber's.
function donationAddress() public view returns(address) { return donationAddress_; }
5,455,449
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; // 导包 import "../@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../@openzeppelin/contracts/math/SafeMath.sol"; import "../@openzeppelin/contracts/utils/Address.sol"; import "../@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../interfaces/yearn/IProxy.sol"; import "../../interfaces/curve/Mintr.sol"; contract StrategyProxy { // 扩展这些类型 using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // 初始化值 IProxy public constant proxy = IProxy(0xF147b8125d2ef93FB6965Db97D6746952a133934); address public constant mintr = address(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0); address public constant crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52); address public constant gauge = address(0x2F50D538606Fa9EDD2B11E2446BEb18C9D5846bB); address public constant y = address(0xFA712EE4788C042e2B7BB55E6cb8ec569C4530c1); mapping(address => bool) public strategies; address public governance; // 构造函数 对 governance 赋值 constructor() public { governance = msg.sender; } // 声明需要交互对象本人(合约) function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } // 在mapping 里增加 _strategy, true 的映射关系 function approveStrategy(address _strategy) external { require(msg.sender == governance, "!governance"); strategies[_strategy] = true; } // 将mapping 中的 _strategy映射置为 false function revokeStrategy(address _strategy) external { require(msg.sender == governance, "!governance"); strategies[_strategy] = false; } // proxy 拥有的代币数量 function lock() external { uint256 amount = IERC20(crv).balanceOf(address(proxy)); if (amount > 0) proxy.increaseAmount(amount); } // 在strategies里映射为true的对象,proxy 回调 参数为_gauge, _amount 的vote_for_gauge_weights函数 function vote(address _gauge, uint256 _amount) public { require(strategies[msg.sender], "!strategy"); proxy.execute(gauge, 0, abi.encodeWithSignature("vote_for_gauge_weights(address,uint256)", _gauge, _amount)); } // 在strategies里映射为true的对象,返还 数量为_amount的代币 function withdraw( address _gauge, address _token, uint256 _amount ) public returns (uint256) { require(strategies[msg.sender], "!strategy"); uint256 _before = IERC20(_token).balanceOf(address(proxy)); proxy.execute(_gauge, 0, abi.encodeWithSignature("withdraw(uint256)", _amount)); // 计算花费由 proxy 承担 uint256 _after = IERC20(_token).balanceOf(address(proxy)); uint256 _net = _after.sub(_before); proxy.execute(_token, 0, abi.encodeWithSignature("transfer(address,uint256)", msg.sender, _net)); return _net; } // 返回 proxy 账户代币数量 function balanceOf(address _gauge) public view returns (uint256) { return IERC20(_gauge).balanceOf(address(proxy)); } // 调用withdraw,返还_gauge 对象的 账户金额 function withdrawAll(address _gauge, address _token) external returns (uint256) { require(strategies[msg.sender], "!strategy"); return withdraw(_gauge, _token, balanceOf(_gauge)); } // _gauge 向proxy 转账 function deposit(address _gauge, address _token) external { require(strategies[msg.sender], "!strategy"); uint256 _balance = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(address(proxy), _balance); _balance = IERC20(_token).balanceOf(address(proxy)); proxy.execute(_token, 0, abi.encodeWithSignature("approve(address,uint256)", _gauge, 0)); proxy.execute(_token, 0, abi.encodeWithSignature("approve(address,uint256)", _gauge, _balance)); (bool success, ) = proxy.execute(_gauge, 0, abi.encodeWithSignature("deposit(uint256)", _balance)); if (!success) assert(false); } // 给proxy 发放津贴 function harvest(address _gauge) external { require(strategies[msg.sender], "!strategy"); uint256 _before = IERC20(crv).balanceOf(address(proxy)); proxy.execute(mintr, 0, abi.encodeWithSignature("mint(address)", _gauge)); uint256 _after = IERC20(crv).balanceOf(address(proxy)); uint256 _balance = _after.sub(_before); proxy.execute(crv, 0, abi.encodeWithSignature("transfer(address,uint256)", msg.sender, _balance)); } }
将mapping 中的 _strategy映射置为 false
function revokeStrategy(address _strategy) external { require(msg.sender == governance, "!governance"); strategies[_strategy] = false; }
5,456,054
./full_match/1/0xd920556b0f3522bB1257923292A256F1e3023e07/sources/SimpleFarm.sol
Reports earned amount by wallet address not yet collected/
function earned( address _walletAddress ) public view returns (uint256) { uint256 difference = rewardPerToken() - perTokenPaid[_walletAddress]; return _balances[_walletAddress] * difference / PRECISION + userRewards[_walletAddress]; }
9,746,324
pragma solidity ^0.5.2; import "./CereneumData.sol"; contract CereneumImplementation is CereneumData { using SafeMath for uint256; //Events event ClaimEvent( uint256 nOriginalClaimAmount, uint256 nAmountGranted, uint256 nBonuses, uint256 nPenalties, bool bWasReferred ); event StartStakeEvent( uint256 nAmount, uint256 nDays ); event CompoundInterestEvent( uint256 nInterestCompounded ); event EndStakeEvent( uint256 nPrincipal, uint256 nPayout, uint256 nDaysServed, uint256 nPenalty, uint256 nStakeShares, uint256 nDaysCommitted ); event EndStakeForAFriendEvent( uint256 nShares, uint256 tStakeEndTimeCommit ); event StartEthStakeEvent( uint256 nEthAmount ); event EndEthStakeEvent( uint256 nPayout ); /// @dev Returns the number of current stakes for given address. /// @param a_address Address of stake to lookup /// @return The number of stakes. function GetNumberOfStakes( address a_address ) external view returns (uint256) { return m_staked[a_address].length; } /// @dev Returns the number of current Eth pool stakes for given address. /// @param a_address Address of stake to lookup /// @return The number of stakes. function GetNumberOfEthPoolStakes( address a_address ) external view returns (uint256) { return m_EthereumStakers[a_address].length; } /// @dev Returns the timestamp until the next daily update /// @return The time until the next daily update. function GetTimeUntilNextDailyUpdate() external view returns (uint256) { uint256 nDay = 1 days; return nDay.sub((block.timestamp.sub(m_tContractLaunchTime)).mod(1 days)); } /// @dev Calculates difference between 2 timestamps in days /// @param a_nStartTime beginning timestamp /// @param a_nEndTime ending timestamp /// @return Difference between timestamps in days function DifferenceInDays( uint256 a_nStartTime, uint256 a_nEndTime ) public pure returns (uint256) { return (a_nEndTime.sub(a_nStartTime).div(1 days)); } /// @dev Calculates the number of days since contract launch for a given timestamp. /// @param a_tTimestamp Timestamp to calculate from /// @return Number of days into contract function TimestampToDaysSinceLaunch( uint256 a_tTimestamp ) public view returns (uint256) { return (a_tTimestamp.sub(m_tContractLaunchTime).div(1 days)); } /// @dev Gets the number of days since the launch of the contract /// @return Number of days since contract launch function DaysSinceLaunch() public view returns (uint256) { return (TimestampToDaysSinceLaunch(block.timestamp)); } /// @dev Checks if we're still in the claimable phase (first 52 weeks) /// @return Boolean on if we are still in the claimable phase function IsClaimablePhase() public view returns (bool) { return (DaysSinceLaunch() < 364); } /// @dev Starts a 1 day stake in the ETH pool. Requires minimum of 0.01 ETH function StartEthStake() external payable { //Require the minimum value for staking require(msg.value >= 0.01 ether, "ETH Sent not above minimum value"); require(DaysSinceLaunch() >= m_nClaimPhaseBufferDays, "Eth Pool staking doesn't begin until after the buffer window"); UpdateDailyData(); m_EthereumStakers[msg.sender].push( EthStakeStruct( msg.value, // Ethereum staked DaysSinceLaunch() //Day staked ) ); emit StartEthStakeEvent( msg.value ); m_nTotalEthStaked = m_nTotalEthStaked.add(msg.value); } /// @dev The default function function() external payable { } /// @dev Withdraw CER from the Eth pool after stake has completed /// @param a_nIndex The index of the stake to be withdrawn function WithdrawFromEthPool(uint256 a_nIndex) external { //Require that the stake index doesn't go out of bounds require(m_EthereumStakers[msg.sender].length > a_nIndex, "Eth stake does not exist"); UpdateDailyData(); uint256 nDay = m_EthereumStakers[msg.sender][a_nIndex].nDay; require(nDay < DaysSinceLaunch(), "Must wait until next day to withdraw"); uint256 nAmount = m_EthereumStakers[msg.sender][a_nIndex].nAmount; uint256 nPayoutAmount = m_dailyDataMap[nDay].nPayoutAmount.div(10); //10% uint256 nEthPoolPayout = nPayoutAmount.mul(nAmount) .div(m_dailyDataMap[nDay].nTotalEthStaked); _mint(msg.sender, nEthPoolPayout); emit EndEthStakeEvent( nEthPoolPayout ); uint256 nEndingIndex = m_EthereumStakers[msg.sender].length.sub(1); //Only copy if we aren't removing the last index if(nEndingIndex != a_nIndex) { //Copy last stake in array over stake we are removing m_EthereumStakers[msg.sender][a_nIndex] = m_EthereumStakers[msg.sender][nEndingIndex]; } //Lower array length by 1 m_EthereumStakers[msg.sender].length = nEndingIndex; } /// @dev Transfers ETH in the contract to the genesis address /// Only callable once every 12 weeks. function TransferContractETH() external { require(address(this).balance != 0, "No Eth to transfer"); require(m_nLastEthWithdrawalTime.add(12 weeks) <= block.timestamp, "Can only withdraw once every 3 months"); m_EthGenesis.transfer(address(this).balance); m_nLastEthWithdrawalTime = block.timestamp; } /// @dev Updates and stores the global interest for each day. /// Additionally adds the frenzy/prosperous bonuses and the Early/Late unstake penalties. /// This function gets called at the start of popular public functions to continuously update. function UpdateDailyData() public { for(m_nLastUpdatedDay; DaysSinceLaunch() > m_nLastUpdatedDay; m_nLastUpdatedDay++) { //Gives 5% inflation per 365 days uint256 nPayoutRound = totalSupply().div(7300); uint256 nUnclaimedCoins = 0; //Frenzy/Prosperous bonuses and Unclaimed redistribution only available during claims phase. if(m_nLastUpdatedDay < 364) { nUnclaimedCoins = m_nMaxRedeemable.sub(m_nTotalRedeemed); nUnclaimedCoins = GetRobinHoodMonthlyAmount(nUnclaimedCoins, m_nLastUpdatedDay); nPayoutRound = nPayoutRound.add(nUnclaimedCoins); //Pay frenzy and Prosperous bonuses to genesis address _mint(m_genesis, nPayoutRound.mul(m_nRedeemedCount).div(m_nUTXOCountAtSnapshot)); // Frenzy _mint(m_genesis, nPayoutRound.mul(m_nTotalRedeemed).div(m_nAdjustedMaxRedeemable)); // Prosperous nPayoutRound = nPayoutRound.add( //Frenzy bonus 0-100% based on total users claiming nPayoutRound.mul(m_nRedeemedCount).div(m_nUTXOCountAtSnapshot) ).add( //Prosperous bonus 0-100% based on size of claims nPayoutRound.mul(m_nTotalRedeemed).div(m_nAdjustedMaxRedeemable) ); } else { //If we are not in the claimable phase anymore apply the voted on interest multiplier //First we need to check if there is a new "most voted on" multiplier uint8 nVoteMultiplier = 1; uint256 nVoteCount = m_votingMultiplierMap[1]; for(uint8 i=2; i <= 10; i++) { if(m_votingMultiplierMap[i] > nVoteCount) { nVoteCount = m_votingMultiplierMap[i]; nVoteMultiplier = i; } } nPayoutRound = nPayoutRound.mul(nVoteMultiplier); //Store last interest multiplier for public viewing m_nInterestMultiplier = nVoteMultiplier; } //Add nPayoutRound to contract's balance _mint(address(this), nPayoutRound.sub(nUnclaimedCoins)); //Add early and late unstake pool to payout round if(m_nEarlyAndLateUnstakePool != 0) { nPayoutRound = nPayoutRound.add(m_nEarlyAndLateUnstakePool); //Reset back to 0 for next day m_nEarlyAndLateUnstakePool = 0; } //Store daily data m_dailyDataMap[m_nLastUpdatedDay] = DailyDataStuct( nPayoutRound, m_nTotalStakeShares, m_nTotalEthStaked ); m_nTotalEthStaked = 0; } } /// @dev Gets the circulating supply (total supply minus staked coins). /// @return Circulating Supply function GetCirculatingSupply() external view returns (uint256) { return totalSupply().sub(balanceOf(address(this))); } /// @dev Verify a Merkle proof using the UTXO Merkle tree /// @param a_hMerkleTreeBranches Merkle tree branches from leaf to root /// @param a_hMerkleLeaf Merkle leaf hash that must be present in the UTXO Merkle tree /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC /// @return Boolean on validity of proof function VerifyProof( bytes32[] memory a_hMerkleTreeBranches, bytes32 a_hMerkleLeaf, BlockchainType a_nWhichChain ) public view returns (bool) { require(uint8(a_nWhichChain) >= 0 && uint8(a_nWhichChain) <= 4, "Invalid blockchain option"); return MerkleProof.verify(a_hMerkleTreeBranches, m_hMerkleTreeRootsArray[uint8(a_nWhichChain)], a_hMerkleLeaf); } /// @dev Validate the ECDSA parameters of signed message /// ECDSA public key associated with the specified Ethereum address /// @param a_addressClaiming Address within signed message /// @param a_publicKeyX X parameter of uncompressed ECDSA public key /// @param a_publicKeyY Y parameter of uncompressed ECDSA public key /// @param a_v v parameter of ECDSA signature /// @param a_r r parameter of ECDSA signature /// @param a_s s parameter of ECDSA signature /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC /// @return Boolean on if the signature is valid function ECDSAVerify( address a_addressClaiming, bytes32 a_publicKeyX, bytes32 a_publicKeyY, uint8 a_v, bytes32 a_r, bytes32 a_s, BlockchainType a_nWhichChain ) public pure returns (bool) { bytes memory addressAsHex = GenerateSignatureMessage(a_addressClaiming, a_nWhichChain); bytes32 hHash; if(a_nWhichChain != BlockchainType.Ethereum) //All Bitcoin chains and Litecoin do double sha256 hash { hHash = sha256(abi.encodePacked(sha256(abi.encodePacked(addressAsHex)))); } else //Otherwise ETH { hHash = keccak256(abi.encodePacked(addressAsHex)); } return ValidateSignature( hHash, a_v, a_r, a_s, PublicKeyToEthereumAddress(a_publicKeyX, a_publicKeyY) ); } /// @dev Convert an uncompressed ECDSA public key into an Ethereum address /// @param a_publicKeyX X parameter of uncompressed ECDSA public key /// @param a_publicKeyY Y parameter of uncompressed ECDSA public key /// @return Ethereum address generated from the ECDSA public key function PublicKeyToEthereumAddress( bytes32 a_publicKeyX, bytes32 a_publicKeyY ) public pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(a_publicKeyX, a_publicKeyY)); return address(uint160(uint256((hash)))); } /// @dev Calculate the Bitcoin-style address associated with an ECDSA public key /// @param a_publicKeyX First half of ECDSA public key /// @param a_publicKeyY Second half of ECDSA public key /// @param a_nAddressType Whether BTC/LTC is Legacy or Segwit address and if it was compressed /// @return Raw Bitcoin address function PublicKeyToBitcoinAddress( bytes32 a_publicKeyX, bytes32 a_publicKeyY, AddressType a_nAddressType ) public pure returns (bytes20) { bytes20 publicKey; uint8 initialByte; if(a_nAddressType == AddressType.LegacyCompressed || a_nAddressType == AddressType.SegwitCompressed) { //Hash the compressed format initialByte = (uint256(a_publicKeyY) & 1) == 0 ? 0x02 : 0x03; publicKey = ripemd160(abi.encodePacked(sha256(abi.encodePacked(initialByte, a_publicKeyX)))); } else { //Hash the uncompressed format initialByte = 0x04; publicKey = ripemd160(abi.encodePacked(sha256(abi.encodePacked(initialByte, a_publicKeyX, a_publicKeyY)))); } if(a_nAddressType == AddressType.LegacyUncompressed || a_nAddressType == AddressType.LegacyCompressed) { return publicKey; } else if(a_nAddressType == AddressType.SegwitUncompressed || a_nAddressType == AddressType.SegwitCompressed) { return ripemd160(abi.encodePacked(sha256(abi.encodePacked(hex"0014", publicKey)))); } } /// @dev Appends an Ethereum address onto the expected string for a Bitcoin signed message /// @param a_address Ethereum address /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC /// @return Correctly formatted message for bitcoin signing function GenerateSignatureMessage( address a_address, BlockchainType a_nWhichChain ) public pure returns(bytes memory) { bytes16 hexDigits = "0123456789abcdef"; bytes memory prefix; uint8 nPrefixLength = 0; //One of the bitcoin chains if(a_nWhichChain >= BlockchainType.Bitcoin && a_nWhichChain <= BlockchainType.BitcoinSV) { nPrefixLength = 46; prefix = new bytes(nPrefixLength); prefix = "\x18Bitcoin Signed Message:\n\x3CClaim_Cereneum_to_0x"; } else if(a_nWhichChain == BlockchainType.Ethereum) //Ethereum chain { nPrefixLength = 48; prefix = new bytes(nPrefixLength); prefix = "\x19Ethereum Signed Message:\n60Claim_Cereneum_to_0x"; } else //Otherwise LTC { nPrefixLength = 47; prefix = new bytes(nPrefixLength); prefix = "\x19Litecoin Signed Message:\n\x3CClaim_Cereneum_to_0x"; } bytes20 addressBytes = bytes20(a_address); bytes memory message = new bytes(nPrefixLength + 40); uint256 nOffset = 0; for(uint i = 0; i < nPrefixLength; i++) { message[nOffset++] = prefix[i]; } for(uint i = 0; i < 20; i++) { message[nOffset++] = hexDigits[uint256(uint8(addressBytes[i] >> 4))]; message[nOffset++] = hexDigits[uint256(uint8(addressBytes[i] & 0x0f))]; } return message; } /// @dev Validate ECSDA signature was signed by the specified address /// @param a_hash Hash of signed data /// @param a_v v parameter of ECDSA signature /// @param a_r r parameter of ECDSA signature /// @param a_s s parameter of ECDSA signature /// @param a_address Ethereum address matching the signature /// @return Boolean on if the signature is valid function ValidateSignature( bytes32 a_hash, uint8 a_v, bytes32 a_r, bytes32 a_s, address a_address ) public pure returns (bool) { return ecrecover( a_hash, a_v, a_r, a_s ) == a_address; } /// @dev Verify that a UTXO with the Merkle leaf hash can be claimed /// @param a_hMerkleLeafHash Merkle tree hash of the UTXO to be checked /// @param a_hMerkleTreeBranches Merkle tree branches from leaf to root /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC /// @return Boolean on if the UTXO from the given hash can be redeemed function CanClaimUTXOHash( bytes32 a_hMerkleLeafHash, bytes32[] memory a_hMerkleTreeBranches, BlockchainType a_nWhichChain ) public view returns (bool) { //Check that the UTXO has not yet been redeemed and that it exists in the Merkle tree return( (m_claimedUTXOsMap[uint8(a_nWhichChain)][a_hMerkleLeafHash] == false) && VerifyProof(a_hMerkleTreeBranches, a_hMerkleLeafHash, a_nWhichChain) ); } /// @dev Check if address can make a claim /// @param a_addressRedeeming Raw Bitcoin address (no base58-check encoding) /// @param a_nAmount Amount of UTXO to redeem /// @param a_hMerkleTreeBranches Merkle tree branches from leaf to root /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC /// @return Boolean on if the UTXO can be redeemed function CanClaim( bytes20 a_addressRedeeming, uint256 a_nAmount, bytes32[] memory a_hMerkleTreeBranches, BlockchainType a_nWhichChain ) public view returns (bool) { //Calculate the hash of the Merkle leaf associated with this UTXO bytes32 hMerkleLeafHash = keccak256( abi.encodePacked( a_addressRedeeming, a_nAmount ) ); //Check if it can be redeemed return CanClaimUTXOHash(hMerkleLeafHash, a_hMerkleTreeBranches, a_nWhichChain); } /// @dev Calculates the monthly Robin Hood reward /// @param a_nAmount The amount to calculate from /// @param a_nDaysSinceLaunch The number of days since contract launch /// @return The amount after applying monthly Robin Hood calculation function GetRobinHoodMonthlyAmount(uint256 a_nAmount, uint256 a_nDaysSinceLaunch) public pure returns (uint256) { uint256 nScaledAmount = a_nAmount.mul(1000000000000); uint256 nScalar = 400000000000000; // 0.25% //Month 1 - 0.25% late penalty if(a_nDaysSinceLaunch < 43) { return nScaledAmount.div(nScalar.mul(29)); } //Month 2 - Additional 0.5% penalty // 0.25% + 0.5% = .75% else if(a_nDaysSinceLaunch < 72) { nScalar = 200000000000000; // 0.5% return nScaledAmount.div(nScalar.mul(29)); } //Month 3 - Additional 0.75% penalty // 0.25% + 0.5% + .75% = 1.5% else if(a_nDaysSinceLaunch < 101) { nScalar = 133333333333333; // 0.75% return nScaledAmount.div(nScalar.mul(29)); } //Month 4 - Additional 1.5% // 0.25% + 0.5% + .75% + 1.5% = 3% else if(a_nDaysSinceLaunch < 130) { nScalar = 66666666666666; // 1.5% return nScaledAmount.div(nScalar.mul(29)); } //Month 5 - Additional 3% // 0.25% + 0.5% + .75% + 1.5% + 3% = 6% else if(a_nDaysSinceLaunch < 159) { nScalar = 33333333333333; // 3% return nScaledAmount.div(nScalar.mul(29)); } //Month 6 - Additional 6% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% = 12% else if(a_nDaysSinceLaunch < 188) { nScalar = 16666666666666; // 6% return nScaledAmount.div(nScalar.mul(29)); } //Month 7 - Additional 8% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% = 20% else if(a_nDaysSinceLaunch < 217) { nScalar = 12499999999999; // 8% return nScaledAmount.div(nScalar.mul(29)); } //Month 8 - Additional 10% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% = 30% else if(a_nDaysSinceLaunch < 246) { nScalar = 10000000000000; // 10% return nScaledAmount.div(nScalar.mul(29)); } //Month 9 - Additional 12.5% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% + 12.5% = 42.5% else if(a_nDaysSinceLaunch < 275) { nScalar = 7999999999999; // 12.5% return nScaledAmount.div(nScalar.mul(29)); } //Month 10 - Additional 15% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% + 12.5% + 15% = 57.5% else if(a_nDaysSinceLaunch < 304) { nScalar = 6666666666666; // 15% return nScaledAmount.div(nScalar.mul(29)); } //Month 11 - Additional 17.5% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% + 12.5% + 15% + 17.5% = 75% else if(a_nDaysSinceLaunch < 334) { nScalar = 5714285714290; // 17.5% return nScaledAmount.div(nScalar.mul(30)); } //Month 12 - Additional 25% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% + 12.5% + 15% + 17.5% + 25% = 100% else if(a_nDaysSinceLaunch < 364) { nScalar = 4000000000000; // 25% return nScaledAmount.div(nScalar.mul(30)); } } /// @dev Calculates the monthly late penalty /// @param a_nAmount The amount to calculate from /// @param a_nDaysSinceLaunch The number of days since contract launch /// @return The amount after applying monthly late penalty function GetMonthlyLatePenalty(uint256 a_nAmount, uint256 a_nDaysSinceLaunch) public pure returns (uint256) { if(a_nDaysSinceLaunch <= m_nClaimPhaseBufferDays) { return 0; } uint256 nScaledAmount = a_nAmount.mul(1000000000000); uint256 nPreviousMonthPenalty = 0; uint256 nScalar = 400000000000000; // 0.25% //Month 1 - 0.25% late penalty if(a_nDaysSinceLaunch <= 43) { a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(14); return nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); } //Month 2 - Additional 0.5% penalty // 0.25% + 0.5% = .75% else if(a_nDaysSinceLaunch <= 72) { nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(43); nScalar = 200000000000000; // 0.5% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 3 - Additional 0.75% penalty // 0.25% + 0.5% + .75% = 1.5% else if(a_nDaysSinceLaunch <= 101) { nScalar = 133333333333333; // 0.75% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(72); nScalar = 133333333333333; // 0.75% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 4 - Additional 1.5% // 0.25% + 0.5% + .75% + 1.5% = 3% else if(a_nDaysSinceLaunch <= 130) { nScalar = 66666666666666; // 1.5% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(101); nScalar = 66666666666666; // 1.5% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 5 - Additional 3% // 0.25% + 0.5% + .75% + 1.5% + 3% = 6% else if(a_nDaysSinceLaunch <= 159) { nScalar = 33333333333333; // 3% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(130); nScalar = 33333333333333; // 3% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 6 - Additional 6% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% = 12% else if(a_nDaysSinceLaunch <= 188) { nScalar = 16666666666666; // 6% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(159); nScalar = 16666666666666; // 6% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 7 - Additional 8% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% = 20% else if(a_nDaysSinceLaunch <= 217) { nScalar = 8333333333333; // 12% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(188); nScalar = 12499999999999; // 8% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 8 - Additional 10% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% = 30% else if(a_nDaysSinceLaunch <= 246) { nScalar = 5000000000000; // 20% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(217); nScalar = 10000000000000; // 10% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 9 - Additional 12.5% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% + 12.5% = 42.5% else if(a_nDaysSinceLaunch <= 275) { nScalar = 3333333333333; // 30% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(246); nScalar = 7999999999999; // 12.5% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 10 - Additional 15% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% + 12.5% + 15% = 57.5% else if(a_nDaysSinceLaunch <= 304) { nScalar = 2352941176472; // 42.5% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(275); nScalar = 6666666666666; // 15% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 11 - Additional 17.5% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% + 12.5% + 15% + 17.5% = 75% else if(a_nDaysSinceLaunch <= 334) { nScalar = 1739130434782; // 57.5% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(304); nScalar = 5714285714290; // 17.5% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(30)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 12 - Additional 25% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% + 12.5% + 15% + 17.5% + 25% = 100% else if(a_nDaysSinceLaunch < 364) { nScalar = 1333333333333; // 75% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(334); nScalar = 4000000000000; // 25% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(30)); return nScaledAmount.add(nPreviousMonthPenalty); } else { return a_nAmount; } } /// @dev Returns claim amount with deduction based on weeks since contract launch. /// @param a_nAmount Amount of claim from UTXO /// @return Amount after any late penalties function GetLateClaimAmount(uint256 a_nAmount) internal view returns (uint256) { uint256 nDaysSinceLaunch = DaysSinceLaunch(); return a_nAmount.sub(GetMonthlyLatePenalty(a_nAmount, nDaysSinceLaunch)); } /// @dev Calculates speed bonus for claiming early /// @param a_nAmount Amount of claim from UTXO /// @return Speed bonus amount function GetSpeedBonus(uint256 a_nAmount) internal view returns (uint256) { uint256 nDaysSinceLaunch = DaysSinceLaunch(); //We give a two week buffer after contract launch before penalties if(nDaysSinceLaunch < m_nClaimPhaseBufferDays) { nDaysSinceLaunch = 0; } else { nDaysSinceLaunch = nDaysSinceLaunch.sub(m_nClaimPhaseBufferDays); } uint256 nMaxDays = 350; a_nAmount = a_nAmount.div(5); return a_nAmount.mul(nMaxDays.sub(nDaysSinceLaunch)).div(nMaxDays); } /// @dev Gets the redeem amount with the blockchain ratio applied. /// @param a_nAmount Amount of UTXO in satoshis /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC /// @return Amount with blockchain ratio applied function GetRedeemRatio(uint256 a_nAmount, BlockchainType a_nWhichChain) internal view returns (uint256) { if(a_nWhichChain != BlockchainType.Bitcoin) { uint8 nWhichChain = uint8(a_nWhichChain); --nWhichChain; //Many zeros to avoid rounding errors uint256 nScalar = 100000000000000000; uint256 nRatio = nScalar.div(m_blockchainRatios[nWhichChain]); a_nAmount = a_nAmount.mul(1000000000000).div(nRatio); } return a_nAmount; } /// @dev Gets the redeem amount and bonuses based on time since contract launch /// @param a_nAmount Amount of UTXO in satoshis /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC /// @return Claim amount, bonuses and penalty function GetRedeemAmount(uint256 a_nAmount, BlockchainType a_nWhichChain) public view returns (uint256, uint256, uint256) { a_nAmount = GetRedeemRatio(a_nAmount, a_nWhichChain); uint256 nAmount = GetLateClaimAmount(a_nAmount); uint256 nBonus = GetSpeedBonus(a_nAmount); return (nAmount, nBonus, a_nAmount.sub(nAmount)); } /// @dev Verify claim ownership from signed message /// @param a_nAmount Amount of UTXO claim /// @param a_hMerkleTreeBranches Merkle tree branches from leaf to root /// @param a_addressClaiming Ethereum address within signed message /// @param a_pubKeyX First half of uncompressed ECDSA public key from signed message /// @param a_pubKeyY Second half of uncompressed ECDSA public key from signed message /// @param a_nAddressType Whether BTC/LTC is Legacy or Segwit address /// @param a_v v parameter of ECDSA signature /// @param a_r r parameter of ECDSA signature /// @param a_s s parameter of ECDSA signature /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC function ValidateOwnership( uint256 a_nAmount, bytes32[] memory a_hMerkleTreeBranches, address a_addressClaiming, bytes32 a_pubKeyX, bytes32 a_pubKeyY, AddressType a_nAddressType, uint8 a_v, bytes32 a_r, bytes32 a_s, BlockchainType a_nWhichChain ) internal { //Calculate the UTXO Merkle leaf hash for the correct chain bytes32 hMerkleLeafHash; if(a_nWhichChain != BlockchainType.Ethereum) //All Bitcoin chains and Litecoin have the same raw address format { hMerkleLeafHash = keccak256(abi.encodePacked(PublicKeyToBitcoinAddress(a_pubKeyX, a_pubKeyY, a_nAddressType), a_nAmount)); } else //Otherwise ETH { hMerkleLeafHash = keccak256(abi.encodePacked(PublicKeyToEthereumAddress(a_pubKeyX, a_pubKeyY), a_nAmount)); } //Require that the UTXO can be redeemed require(CanClaimUTXOHash(hMerkleLeafHash, a_hMerkleTreeBranches, a_nWhichChain), "UTXO Cannot be redeemed."); //Verify the ECDSA parameters match the signed message require( ECDSAVerify( a_addressClaiming, a_pubKeyX, a_pubKeyY, a_v, a_r, a_s, a_nWhichChain ), "ECDSA verification failed." ); //Save the UTXO as redeemed in the global map m_claimedUTXOsMap[uint8(a_nWhichChain)][hMerkleLeafHash] = true; } /// @dev Claim tokens from a UTXO at snapshot block /// granting CER tokens proportional to amount of UTXO. /// BCH, BSV, ETH & LTC chains get proportional BTC ratio awards. /// @param a_nAmount Amount of UTXO /// @param a_hMerkleTreeBranches Merkle tree branches from leaf to root /// @param a_addressClaiming The Ethereum address for the claimed CER tokens to be sent to /// @param a_publicKeyX X parameter of uncompressed ECDSA public key from UTXO /// @param a_publicKeyY Y parameter of uncompressed ECDSA public key from UTXO /// @param a_nAddressType Whether BTC/LTC is Legacy or Segwit address and if it was compressed /// @param a_v v parameter of ECDSA signature /// @param a_r r parameter of ECDSA signature /// @param a_s s parameter of ECDSA signature /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC /// @param a_referrer Optional address of referrer. Address(0) for no referral /// @return The number of tokens redeemed, if successful function Claim( uint256 a_nAmount, bytes32[] memory a_hMerkleTreeBranches, address a_addressClaiming, bytes32 a_publicKeyX, bytes32 a_publicKeyY, AddressType a_nAddressType, uint8 a_v, bytes32 a_r, bytes32 a_s, BlockchainType a_nWhichChain, address a_referrer ) public returns (uint256) { //No claims after the first 50 weeks of contract launch require(IsClaimablePhase(), "Claim is outside of claims period."); require(uint8(a_nWhichChain) >= 0 && uint8(a_nWhichChain) <= 4, "Incorrect blockchain value."); require(a_v <= 30 && a_v >= 27, "V parameter is invalid."); ValidateOwnership( a_nAmount, a_hMerkleTreeBranches, a_addressClaiming, a_publicKeyX, a_publicKeyY, a_nAddressType, a_v, a_r, a_s, a_nWhichChain ); UpdateDailyData(); m_nTotalRedeemed = m_nTotalRedeemed.add(GetRedeemRatio(a_nAmount, a_nWhichChain)); (uint256 nTokensRedeemed, uint256 nBonuses, uint256 nPenalties) = GetRedeemAmount(a_nAmount, a_nWhichChain); //Transfer coins from contracts wallet to claim wallet _transfer(address(this), a_addressClaiming, nTokensRedeemed); //Mint speed bonus to claiming address _mint(a_addressClaiming, nBonuses); //Speed bonus matched for genesis address _mint(m_genesis, nBonuses); m_nRedeemedCount = m_nRedeemedCount.add(1); if(a_referrer != address(0)) { //Grant 10% bonus token to the person being referred _mint(a_addressClaiming, nTokensRedeemed.div(10)); nBonuses = nBonuses.add(nTokensRedeemed.div(10)); //Grant 20% bonus of tokens to referrer _mint(a_referrer, nTokensRedeemed.div(5)); //Match referral bonus for genesis address (20% for referral and 10% for claimer referral = 30%) _mint(m_genesis, nTokensRedeemed.mul(1000000000000).div(3333333333333)); } emit ClaimEvent( a_nAmount, nTokensRedeemed, nBonuses, nPenalties, a_referrer != address(0) ); //Return the number of tokens redeemed return nTokensRedeemed.add(nBonuses); } /// @dev Calculates stake payouts for a given stake /// @param a_nStakeShares Number of shares to calculate payout for /// @param a_tLockTime Starting timestamp of stake /// @param a_tEndTime Ending timestamp of stake /// @return payout amount function CalculatePayout( uint256 a_nStakeShares, uint256 a_tLockTime, uint256 a_tEndTime ) public view returns (uint256) { if(m_nLastUpdatedDay == 0) return 0; uint256 nPayout = 0; uint256 tStartDay = TimestampToDaysSinceLaunch(a_tLockTime); //Calculate what day stake was closed uint256 tEndDay = TimestampToDaysSinceLaunch(a_tEndTime); //Iterate through each day and sum up the payout for(uint256 i = tStartDay; i < tEndDay; i++) { uint256 nDailyPayout = m_dailyDataMap[i].nPayoutAmount.mul(a_nStakeShares) .div(m_dailyDataMap[i].nTotalStakeShares); //Keep sum of payouts nPayout = nPayout.add(nDailyPayout); } return nPayout; } /// @dev Updates current amount of stake to apply compounding interest /// @notice This applies all of your earned interest to future payout calculations /// @param a_nStakeIndex index of stake to compound interest for function CompoundInterest( uint256 a_nStakeIndex ) external { require(m_nLastUpdatedDay != 0, "First update day has not finished."); //Get a reference to the stake to save gas from constant map lookups StakeStruct storage rStake = m_staked[msg.sender][a_nStakeIndex]; require(block.timestamp < rStake.tEndStakeCommitTime, "Stake has already matured."); UpdateDailyData(); uint256 nInterestEarned = CalculatePayout( rStake.nSharesStaked, rStake.tLastCompoundedUpdateTime, block.timestamp ); if(nInterestEarned != 0) { rStake.nCompoundedPayoutAccumulated = rStake.nCompoundedPayoutAccumulated.add(nInterestEarned); rStake.nSharesStaked = rStake.nSharesStaked.add(nInterestEarned); //InterestRateMultiplier votes m_votingMultiplierMap[rStake.nVotedOnMultiplier] = m_votingMultiplierMap[rStake.nVotedOnMultiplier].add(nInterestEarned); m_nTotalStakeShares = m_nTotalStakeShares.add(nInterestEarned); rStake.tLastCompoundedUpdateTime = block.timestamp; emit CompoundInterestEvent( nInterestEarned ); } } /// @dev Starts a stake /// @param a_nAmount Amount of token to stake /// @param a_nDays Number of days to stake /// @param a_nInterestMultiplierVote Pooled interest rate to vote for (1-10 => 5%-50% interest) function StartStake( uint256 a_nAmount, uint256 a_nDays, uint8 a_nInterestMultiplierVote ) external { require(DaysSinceLaunch() >= m_nClaimPhaseBufferDays, "Staking doesn't begin until after the buffer window"); //Verify account has enough tokens require(balanceOf(msg.sender) >= a_nAmount, "Not enough funds for stake."); //Don't allow 0 amount stakes require(a_nAmount > 0, "Stake amount must be greater than 0"); require(a_nDays >= 7, "Stake is under the minimum time required."); require(a_nInterestMultiplierVote >= 1 && a_nInterestMultiplierVote <= 10, "Interest multiplier range is 1-10."); //Calculate Unlock time uint256 tEndStakeCommitTime = block.timestamp.add(a_nDays.mul(1 days)); //Don't allow stakes over the maximum stake time require(tEndStakeCommitTime <= block.timestamp.add(m_nMaxStakingTime), "Stake time exceeds maximum."); UpdateDailyData(); //Calculate bonus interest for longer stake periods (20% bonus per year) uint256 nSharesModifier = 0; //Minimum stake time of 3 months to get amplifier bonus if(a_nDays >= 90) { //We can't have a fractional modifier such as .5 so we need to use whole numbers and divide later nSharesModifier = a_nDays.mul(2000000).div(365); } //20% bonus shares per year of committed stake time uint256 nStakeShares = a_nAmount.add(a_nAmount.mul(nSharesModifier).div(10000000)); //Create and store the stake m_staked[msg.sender].push( StakeStruct( a_nAmount, // nAmountStaked nStakeShares, // nSharesStaked 0, //Accumulated Payout from CompoundInterest block.timestamp, // tLockTime tEndStakeCommitTime, // tEndStakeCommitTime block.timestamp, //tLastCompoundedUpdateTime 0, // tTimeRemovedFromGlobalPool a_nInterestMultiplierVote, true, // bIsInGlobalPool false // bIsLatePenaltyAlreadyPooled ) ); emit StartStakeEvent( a_nAmount, a_nDays ); //InterestRateMultiplier m_votingMultiplierMap[a_nInterestMultiplierVote] = m_votingMultiplierMap[a_nInterestMultiplierVote].add(nStakeShares); //Globally track staked tokens m_nTotalStakedTokens = m_nTotalStakedTokens.add(a_nAmount); //Globally track staked shares m_nTotalStakeShares = m_nTotalStakeShares.add(nStakeShares); //Transfer staked tokens to contract wallet _transfer(msg.sender, address(this), a_nAmount); } /// @dev Calculates penalty for unstaking late /// @param a_tEndStakeCommitTime Timestamp stake matured /// @param a_tTimeRemovedFromGlobalPool Timestamp stake was removed from global pool /// @param a_nInterestEarned Interest earned from stake /// @return penalty value function CalculateLatePenalty( uint256 a_tEndStakeCommitTime, uint256 a_tTimeRemovedFromGlobalPool, uint256 a_nInterestEarned ) public pure returns (uint256) { uint256 nPenalty = 0; //One week grace period if(a_tTimeRemovedFromGlobalPool > a_tEndStakeCommitTime.add(1 weeks)) { //Penalty is 1% per day after the 1 week grace period uint256 nPenaltyPercent = DifferenceInDays(a_tEndStakeCommitTime.add(1 weeks), a_tTimeRemovedFromGlobalPool); //Cap max percent at 100 if(nPenaltyPercent > 100) { nPenaltyPercent = 100; } //Calculate penalty nPenalty = a_nInterestEarned.mul(nPenaltyPercent).div(100); } return nPenalty; } /// @dev Calculates penalty for unstaking early /// @param a_tLockTime Starting timestamp of stake /// @param a_nEndStakeCommitTime Timestamp the stake matures /// @param a_nAmount Amount that was staked /// @param a_nInterestEarned Interest earned from stake /// @return penalty value function CalculateEarlyPenalty( uint256 a_tLockTime, uint256 a_nEndStakeCommitTime, uint256 a_nAmount, uint256 a_nInterestEarned ) public view returns (uint256) { uint256 nPenalty = 0; if(block.timestamp < a_nEndStakeCommitTime) { //If they didn't stake for at least 1 full day we give them no interest //To prevent any abuse if(DifferenceInDays(a_tLockTime, block.timestamp) == 0) { nPenalty = a_nInterestEarned; } else { //Base penalty is half of earned interest nPenalty = a_nInterestEarned.div(2); } uint256 nCommittedStakeDays = DifferenceInDays(a_tLockTime, a_nEndStakeCommitTime); if(nCommittedStakeDays >= 90) { //Take another 10% per year of committed stake nPenalty = nPenalty.add(nPenalty.mul(nCommittedStakeDays).div(3650)); } //5% yearly interest converted to daily interest multiplied by stake time uint256 nMinimumPenalty = a_nAmount.mul(nCommittedStakeDays).div(7300); if(nMinimumPenalty > nPenalty) { nPenalty = nMinimumPenalty; } } return nPenalty; } /// @dev Removes completed stake from global pool /// @notice Removing finished stakes will increase the payout to other stakers. /// @param a_nStakeIndex Index of stake to process /// @param a_address Address of the staker function EndStakeForAFriend( uint256 a_nStakeIndex, address a_address ) external { //Require that the stake index doesn't go out of bounds require(m_staked[a_address].length > a_nStakeIndex, "Stake does not exist"); //Require that the stake has been matured require(block.timestamp > m_staked[a_address][a_nStakeIndex].tEndStakeCommitTime, "Stake must be matured."); ProcessStakeEnding(a_nStakeIndex, a_address, true); } /// @dev Ends a stake, even if it is before it has matured. /// @notice If stake has matured behavior is the same as EndStakeSafely /// @param a_nStakeIndex Index of stake to close function EndStakeEarly( uint256 a_nStakeIndex ) external { //Require that the stake index doesn't go out of bounds require(m_staked[msg.sender].length > a_nStakeIndex, "Stake does not exist"); ProcessStakeEnding(a_nStakeIndex, msg.sender, false); } /// @dev Ends a stake safely. Will only execute if a stake is matured. /// @param a_nStakeIndex Index of stake to close function EndStakeSafely( uint256 a_nStakeIndex ) external { //Require that the stake index doesn't go out of bounds require(m_staked[msg.sender].length > a_nStakeIndex, "Stake does not exist"); //Require that stake is matured require(block.timestamp > m_staked[msg.sender][a_nStakeIndex].tEndStakeCommitTime, "Stake must be matured."); ProcessStakeEnding(a_nStakeIndex, msg.sender, false); } function ProcessStakeEnding( uint256 a_nStakeIndex, address a_address, bool a_bWasForAFriend ) internal { UpdateDailyData(); //Get a reference to the stake to save gas from constant map lookups StakeStruct storage rStake = m_staked[a_address][a_nStakeIndex]; uint256 tEndTime = block.timestamp > rStake.tEndStakeCommitTime ? rStake.tEndStakeCommitTime : block.timestamp; //Calculate Payout uint256 nTotalPayout = CalculatePayout( rStake.nSharesStaked, rStake.tLastCompoundedUpdateTime, tEndTime ); //Add any accumulated interest payout from user calling CompoundInterest nTotalPayout = nTotalPayout.add(rStake.nCompoundedPayoutAccumulated); //Add back the original amount staked nTotalPayout = nTotalPayout.add(rStake.nAmountStaked); //Is stake still in the global pool? if(rStake.bIsInGlobalPool) { //Update global staked token tracking m_nTotalStakedTokens = m_nTotalStakedTokens.sub(rStake.nAmountStaked); //Update global stake shares tracking m_nTotalStakeShares = m_nTotalStakeShares.sub(rStake.nSharesStaked); //InterestRateMultiplier m_votingMultiplierMap[rStake.nVotedOnMultiplier] = m_votingMultiplierMap[rStake.nVotedOnMultiplier].sub(rStake.nSharesStaked); //Set time removed rStake.tTimeRemovedFromGlobalPool = block.timestamp; //Set flag that it is no longer in the global pool rStake.bIsInGlobalPool = false; if(a_bWasForAFriend) { emit EndStakeForAFriendEvent( rStake.nSharesStaked, rStake.tEndStakeCommitTime ); } } //Calculate penalties if any uint256 nPenalty = 0; if(!a_bWasForAFriend) //Can't have an early penalty if it was called by EndStakeForAFriend { nPenalty = CalculateEarlyPenalty( rStake.tLockTime, rStake.tEndStakeCommitTime, rStake.nAmountStaked, nTotalPayout.sub(rStake.nAmountStaked) ); } //Only calculate late penalty if there wasn't an early penalty if(nPenalty == 0) { nPenalty = CalculateLatePenalty( rStake.tEndStakeCommitTime, rStake.tTimeRemovedFromGlobalPool, nTotalPayout.sub(rStake.nAmountStaked) ); } //Don't payout penalty amount that has already been paid out if(nPenalty != 0 && !rStake.bIsLatePenaltyAlreadyPooled) { //Split penalty between genesis and pool m_nEarlyAndLateUnstakePool = m_nEarlyAndLateUnstakePool.add(nPenalty.div(2)); _transfer(address(this), m_genesis, nPenalty.div(2)); } if(a_bWasForAFriend) { //Set flag rStake.bIsLatePenaltyAlreadyPooled = true; } else { //Apply penalty nTotalPayout = nTotalPayout.sub(nPenalty); emit EndStakeEvent( rStake.nAmountStaked, nTotalPayout, block.timestamp < rStake.tEndStakeCommitTime ? DifferenceInDays(rStake.tLockTime, block.timestamp) : DifferenceInDays(rStake.tLockTime, rStake.tTimeRemovedFromGlobalPool), nPenalty, rStake.nSharesStaked, DifferenceInDays(rStake.tLockTime, rStake.tEndStakeCommitTime) ); //Payout staked coins from contract _transfer(address(this), a_address, nTotalPayout); //Remove stake RemoveStake(a_address, a_nStakeIndex); } } /// @dev Remove stake from array /// @param a_address address of staker /// @param a_nStakeIndex index of the stake to delete function RemoveStake( address a_address, uint256 a_nStakeIndex ) internal { uint256 nEndingIndex = m_staked[a_address].length.sub(1); //Only copy if we aren't removing the last index if(nEndingIndex != a_nStakeIndex) { //Copy last stake in array over stake we are removing m_staked[a_address][a_nStakeIndex] = m_staked[a_address][nEndingIndex]; } //Lower array length by 1 m_staked[a_address].length = nEndingIndex; } }
Calculates penalty for unstaking early a_tLockTime Starting timestamp of stake a_nEndStakeCommitTime Timestamp the stake matures a_nAmount Amount that was staked a_nInterestEarned Interest earned from stake return penalty valueIf they didn't stake for at least 1 full day we give them no interestTo prevent any abuseBase penalty is half of earned interestTake another 10% per year of committed stake
function CalculateEarlyPenalty( uint256 a_tLockTime, uint256 a_nEndStakeCommitTime, uint256 a_nAmount, uint256 a_nInterestEarned ) public view returns (uint256) { uint256 nPenalty = 0; if(block.timestamp < a_nEndStakeCommitTime) { if(DifferenceInDays(a_tLockTime, block.timestamp) == 0) { nPenalty = a_nInterestEarned; } else { nPenalty = a_nInterestEarned.div(2); } uint256 nCommittedStakeDays = DifferenceInDays(a_tLockTime, a_nEndStakeCommitTime); if(nCommittedStakeDays >= 90) { nPenalty = nPenalty.add(nPenalty.mul(nCommittedStakeDays).div(3650)); } if(nMinimumPenalty > nPenalty) { nPenalty = nMinimumPenalty; } } return nPenalty; }
5,400,151
// SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '../interfaces/IElasticToken.sol'; import '../libraries/ElasticMath.sol'; import '../core/ElasticDAO.sol'; import '../models/DAO.sol'; import '../models/Ecosystem.sol'; import '../models/Token.sol'; import '../models/TokenHolder.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; /** * @dev ElasticGovernanceToken contract outlines and defines all the functionality * of an ElasticGovernanceToken and also serves as it's storage */ contract ElasticGovernanceToken is IElasticToken, ReentrancyGuard { address public burner; address public daoAddress; address public ecosystemModelAddress; address public minter; bool public initialized; mapping(address => mapping(address => uint256)) private _allowances; modifier onlyDAO() { require(msg.sender == daoAddress, 'ElasticDAO: Not authorized'); _; } modifier onlyDAOorBurner() { require(msg.sender == daoAddress || msg.sender == burner, 'ElasticDAO: Not authorized'); _; } modifier onlyDAOorMinter() { require(msg.sender == daoAddress || msg.sender == minter, 'ElasticDAO: Not authorized'); _; } /** * @notice initializes the ElasticGovernanceToken * * @param _burner - the address which can burn tokens * @param _minter - the address which can mint tokens * @param _ecosystem - Ecosystem Instance * @param _token - Token Instance * * @dev Requirements: * - The token should not already be initialized * - The address of the burner cannot be zero * - The address of the deployed ElasticDAO cannot be zero * - The address of the ecosystemModelAddress cannot be zero * - The address of the minter cannot be zero * * @return bool */ function initialize( address _burner, address _minter, Ecosystem.Instance memory _ecosystem, Token.Instance memory _token ) external nonReentrant returns (Token.Instance memory) { require(initialized == false, 'ElasticDAO: Already initialized'); require(_burner != address(0), 'ElasticDAO: Address Zero'); require(_ecosystem.daoAddress != address(0), 'ElasticDAO: Address Zero'); require(_ecosystem.ecosystemModelAddress != address(0), 'ElasticDAO: Address Zero'); require(_minter != address(0), 'ElasticDAO: Address Zero'); initialized = true; burner = _burner; daoAddress = _ecosystem.daoAddress; ecosystemModelAddress = _ecosystem.ecosystemModelAddress; minter = _minter; Token tokenStorage = Token(_ecosystem.tokenModelAddress); tokenStorage.serialize(_token); return _token; } /** * @notice Returns the remaining number of tokens that @param _spender will be * allowed to spend on behalf of @param _owner through {transferFrom}. This is * zero by default * * @param _spender - the address of the spender * @param _owner - the address of the owner * * @dev This value changes when {approve} or {transferFrom} are called * * @return uint256 */ function allowance(address _owner, address _spender) external view override returns (uint256) { return _allowances[_owner][_spender]; } /** * @notice Sets @param _amount as the allowance of @param _spender over the caller's tokens * * @param _spender - the address of the spender * * @dev * 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 * * @dev Emits an {Approval} event * * @return bool */ function approve(address _spender, uint256 _amount) external override nonReentrant returns (bool) { _approve(msg.sender, _spender, _amount); return true; } /** * @notice Returns the amount of tokens owned by @param _account using ElasticMath * * @param _account - address of the account * * @dev the number of tokens is given by: * t = lambda * m * k * * t - number of tokens * m - lambda modifier - it's value increases every time someone joins the DAO * k - constant token multiplier - it increases the number of tokens * that each member of the DAO has with respect to their lambda * * Further math and documentaion of 't' can be found at ../libraries/ElasticMath.sol * * @return uint256 */ function balanceOf(address _account) external view override returns (uint256) { Token.Instance memory token = _getToken(); TokenHolder.Instance memory tokenHolder = _getTokenHolder(_account); uint256 t = ElasticMath.t(tokenHolder.lambda, token.k, token.m); return t; } /** * @notice Returns the amount of shares ( lambda ) owned by _account. * * @param _account - address of the account * * @return lambda uint256 - lambda is the number of shares */ function balanceOfInShares(address _account) external view override returns (uint256) { TokenHolder.Instance memory tokenHolder = _getTokenHolder(_account); return tokenHolder.lambda; } /** * @notice Returns the amount of tokens @param _account can vote with, using ElasticMath * * @param _account - the address of the account * * @dev checks if @param _account has more or less lambda than maxVotingLambda, * based on which number of tokens (t) @param _account can vote with is calculated. * Further math and documentaion of 't' can be found at ../libraries/ElasticMath.sol * * @return balance uint256 numberOfTokens (t) */ function balanceOfVoting(address _account) external view returns (uint256 balance) { Token.Instance memory token = _getToken(); TokenHolder.Instance memory tokenHolder = _getTokenHolder(_account); uint256 maxVotingLambda = _getDAO().maxVotingLambda; if (tokenHolder.lambda > maxVotingLambda) { return ElasticMath.t(maxVotingLambda, token.k, token.m); } else { return ElasticMath.t(tokenHolder.lambda, token.k, token.m); } } /** * @notice Reduces the balance(tokens) of @param _account by _amount * * @param _account address of the account * * @param _amount - the amount by which the number of tokens is to be reduced * * @return bool */ function burn(address _account, uint256 _amount) external override onlyDAOorBurner nonReentrant returns (bool) { _burn(_account, _amount); return true; } /** * @notice Reduces the balance(lambda) of @param _account by _amount * * @param _account - address of the account * * @param _amount - the amount by which the number of shares has to be reduced * * @return bool */ function burnShares(address _account, uint256 _amount) external override onlyDAOorBurner nonReentrant returns (bool) { _burnShares(_account, _amount); return true; } /** * @notice returns the number of decimals * * @return 18 */ function decimals() external pure returns (uint256) { return 18; } /** * @notice decreases the allowance of @param _spender by _subtractedValue * * @param _spender - address of the spender * @param _subtractedValue - the value the allowance has to be decreased by * * @dev Requirement: * Allowance cannot be lower than 0 * * @return bool */ function decreaseAllowance(address _spender, uint256 _subtractedValue) external nonReentrant returns (bool) { uint256 newAllowance = SafeMath.sub(_allowances[msg.sender][_spender], _subtractedValue); _approve(msg.sender, _spender, newAllowance); return true; } /** * @notice increases the allowance of @param _spender by _addedValue * * @param _spender - address of the spender * @param _addedValue - the value the allowance has to be increased by * * @return bool */ function increaseAllowance(address _spender, uint256 _addedValue) external nonReentrant returns (bool) { _approve(msg.sender, _spender, SafeMath.add(_allowances[msg.sender][_spender], _addedValue)); return true; } /** * @dev mints @param _amount tokens for @param _account * @param _account - the address of the account for whom the token have to be minted to * @param _amount - the amount of tokens to be minted * @return bool */ function mint(address _account, uint256 _amount) external override onlyDAOorMinter nonReentrant returns (bool) { _mint(_account, _amount); return true; } /** * @dev mints @param _amount of shares for @param _account * @param _account address of the account * @param _amount - the amount of shares to be minted * @return bool */ function mintShares(address _account, uint256 _amount) external override onlyDAOorMinter nonReentrant returns (bool) { _mintShares(_account, _amount); return true; } /** * @dev Returns the name of the token. * @return string - name of the token */ function name() external view returns (string memory) { return _getToken().name; } /** * @notice Returns the number of token holders of ElasticGovernanceToken * * @return uint256 numberOfTokenHolders */ function numberOfTokenHolders() external view override returns (uint256) { return _getToken().numberOfTokenHolders; } /** * @notice sets the burner of the ElasticGovernanceToken * a Burner is an address that can burn tokens(reduce the amount of tokens in circulation) * * @param _burner - the address of the burner * * @dev Requirement: * - Address of the burner cannot be zero address * * @return bool */ function setBurner(address _burner) external onlyDAO nonReentrant returns (bool) { require(_burner != address(0), 'ElasticDAO: Address Zero'); burner = _burner; return true; } /** * @notice sets the minter of the ElasticGovernanceToken * a Minter is an address that can mint tokens(increase the amount of tokens in circulation) * * @param _minter - address of the minter * * @dev Requirement: * - Address of the minter cannot be zero address * * @return bool */ function setMinter(address _minter) external onlyDAO nonReentrant returns (bool) { require(_minter != address(0), 'ElasticDAO: Address Zero'); minter = _minter; return true; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. * * @return string - the symbol of the token */ function symbol() external view returns (string memory) { return _getToken().symbol; } /** * @notice returns the totalSupply of tokens in the DAO * * @dev * t - the total number of tokens in the DAO * lambda - the total number of shares outstanding in the DAO currently * m - current value of the share modifier * k - constant * t = ( lambda * m * k ) * Further math and documentaion of 't' can be found at ../libraries/ElasticMath.sol * * @return uint256 - the value of t */ function totalSupply() external view override returns (uint256) { Token.Instance memory token = _getToken(); return ElasticMath.t(token.lambda, token.k, token.m); } /** * @notice Returns the current lambda value * * @return uint256 lambda */ function totalSupplyInShares() external view override returns (uint256) { Token.Instance memory token = _getToken(); return token.lambda; } /** * @dev Moves @param _amount tokens from the caller's account to @param _to address * * Returns a boolean value indicating whether the operation succeeded * * Emits a {Transfer} event * @return bool */ function transfer(address _to, uint256 _amount) external override nonReentrant returns (bool) { _transfer(msg.sender, _to, _amount); return true; } /** * @dev Moves @param _amount tokens from @param _from to @param _to using the * allowance mechanism. @param _amount is then deducted from the caller's * allowance * * Returns a boolean value indicating whether the operation succeeded * * Emits a {Transfer} event * @return bool */ function transferFrom( address _from, address _to, uint256 _amount ) external override nonReentrant returns (bool) { require(msg.sender == _from || _amount <= _allowances[_from][msg.sender], 'ERC20: Bad Caller'); if (msg.sender != _from && _allowances[_from][msg.sender] != uint256(-1)) { _allowances[_from][msg.sender] = SafeMath.sub(_allowances[_from][msg.sender], _amount); emit Approval(_from, msg.sender, _allowances[_from][msg.sender]); } _transfer(_from, _to, _amount); return true; } // Private function _approve( address _owner, address _spender, uint256 _amount ) internal { 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); } function _burn(address _account, uint256 _deltaT) internal { Token.Instance memory token = _getToken(); uint256 deltaLambda = ElasticMath.lambdaFromT(_deltaT, token.k, token.m); _burnShares(_account, deltaLambda); } function _burnShares(address _account, uint256 _deltaLambda) internal { Ecosystem.Instance memory ecosystem = _getEcosystem(); Token tokenStorage = Token(ecosystem.tokenModelAddress); Token.Instance memory token = tokenStorage.deserialize(address(this), ecosystem); TokenHolder.Instance memory tokenHolder = _getTokenHolder(_account); bool alreadyTokenHolder = tokenHolder.lambda > 0; uint256 deltaT = ElasticMath.t(_deltaLambda, token.k, token.m); tokenHolder = _updateBalance(tokenHolder, false, _deltaLambda); token.lambda = SafeMath.sub(token.lambda, _deltaLambda); tokenStorage.serialize(token); TokenHolder tokenHolderStorage = TokenHolder(ecosystem.tokenHolderModelAddress); tokenHolderStorage.serialize(tokenHolder); _updateNumberOfTokenHolders(alreadyTokenHolder, token, tokenHolder, tokenStorage); emit Transfer(_account, address(0), deltaT); } function _mint(address _account, uint256 _deltaT) internal { Token.Instance memory token = _getToken(); uint256 deltaLambda = ElasticMath.lambdaFromT(_deltaT, token.k, token.m); _mintShares(_account, deltaLambda); } function _mintShares(address _account, uint256 _deltaLambda) internal { Ecosystem.Instance memory ecosystem = _getEcosystem(); Token tokenStorage = Token(ecosystem.tokenModelAddress); Token.Instance memory token = tokenStorage.deserialize(address(this), ecosystem); TokenHolder.Instance memory tokenHolder = _getTokenHolder(_account); bool alreadyTokenHolder = tokenHolder.lambda > 0; uint256 deltaT = ElasticMath.t(_deltaLambda, token.k, token.m); tokenHolder = _updateBalance(tokenHolder, true, _deltaLambda); token.lambda = SafeMath.add(token.lambda, _deltaLambda); tokenStorage.serialize(token); TokenHolder tokenHolderStorage = TokenHolder(ecosystem.tokenHolderModelAddress); tokenHolderStorage.serialize(tokenHolder); _updateNumberOfTokenHolders(alreadyTokenHolder, token, tokenHolder, tokenStorage); emit Transfer(address(0), _account, deltaT); } function _transfer( address _from, address _to, uint256 _deltaT ) internal { require(_from != _to, 'ElasticDAO: Can not transfer to self'); Ecosystem.Instance memory ecosystem = _getEcosystem(); Token tokenStorage = Token(ecosystem.tokenModelAddress); Token.Instance memory token = tokenStorage.deserialize(address(this), ecosystem); TokenHolder.Instance memory fromTokenHolder = _getTokenHolder(_from); TokenHolder.Instance memory toTokenHolder = _getTokenHolder(_to); bool fromAlreadyTokenHolder = fromTokenHolder.lambda > 0; bool toAlreadyTokenHolder = toTokenHolder.lambda > 0; uint256 deltaLambda = ElasticMath.lambdaFromT(_deltaT, token.k, token.m); uint256 deltaT = ElasticMath.t(deltaLambda, token.k, token.m); fromTokenHolder = _updateBalance(fromTokenHolder, false, deltaLambda); toTokenHolder = _updateBalance(toTokenHolder, true, deltaLambda); TokenHolder tokenHolderStorage = TokenHolder(ecosystem.tokenHolderModelAddress); tokenHolderStorage.serialize(fromTokenHolder); tokenHolderStorage.serialize(toTokenHolder); _updateNumberOfTokenHolders(fromAlreadyTokenHolder, token, fromTokenHolder, tokenStorage); _updateNumberOfTokenHolders(toAlreadyTokenHolder, token, toTokenHolder, tokenStorage); emit Transfer(_from, _to, deltaT); } function _updateBalance( TokenHolder.Instance memory _tokenHolder, bool _isIncreasing, uint256 _deltaLambda ) internal pure returns (TokenHolder.Instance memory) { if (_isIncreasing) { _tokenHolder.lambda = SafeMath.add(_tokenHolder.lambda, _deltaLambda); } else { _tokenHolder.lambda = SafeMath.sub(_tokenHolder.lambda, _deltaLambda); } return _tokenHolder; } function _updateNumberOfTokenHolders( bool alreadyTokenHolder, Token.Instance memory token, TokenHolder.Instance memory tokenHolder, Token tokenStorage ) internal { if (tokenHolder.lambda > 0 && alreadyTokenHolder == false) { tokenStorage.updateNumberOfTokenHolders(token, SafeMath.add(token.numberOfTokenHolders, 1)); } if (tokenHolder.lambda == 0 && alreadyTokenHolder) { tokenStorage.updateNumberOfTokenHolders(token, SafeMath.sub(token.numberOfTokenHolders, 1)); } } // Private Getters function _getDAO() internal view returns (DAO.Instance memory) { Ecosystem.Instance memory ecosystem = _getEcosystem(); return DAO(ecosystem.daoModelAddress).deserialize(daoAddress, ecosystem); } function _getEcosystem() internal view returns (Ecosystem.Instance memory) { return Ecosystem(ecosystemModelAddress).deserialize(daoAddress); } function _getTokenHolder(address _account) internal view returns (TokenHolder.Instance memory) { Ecosystem.Instance memory ecosystem = _getEcosystem(); return TokenHolder(ecosystem.tokenHolderModelAddress).deserialize( _account, ecosystem, Token(ecosystem.tokenModelAddress).deserialize(address(this), ecosystem) ); } function _getToken() internal view returns (Token.Instance memory) { Ecosystem.Instance memory ecosystem = _getEcosystem(); return Token(ecosystem.tokenModelAddress).deserialize(address(this), ecosystem); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IElasticToken is IERC20 { /** * @dev Returns the amount of shares owned by @param _account. * @param _account - address of the account * @return lambda uint256 - lambda is the number of shares */ function balanceOfInShares(address _account) external view returns (uint256 lambda); /** * @dev Reduces the balance(tokens) of @param _account by @param _amount * @param _account address of the account * @param _amount - the amount by which the number of tokens has to be reduced * @return bool */ function burn(address _account, uint256 _amount) external returns (bool); /** * @dev Reduces the balance(shares) of @param _account by @param _amount * @param _account - address of the account * @param _amount - the amount by which the number of shares has to be reduced * @return bool */ function burnShares(address _account, uint256 _amount) external returns (bool); /** * @dev mints @param _amount tokens for @param _account * @param _account - the address of the account for whom the token have to be minted to * @param _amount - the amount of tokens to be minted * @return bool */ function mint(address _account, uint256 _amount) external returns (bool); /** * @dev mints @param _amount of shares for @param _account * @param _account address of the account * @param _amount - the amount of shares to be minted * @return bool */ function mintShares(address _account, uint256 _amount) external returns (bool); /** * @dev returns total number of token holders * @return uint256 */ function numberOfTokenHolders() external view returns (uint256); /** * @dev Returns the total supply of shares in the DAO * @return lambda uint256 - lambda is the number of shares */ function totalSupplyInShares() external view returns (uint256 lambda); } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; import './SafeMath.sol'; /** * @dev Provides functions for performing ElasticDAO specific math. * * These functions correspond with functions provided by the JS SDK and should * always be used instead of doing calculations within other contracts to avoid * any inconsistencies in the math. * * Notes: * * - Dash values represent the state after a transaction has completed successfully. * - Non-dash values represent the current state, before the transaction has completed. * - Lambda is the math term for shares. We typically expose the value to users as * shares instead of lambda because it's easier to grok. */ library ElasticMath { /** * @dev calculates the value of capitalDelta; the amount of ETH backing each * governance token. * @param totalEthValue amount of ETH in the DAO contract * @param totalSupplyOfTokens number of tokens in existance * * capitalDelta = totalEthValue / totalSupplyOfTokens * @return uint256 */ function capitalDelta(uint256 totalEthValue, uint256 totalSupplyOfTokens) internal pure returns (uint256) { return wdiv(totalEthValue, totalSupplyOfTokens); } /** * @dev calculates the value of deltaE; the amount of ETH required to mint deltaLambda * @param deltaLambda = lambdaDash - lambda * @param capitalDeltaValue the ETH/token ratio; see capitalDelta(uint256, uint256) * @param k constant token multiplier - it increases the number of tokens * that each member of the DAO has with respect to their lambda * @param elasticity the percentage by which capitalDelta (cost of entering the DAO) * should increase on every join * @param lambda outstanding shares * @param m - lambda modifier - it's value increases every time someone joins the DAO * * lambdaDash = deltaLambda + lambda * mDash = ( lambdaDash / lambda ) * m * deltaE = capitalDelta * k * ( lambdaDash * mDash * ( 1 + elasticity ) - lambda * m ) * @return uint256 */ function deltaE( uint256 deltaLambda, uint256 capitalDeltaValue, uint256 k, uint256 elasticity, uint256 lambda, uint256 m ) internal pure returns (uint256) { uint256 lambdaDash = SafeMath.add(deltaLambda, lambda); return wmul( wmul(capitalDeltaValue, k), SafeMath.sub( wmul(lambdaDash, wmul(mDash(lambdaDash, lambda, m), revamp(elasticity))), wmul(lambda, m) ) ); } /** * @dev calculates the lambda value given t, k, & m * @param tokens t value; number of tokens for which lambda should be calculated * @param k constant token multiplier - it increases the number of tokens * that each member of the DAO has with respect to their lambda * @param m - lambda modifier - it's value increases every time someone joins the DAO * * lambda = t / ( m * k) * @return uint256 */ function lambdaFromT( uint256 tokens, uint256 k, uint256 m ) internal pure returns (uint256) { return wdiv(tokens, wmul(k, m)); } /** * @dev calculates the future share modifier given the future value of * lambda (lambdaDash), the current value of lambda, and the current share modifier * @param m current share modifier * @param lambda current outstanding shares * @param lambdaDash future outstanding shares * * mDash = ( lambdaDash / lambda ) * m * @return uint256 */ function mDash( uint256 lambdaDash, uint256 lambda, uint256 m ) internal pure returns (uint256) { return wmul(wdiv(lambdaDash, lambda), m); } /** * @dev calculates the value of revamp * @param elasticity the percentage by which capitalDelta should increase * * revamp = 1 + elasticity * @return uint256 */ function revamp(uint256 elasticity) internal pure returns (uint256) { return SafeMath.add(elasticity, 1000000000000000000); } /** * @dev calculates the number of tokens represented by lambda given k & m * @param lambda shares * @param k a constant, initially set by the DAO * @param m share modifier * * t = lambda * m * k * @return uint256 */ function t( uint256 lambda, uint256 k, uint256 m ) internal view returns (uint256) { if (lambda == 0) { return 0; } return wmul(wmul(lambda, k), m); } /** * @dev multiplies two float values, required since solidity does not handle * floating point values * * inspiration: https://github.com/dapphub/ds-math/blob/master/src/math.sol * * @return uint256 */ function wmul(uint256 a, uint256 b) internal pure returns (uint256) { return SafeMath.div( SafeMath.add(SafeMath.mul(a, b), SafeMath.div(1000000000000000000, 2)), 1000000000000000000 ); } /** * @dev divides two float values, required since solidity does not handle * floating point values. * * inspiration: https://github.com/dapphub/ds-math/blob/master/src/math.sol * * @return uint256 */ function wdiv(uint256 a, uint256 b) internal pure returns (uint256) { return SafeMath.div(SafeMath.add(SafeMath.mul(a, 1000000000000000000), SafeMath.div(b, 2)), b); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '../interfaces/IUniswapV2Pair.sol'; import '../libraries/ElasticMath.sol'; import '../models/DAO.sol'; import '../models/Ecosystem.sol'; import '../models/Token.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import '@pie-dao/proxy/contracts/PProxy.sol'; import 'hardhat/console.sol'; /** * @dev The ElasticDAO contract outlines and defines all the functionality * such as initialize, Join, exit, etc for an elasticDAO. * * It also serves as the vault for ElasticDAO. */ contract ElasticDAO is ReentrancyGuard { address public deployer; address public ecosystemModelAddress; address public controller; address[] public summoners; address[] public liquidityPools; bool public initialized; event ElasticGovernanceTokenDeployed(address indexed tokenAddress); event MaxVotingLambdaChanged(uint256 value); event ControllerChanged(address value); event ExitDAO(address indexed memberAddress, uint256 shareAmount, uint256 ethAmount); event FailedToFullyPenalize( address indexed memberAddress, uint256 attemptedAmount, uint256 actualAmount ); event JoinDAO(address indexed memberAddress, uint256 shareAmount, uint256 ethAmount); event LiquidityPoolAdded(address indexed poolAddress); event LiquidityPoolRemoved(address indexed poolAddress); event SeedDAO(address indexed summonerAddress, uint256 amount); event SummonedDAO(address indexed summonedBy); modifier onlyAfterSummoning() { DAO.Instance memory dao = _getDAO(); require(dao.summoned, 'ElasticDAO: DAO must be summoned'); _; } modifier onlyAfterTokenInitialized() { Ecosystem.Instance memory ecosystem = _getEcosystem(); bool tokenInitialized = Token(ecosystem.tokenModelAddress).exists( ecosystem.governanceTokenAddress, ecosystem.daoAddress ); require(tokenInitialized, 'ElasticDAO: Please call initializeToken first'); _; } modifier onlyBeforeSummoning() { DAO.Instance memory dao = _getDAO(); require(dao.summoned == false, 'ElasticDAO: DAO must not be summoned'); _; } modifier onlyController() { require(msg.sender == controller, 'ElasticDAO: Only controller'); _; } modifier onlyDeployer() { require(msg.sender == deployer, 'ElasticDAO: Only deployer'); _; } modifier onlySummoners() { Ecosystem.Instance memory ecosystem = _getEcosystem(); DAO daoContract = DAO(ecosystem.daoModelAddress); DAO.Instance memory dao = daoContract.deserialize(address(this), ecosystem); bool summonerCheck = daoContract.isSummoner(dao, msg.sender); require(summonerCheck, 'ElasticDAO: Only summoners'); _; } modifier onlyWhenOpen() { require(address(this).balance > 0, 'ElasticDAO: This DAO is closed'); _; } /** * @notice Initializes and builds the ElasticDAO struct * * @param _ecosystemModelAddress - the address of the ecosystem model * @param _controller the address which can control the core DAO functions * @param _summoners - an array containing the addresses of the summoners * @param _name - the name of the DAO * @param _maxVotingLambda - the maximum amount of lambda that can be used to vote in the DAO * * @dev * Requirements: * - The DAO cannot already be initialized * - The ecosystem model address cannot be the zero address * - The DAO must have atleast one summoner to summon the DAO */ function initialize( address _ecosystemModelAddress, address _controller, address[] memory _summoners, string memory _name, uint256 _maxVotingLambda ) external nonReentrant { require(initialized == false, 'ElasticDAO: Already initialized'); require( _ecosystemModelAddress != address(0) && _controller != address(0), 'ElasticDAO: Address Zero' ); require(_summoners.length > 0, 'ElasticDAO: At least 1 summoner required'); for (uint256 i = 0; i < _summoners.length; i += 1) { if (_summoners[i] == address(0)) { revert('ElasticDAO: Summoner address can not be zero address'); } } controller = _controller; deployer = msg.sender; summoners = _summoners; Ecosystem.Instance memory defaults = Ecosystem(_ecosystemModelAddress).deserialize(address(0)); Ecosystem.Instance memory ecosystem = _buildEcosystem(controller, defaults); ecosystemModelAddress = ecosystem.ecosystemModelAddress; bool success = _buildDAO(_summoners, _name, _maxVotingLambda, ecosystem); initialized = true; require(success, 'ElasticDAO: Build DAO Failed'); } function addLiquidityPool(address _poolAddress) external onlyController nonReentrant returns (bool) { liquidityPools.push(_poolAddress); emit LiquidityPoolAdded(_poolAddress); } /** * @notice initializes the token of the DAO * * @param _name - name of the token * @param _symbol - symbol of the token * @param _eByL -the amount of lambda a summoner gets(per ETH) during the seeding phase of the DAO * @param _elasticity the value by which the cost of entering the DAO increases ( on every join ) * @param _k - is the constant token multiplier * it increases the number of tokens that each member of the DAO has with respect to their lambda * @param _maxLambdaPurchase - is the maximum amount of lambda that can be purchased per wallet * * @dev emits ElasticGovernanceTokenDeployed event * @dev * Requirements: * - Only the deployer of the DAO can initialize the Token */ function initializeToken( string memory _name, string memory _symbol, uint256 _eByL, uint256 _elasticity, uint256 _k, uint256 _maxLambdaPurchase ) external onlyBeforeSummoning onlyDeployer nonReentrant { Ecosystem.Instance memory ecosystem = _getEcosystem(); Token.Instance memory token = _buildToken( controller, _name, _symbol, _eByL, _elasticity, _k, _maxLambdaPurchase, ecosystem ); emit ElasticGovernanceTokenDeployed(token.uuid); } /** * @notice this function is to be used for exiting the DAO * for the underlying ETH value of _deltaLambda * * The eth value of _deltaLambda is calculated using: * * eth to be transfered = ( deltaLambda/lambda ) * totalEthInTheDAO * * @param _deltaLambda - the amount of lambda the address exits with * * Requirement: * - ETH transfer must be successful * @dev emits ExitDAO event */ function exit(uint256 _deltaLambda) external onlyAfterSummoning nonReentrant { // burn the shares Token.Instance memory token = _getToken(); ElasticGovernanceToken tokenContract = ElasticGovernanceToken(token.uuid); // eth to be transfered = ( deltaLambda/lambda ) * totalEthInTheDAO uint256 ratioOfShares = ElasticMath.wdiv(_deltaLambda, token.lambda); uint256 ethToBeTransfered = ElasticMath.wmul(ratioOfShares, address(this).balance); // transfer the eth tokenContract.burnShares(msg.sender, _deltaLambda); (bool success, ) = msg.sender.call{ value: ethToBeTransfered }(''); require(success, 'ElasticDAO: Exit Failed'); emit ExitDAO(msg.sender, _deltaLambda, ethToBeTransfered); } /** * @notice this function returns the length of the liquidity pools array * */ function getLiquidityPoolCount() public view returns (uint256) { return liquidityPools.length; } /** * @notice this function is used to join the DAO after it has been summoned * Joining the DAO is syntactically equal to minting _deltaLambda for the function caller. * * Based on the current state of the DAO, capitalDelta, deltaE, mDash are calulated, * after which maxTokenLambda is minted for the address calling the function. * * @dev documentation and further math regarding capitalDelta, deltaE, * mDash can be found at ../libraries/ElasticMath.sol * @dev emits the JoinDAO event * * @dev Requirements: * (The value of maxLambdaPurchase is set during the initialzing of the DAO) * The correct value of ETH, calculated via deltaE, * must be sent in the transaction by the calling address * The token contract should be successfully be able to mint token.makxLambdaPurchase */ function join() external payable onlyAfterSummoning onlyWhenOpen nonReentrant { Token.Instance memory token = _getToken(); ElasticGovernanceToken tokenContract = ElasticGovernanceToken(token.uuid); uint256 capitalDelta = ElasticMath.capitalDelta( // the current totalBalance of the DAO is inclusive of msg.value, // capitalDelta is to be calculated without the msg.value SafeMath.sub(address(this).balance, msg.value), tokenContract.totalSupply() ); uint256 deltaE = ElasticMath.deltaE( token.maxLambdaPurchase, capitalDelta, token.k, token.elasticity, token.lambda, token.m ); require(msg.value >= deltaE, 'ElasticDAO: Incorrect ETH amount'); // mdash uint256 lambdaDash = SafeMath.add(token.maxLambdaPurchase, token.lambda); uint256 mDash = ElasticMath.mDash(lambdaDash, token.lambda, token.m); // serialize the token Ecosystem.Instance memory ecosystem = _getEcosystem(); Token tokenStorage = Token(ecosystem.tokenModelAddress); token.m = mDash; tokenStorage.serialize(token); // tokencontract mint shares bool success = tokenContract.mintShares(msg.sender, token.maxLambdaPurchase); require(success, 'ElasticDAO: Mint Shares Failed during Join'); for (uint256 i = 0; i < liquidityPools.length; i += 1) { IUniswapV2Pair(liquidityPools[i]).sync(); } // return extra ETH if (success && msg.value > deltaE) { (success, ) = msg.sender.call{ value: SafeMath.sub(msg.value, deltaE) }(''); require(success, 'ElasticDAO: TransactionFailed'); } emit JoinDAO(msg.sender, token.maxLambdaPurchase, msg.value); } /** * @notice penalizes @param _addresses with @param _amounts respectively * * @param _addresses - an array of addresses * @param _amounts - an array containing the amounts each address has to be penalized respectively * * @dev Requirement: * - Each address must have a corresponding amount to be penalized with */ function penalize(address[] memory _addresses, uint256[] memory _amounts) external onlyController nonReentrant { require( _addresses.length == _amounts.length, 'ElasticDAO: An amount is required for each address' ); ElasticGovernanceToken tokenContract = ElasticGovernanceToken(_getToken().uuid); for (uint256 i = 0; i < _addresses.length; i += 1) { uint256 lambda = tokenContract.balanceOfInShares(_addresses[i]); if (lambda < _amounts[i]) { if (lambda != 0) { tokenContract.burnShares(_addresses[i], lambda); } FailedToFullyPenalize(_addresses[i], _amounts[i], lambda); } else { tokenContract.burnShares(_addresses[i], _amounts[i]); } } } function removeLiquidityPool(address _poolAddress) external onlyController nonReentrant returns (bool) { for (uint256 i = 0; i < liquidityPools.length; i += 1) { if (liquidityPools[i] == _poolAddress) { liquidityPools[i] = liquidityPools[liquidityPools.length - 1]; liquidityPools.pop(); } } emit LiquidityPoolRemoved(_poolAddress); } /** * @notice rewards @param _addresess with @param _amounts respectively * * @param _addresses - an array of addresses * @param _amounts - an array containing the amounts each address has to be rewarded respectively * * @dev Requirement: * - Each address must have a corresponding amount to be rewarded with */ function reward(address[] memory _addresses, uint256[] memory _amounts) external onlyController nonReentrant { require( _addresses.length == _amounts.length, 'ElasticDAO: An amount is required for each address' ); ElasticGovernanceToken tokenContract = ElasticGovernanceToken(_getToken().uuid); for (uint256 i = 0; i < _addresses.length; i += 1) { tokenContract.mintShares(_addresses[i], _amounts[i]); } } /** * @notice sets the controller of the DAO, * The controller of the DAO handles various responsibilities of the DAO, * such as burning and minting tokens on behalf of the DAO * * @param _controller - the new address of the controller of the DAO * * @dev emits ControllerChanged event * @dev Requirements: * - The controller must not be the 0 address * - The controller of the DAO should successfully be set as the burner of the tokens of the DAO * - The controller of the DAO should successfully be set as the minter of the tokens of the DAO */ function setController(address _controller) external onlyController nonReentrant { require(_controller != address(0), 'ElasticDAO: Address Zero'); controller = _controller; // Update minter / burner ElasticGovernanceToken tokenContract = ElasticGovernanceToken(_getToken().uuid); bool success = tokenContract.setBurner(controller); require(success, 'ElasticDAO: Set Burner failed during setController'); success = tokenContract.setMinter(controller); require(success, 'ElasticDAO: Set Minter failed during setController'); emit ControllerChanged(controller); } /** * @notice sets the max voting lambda value for the DAO * @param _maxVotingLambda - the value of the maximum amount of lambda that can be used for voting * @dev emits MaxVotingLambdaChanged event */ function setMaxVotingLambda(uint256 _maxVotingLambda) external onlyController nonReentrant { Ecosystem.Instance memory ecosystem = _getEcosystem(); DAO daoStorage = DAO(ecosystem.daoModelAddress); DAO.Instance memory dao = daoStorage.deserialize(address(this), ecosystem); dao.maxVotingLambda = _maxVotingLambda; daoStorage.serialize(dao); emit MaxVotingLambdaChanged(_maxVotingLambda); } /** * @notice seeds the DAO, * Essentially transferring of ETH by a summoner address, in return for lambda is seeding the DAO, * The lambda receieved is given by: * Lambda = Eth / eByL * * @dev seeding of the DAO occurs after the DAO has been initialized, * and before the DAO has been summoned * @dev emits the SeedDAO event */ function seedSummoning() external payable onlyBeforeSummoning onlySummoners onlyAfterTokenInitialized nonReentrant { Token.Instance memory token = _getToken(); uint256 deltaE = msg.value; uint256 deltaLambda = ElasticMath.wdiv(deltaE, token.eByL); ElasticGovernanceToken(token.uuid).mintShares(msg.sender, deltaLambda); emit SeedDAO(msg.sender, deltaLambda); } /** * @notice summons the DAO, * Summoning the DAO results in all summoners getting _deltaLambda * after which people can enter the DAO using the join function * * @param _deltaLambda - the amount of lambda each summoner address receives * * @dev emits SummonedDAO event * @dev Requirement: * The DAO must be seeded with ETH during the seeding phase * (This is to facilitate capitalDelta calculations after the DAO has been summoned). * * @dev documentation and further math regarding capitalDelta * can be found at ../libraries/ElasticMath.sol */ function summon(uint256 _deltaLambda) external onlyBeforeSummoning onlySummoners nonReentrant { require(address(this).balance > 0, 'ElasticDAO: Please seed DAO with ETH to set ETH:EGT ratio'); Ecosystem.Instance memory ecosystem = _getEcosystem(); DAO daoContract = DAO(ecosystem.daoModelAddress); DAO.Instance memory dao = daoContract.deserialize(address(this), ecosystem); Token.Instance memory token = Token(ecosystem.tokenModelAddress).deserialize(ecosystem.governanceTokenAddress, ecosystem); ElasticGovernanceToken tokenContract = ElasticGovernanceToken(token.uuid); // number of summoners can not grow unboundly. it is fixed limit. for (uint256 i = 0; i < dao.numberOfSummoners; i += 1) { tokenContract.mintShares(daoContract.getSummoner(dao, i), _deltaLambda); } dao.summoned = true; daoContract.serialize(dao); emit SummonedDAO(msg.sender); } // Getters function getDAO() external view returns (DAO.Instance memory) { return _getDAO(); } function getEcosystem() external view returns (Ecosystem.Instance memory) { return _getEcosystem(); } /** * @dev creates DAO.Instance record * @param _summoners addresses of the summoners * @param _name name of the DAO * @param _ecosystem instance of Ecosystem the DAO uses * @param _maxVotingLambda - the maximum amount of lambda that can be used to vote in the DAO * @return bool true */ function _buildDAO( address[] memory _summoners, string memory _name, uint256 _maxVotingLambda, Ecosystem.Instance memory _ecosystem ) internal returns (bool) { DAO daoStorage = DAO(_ecosystem.daoModelAddress); DAO.Instance memory dao; dao.uuid = address(this); dao.ecosystem = _ecosystem; dao.maxVotingLambda = _maxVotingLambda; dao.name = _name; dao.summoned = false; dao.summoners = _summoners; daoStorage.serialize(dao); return true; } /** * @dev Deploys proxies leveraging the implementation contracts found on the * default Ecosystem.Instance record. * @param _controller the address which can control the core DAO functions * @param _defaults instance of Ecosystem with the implementation addresses * @return ecosystem Ecosystem.Instance */ function _buildEcosystem(address _controller, Ecosystem.Instance memory _defaults) internal returns (Ecosystem.Instance memory ecosystem) { ecosystem.daoAddress = address(this); ecosystem.daoModelAddress = _deployProxy(_defaults.daoModelAddress, _controller); ecosystem.ecosystemModelAddress = _deployProxy(_defaults.ecosystemModelAddress, _controller); ecosystem.governanceTokenAddress = _deployProxy(_defaults.governanceTokenAddress, _controller); ecosystem.tokenHolderModelAddress = _deployProxy( _defaults.tokenHolderModelAddress, _controller ); ecosystem.tokenModelAddress = _deployProxy(_defaults.tokenModelAddress, _controller); Ecosystem(ecosystem.ecosystemModelAddress).serialize(ecosystem); return ecosystem; } /** * @dev creates a Token.Instance record and initializes the ElasticGovernanceToken. * @param _controller the address which can control the core DAO functions * @param _name name of the token * @param _symbol symbol of the token * @param _eByL initial ETH/token ratio * @param _elasticity the percentage by which capitalDelta should increase * @param _k a constant, initially set by the DAO * @param _maxLambdaPurchase maximum amount of lambda (shares) that can be * minted on each call to the join function in ElasticDAO.sol * @param _ecosystem the DAO's ecosystem instance * @return token Token.Instance */ function _buildToken( address _controller, string memory _name, string memory _symbol, uint256 _eByL, uint256 _elasticity, uint256 _k, uint256 _maxLambdaPurchase, Ecosystem.Instance memory _ecosystem ) internal returns (Token.Instance memory token) { token.eByL = _eByL; token.ecosystem = _ecosystem; token.elasticity = _elasticity; token.k = _k; token.lambda = 0; token.m = 1000000000000000000; token.maxLambdaPurchase = _maxLambdaPurchase; token.name = _name; token.symbol = _symbol; token.uuid = _ecosystem.governanceTokenAddress; // initialize the token within the ecosystem return ElasticGovernanceToken(token.uuid).initialize(_controller, _controller, _ecosystem, token); } function _deployProxy(address _implementationAddress, address _owner) internal returns (address) { PProxy proxy = new PProxy(); proxy.setImplementation(_implementationAddress); proxy.setProxyOwner(_owner); return address(proxy); } // Private function _getDAO() internal view returns (DAO.Instance memory) { Ecosystem.Instance memory ecosystem = _getEcosystem(); return DAO(ecosystem.daoModelAddress).deserialize(address(this), ecosystem); } function _getEcosystem() internal view returns (Ecosystem.Instance memory) { return Ecosystem(ecosystemModelAddress).deserialize(address(this)); } function _getToken() internal view returns (Token.Instance memory) { Ecosystem.Instance memory ecosystem = _getEcosystem(); return Token(ecosystem.tokenModelAddress).deserialize(ecosystem.governanceTokenAddress, ecosystem); } receive() external payable {} fallback() external payable {} } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import './Ecosystem.sol'; import './EternalModel.sol'; /** * @author ElasticDAO - https://ElasticDAO.org * @notice This contract is used for storing core DAO data * @dev ElasticDAO network contracts can read/write from this contract */ contract DAO is EternalModel, ReentrancyGuard { struct Instance { address uuid; address[] summoners; bool summoned; string name; uint256 maxVotingLambda; uint256 numberOfSummoners; Ecosystem.Instance ecosystem; } event Serialized(address indexed uuid); /** * @dev deserializes Instance struct * @param _uuid - address of the unique user ID * @return record Instance */ function deserialize(address _uuid, Ecosystem.Instance memory _ecosystem) external view returns (Instance memory record) { record.uuid = _uuid; record.ecosystem = _ecosystem; if (_exists(_uuid)) { record.maxVotingLambda = getUint(keccak256(abi.encode(_uuid, 'maxVotingLambda'))); record.name = getString(keccak256(abi.encode(_uuid, 'name'))); record.numberOfSummoners = getUint(keccak256(abi.encode(_uuid, 'numberOfSummoners'))); record.summoned = getBool(keccak256(abi.encode(_uuid, 'summoned'))); } return record; } /** * @dev checks if @param _uuid exists * @param _uuid - address of the unique user ID * @return recordExists bool */ function exists(address _uuid) external view returns (bool) { return _exists(_uuid); } function getSummoner(Instance memory _dao, uint256 _index) external view returns (address) { return getAddress(keccak256(abi.encode(_dao.uuid, 'summoners', _index))); } /** * @dev checks if @param _uuid where _uuid is msg.sender - is a Summoner * @param _dao DAO.Instance * @param _summonerAddress address * @return bool */ function isSummoner(Instance memory _dao, address _summonerAddress) external view returns (bool) { return getBool(keccak256(abi.encode(_dao.uuid, 'summoner', _summonerAddress))); } /** * @dev serializes Instance struct * @param _record Instance */ function serialize(Instance memory _record) external nonReentrant { require(msg.sender == _record.uuid, 'ElasticDAO: Unauthorized'); setUint(keccak256(abi.encode(_record.uuid, 'maxVotingLambda')), _record.maxVotingLambda); setString(keccak256(abi.encode(_record.uuid, 'name')), _record.name); setBool(keccak256(abi.encode(_record.uuid, 'summoned')), _record.summoned); if (_record.summoners.length > 0) { _record.numberOfSummoners = _record.summoners.length; setUint(keccak256(abi.encode(_record.uuid, 'numberOfSummoners')), _record.numberOfSummoners); for (uint256 i = 0; i < _record.numberOfSummoners; i += 1) { setBool(keccak256(abi.encode(_record.uuid, 'summoner', _record.summoners[i])), true); setAddress(keccak256(abi.encode(_record.uuid, 'summoners', i)), _record.summoners[i]); } } setBool(keccak256(abi.encode(_record.uuid, 'exists')), true); emit Serialized(_record.uuid); } function _exists(address _uuid) internal view returns (bool) { return getBool(keccak256(abi.encode(_uuid, 'exists'))); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import './EternalModel.sol'; /** * @title ElasticDAO ecosystem * @author ElasticDAO - https://ElasticDAO.org * @notice This contract is used for storing core dao data * @dev ElasticDAO network contracts can read/write from this contract * @dev Serialize - Translation of data from the concerned struct to key-value pairs * @dev Deserialize - Translation of data from the key-value pairs to a struct */ contract Ecosystem is EternalModel, ReentrancyGuard { struct Instance { address daoAddress; // Models address daoModelAddress; address ecosystemModelAddress; address tokenHolderModelAddress; address tokenModelAddress; // Tokens address governanceTokenAddress; } event Serialized(address indexed _daoAddress); /** * @dev deserializes Instance struct * @param _daoAddress - address of the unique user ID * @return record Instance */ function deserialize(address _daoAddress) external view returns (Instance memory record) { if (_exists(_daoAddress)) { record.daoAddress = _daoAddress; record.daoModelAddress = getAddress( keccak256(abi.encode(record.daoAddress, 'daoModelAddress')) ); record.ecosystemModelAddress = address(this); record.governanceTokenAddress = getAddress( keccak256(abi.encode(record.daoAddress, 'governanceTokenAddress')) ); record.tokenHolderModelAddress = getAddress( keccak256(abi.encode(record.daoAddress, 'tokenHolderModelAddress')) ); record.tokenModelAddress = getAddress( keccak256(abi.encode(record.daoAddress, 'tokenModelAddress')) ); } return record; } /** * @dev checks if @param _daoAddress * @param _daoAddress - address of the unique user ID * @return recordExists bool */ function exists(address _daoAddress) external view returns (bool recordExists) { return _exists(_daoAddress); } /** * @dev serializes Instance struct * @param _record Instance */ function serialize(Instance memory _record) external nonReentrant { bool recordExists = _exists(_record.daoAddress); require( msg.sender == _record.daoAddress || (_record.daoAddress == address(0) && !recordExists), 'ElasticDAO: Unauthorized' ); setAddress( keccak256(abi.encode(_record.daoAddress, 'daoModelAddress')), _record.daoModelAddress ); setAddress( keccak256(abi.encode(_record.daoAddress, 'governanceTokenAddress')), _record.governanceTokenAddress ); setAddress( keccak256(abi.encode(_record.daoAddress, 'tokenHolderModelAddress')), _record.tokenHolderModelAddress ); setAddress( keccak256(abi.encode(_record.daoAddress, 'tokenModelAddress')), _record.tokenModelAddress ); setBool(keccak256(abi.encode(_record.daoAddress, 'exists')), true); emit Serialized(_record.daoAddress); } function _exists(address _daoAddress) internal view returns (bool recordExists) { return getBool(keccak256(abi.encode(_daoAddress, 'exists'))); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import './Ecosystem.sol'; import './EternalModel.sol'; import '../tokens/ElasticGovernanceToken.sol'; /** * @title A data storage for EGT (Elastic Governance Token) * @notice More info about EGT could be found in ./tokens/ElasticGovernanceToken.sol * @notice This contract is used for storing token data * @dev ElasticDAO network contracts can read/write from this contract * Serialize - Translation of data from the concerned struct to key-value pairs * Deserialize - Translation of data from the key-value pairs to a struct */ contract Token is EternalModel, ReentrancyGuard { struct Instance { address uuid; string name; string symbol; uint256 eByL; uint256 elasticity; uint256 k; uint256 lambda; uint256 m; uint256 maxLambdaPurchase; uint256 numberOfTokenHolders; Ecosystem.Instance ecosystem; } event Serialized(address indexed uuid); /** * @dev deserializes Instance struct * @param _uuid - address of the unique user ID * @return record Instance */ function deserialize(address _uuid, Ecosystem.Instance memory _ecosystem) external view returns (Instance memory record) { record.uuid = _uuid; record.ecosystem = _ecosystem; if (_exists(_uuid, _ecosystem.daoAddress)) { record.eByL = getUint(keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'eByL'))); record.elasticity = getUint( keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'elasticity')) ); record.k = getUint(keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'k'))); record.lambda = getUint(keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'lambda'))); record.m = getUint(keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'm'))); record.maxLambdaPurchase = getUint( keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'maxLambdaPurchase')) ); record.name = getString(keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'name'))); record.numberOfTokenHolders = getUint( keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'numberOfTokenHolders')) ); record.symbol = getString( keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'symbol')) ); } return record; } function exists(address _uuid, address _daoAddress) external view returns (bool) { return _exists(_uuid, _daoAddress); } /** * @dev serializes Instance struct * @param _record Instance */ function serialize(Instance memory _record) external nonReentrant { require( msg.sender == _record.uuid || (msg.sender == _record.ecosystem.daoAddress && _exists(_record.uuid, _record.ecosystem.daoAddress)), 'ElasticDAO: Unauthorized' ); setString( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'name')), _record.name ); setString( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'symbol')), _record.symbol ); setUint( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'eByL')), _record.eByL ); setUint( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'elasticity')), _record.elasticity ); setUint(keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'k')), _record.k); setUint( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'lambda')), _record.lambda ); setUint(keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'm')), _record.m); setUint( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'maxLambdaPurchase')), _record.maxLambdaPurchase ); setBool(keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'exists')), true); emit Serialized(_record.uuid); } function updateNumberOfTokenHolders(Instance memory _record, uint256 numberOfTokenHolders) external nonReentrant { require( msg.sender == _record.uuid && _exists(_record.uuid, _record.ecosystem.daoAddress), 'ElasticDAO: Unauthorized' ); setUint( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'numberOfTokenHolders')), numberOfTokenHolders ); } function _exists(address _uuid, address _daoAddress) internal view returns (bool) { return getBool(keccak256(abi.encode(_uuid, _daoAddress, 'exists'))); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import './Ecosystem.sol'; import './EternalModel.sol'; import './Token.sol'; /** * @title a data storage for Token holders * @author ElasticDAO - https://ElasticDAO.org * @notice This contract is used for storing token data * @dev ElasticDAO network contracts can read/write from this contract * Serialize - Translation of data from the concerned struct to key-value pairs * Deserialize - Translation of data from the key-value pairs to a struct */ contract TokenHolder is EternalModel, ReentrancyGuard { struct Instance { address account; uint256 lambda; Ecosystem.Instance ecosystem; Token.Instance token; } event Serialized(address indexed account, address indexed token); function deserialize( address _account, Ecosystem.Instance memory _ecosystem, Token.Instance memory _token ) external view returns (Instance memory record) { record.account = _account; record.ecosystem = _ecosystem; record.token = _token; if (_exists(_account, _token)) { record.lambda = getUint(keccak256(abi.encode(record.token.uuid, record.account, 'lambda'))); } return record; } function exists(address _account, Token.Instance memory _token) external view returns (bool) { return _exists(_account, _token); } /** * @dev serializes Instance struct * @param _record Instance */ function serialize(Instance memory _record) external nonReentrant { require(msg.sender == _record.token.uuid, 'ElasticDAO: Unauthorized'); setUint(keccak256(abi.encode(_record.token.uuid, _record.account, 'lambda')), _record.lambda); setBool(keccak256(abi.encode(_record.token.uuid, _record.account, 'exists')), true); emit Serialized(_record.account, _record.token.uuid); } function _exists(address _account, Token.Instance memory _token) internal view returns (bool) { return getBool(keccak256(abi.encode(_token.uuid, _account, 'exists'))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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]. */ 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 () 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.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.7.2; /** * @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) { require(b <= a, 'SafeMath: subtraction overflow'); 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 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) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; require(c > 0, 'SafeMath: division by zero'); return c; } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; interface IUniswapV2Pair { function sync() external; } pragma solidity ^0.7.1; import "./PProxyStorage.sol"; contract PProxy is PProxyStorage { bytes32 constant IMPLEMENTATION_SLOT = keccak256(abi.encodePacked("IMPLEMENTATION_SLOT")); bytes32 constant OWNER_SLOT = keccak256(abi.encodePacked("OWNER_SLOT")); modifier onlyProxyOwner() { require(msg.sender == readAddress(OWNER_SLOT), "PProxy.onlyProxyOwner: msg sender not owner"); _; } constructor () public { setAddress(OWNER_SLOT, msg.sender); } function getProxyOwner() public view returns (address) { return readAddress(OWNER_SLOT); } function setProxyOwner(address _newOwner) onlyProxyOwner public { setAddress(OWNER_SLOT, _newOwner); } function getImplementation() public view returns (address) { return readAddress(IMPLEMENTATION_SLOT); } function setImplementation(address _newImplementation) onlyProxyOwner public { setAddress(IMPLEMENTATION_SLOT, _newImplementation); } fallback () external payable { return internalFallback(); } function internalFallback() internal virtual { address contractAddr = readAddress(IMPLEMENTATION_SLOT); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), contractAddr, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; /** * @title Implementation of Eternal Storage for ElasticDAO - * - (https://fravoll.github.io/solidity-patterns/eternal_storage.html) * @author ElasticDAO - https://ElasticDAO.org * @notice This contract is used for storing contract network data * @dev ElasticDAO network contracts can read/write from this contract */ contract EternalModel { struct Storage { mapping(bytes32 => address) addressStorage; mapping(bytes32 => bool) boolStorage; mapping(bytes32 => bytes) bytesStorage; mapping(bytes32 => int256) intStorage; mapping(bytes32 => string) stringStorage; mapping(bytes32 => uint256) uIntStorage; } Storage internal s; /** * @notice Getter Functions */ /** * @notice Gets stored contract data in unit256 format * @param _key bytes32 location should be keccak256 and abi.encodePacked * @return uint256 _value from storage _key location */ function getUint(bytes32 _key) internal view returns (uint256) { return s.uIntStorage[_key]; } /** * @notice Get stored contract data in string format * @param _key bytes32 location should be keccak256 and abi.encodePacked * @return string _value from storage _key location */ function getString(bytes32 _key) internal view returns (string memory) { return s.stringStorage[_key]; } /** * @notice Get stored contract data in address format * @param _key bytes32 location should be keccak256 and abi.encodePacked * @return address _value from storage _key location */ function getAddress(bytes32 _key) internal view returns (address) { return s.addressStorage[_key]; } /** * @notice Get stored contract data in bool format * @param _key bytes32 location should be keccak256 and abi.encodePacked * @return bool _value from storage _key location */ function getBool(bytes32 _key) internal view returns (bool) { return s.boolStorage[_key]; } /** * @notice Setters Functions */ /** * @notice Store contract data in uint256 format * @dev restricted to latest ElasticDAO Networks contracts * @param _key bytes32 location should be keccak256 and abi.encodePacked * @param _value uint256 value */ function setUint(bytes32 _key, uint256 _value) internal { s.uIntStorage[_key] = _value; } /** * @notice Store contract data in string format * @dev restricted to latest ElasticDAO Networks contracts * @param _key bytes32 location should be keccak256 and abi.encodePacked * @param _value string value */ function setString(bytes32 _key, string memory _value) internal { s.stringStorage[_key] = _value; } /** * @notice Store contract data in address format * @dev restricted to latest ElasticDAO Networks contracts * @param _key bytes32 location should be keccak256 and abi.encodePacked * @param _value address value */ function setAddress(bytes32 _key, address _value) internal { s.addressStorage[_key] = _value; } /** * @notice Store contract data in bool format * @dev restricted to latest ElasticDAO Networks contracts * @param _key bytes32 location should be keccak256 and abi.encodePacked * @param _value bool value */ function setBool(bytes32 _key, bool _value) internal { s.boolStorage[_key] = _value; } } pragma solidity ^0.7.1; contract PProxyStorage { function readBool(bytes32 _key) public view returns(bool) { return storageRead(_key) == bytes32(uint256(1)); } function setBool(bytes32 _key, bool _value) internal { if(_value) { storageSet(_key, bytes32(uint256(1))); } else { storageSet(_key, bytes32(uint256(0))); } } function readAddress(bytes32 _key) public view returns(address) { return bytes32ToAddress(storageRead(_key)); } function setAddress(bytes32 _key, address _value) internal { storageSet(_key, addressToBytes32(_value)); } function storageRead(bytes32 _key) public view returns(bytes32) { bytes32 value; //solium-disable-next-line security/no-inline-assembly assembly { value := sload(_key) } return value; } function storageSet(bytes32 _key, bytes32 _value) internal { // targetAddress = _address; // No! bytes32 implAddressStorageKey = _key; //solium-disable-next-line security/no-inline-assembly assembly { sstore(implAddressStorageKey, _value) } } function bytes32ToAddress(bytes32 _value) public pure returns(address) { return address(uint160(uint256(_value))); } function addressToBytes32(address _value) public pure returns(bytes32) { return bytes32(uint256(_value)); } }
Reduces the balance(lambda) of _account by _amount _account - address of the account _amount - the amount by which the number of shares has to be reduced return bool/
function burnShares(address _account, uint256 _amount) external override onlyDAOorBurner nonReentrant returns (bool) { _burnShares(_account, _amount); return true; }
10,474,381
./full_match/1/0xC6713e9Bdc0B2f9fb50998F09e0Db16D7528E059/sources/contracts/interfaces/IManager.sol
Remove a manager internally _manager The address of the manager to remove
function _removeManager(address _manager) internal { require(managers.contains(_manager), "Not exist"); managers.remove(_manager); emit ManagerRemoved(_manager); }
2,942,224
pragma solidity ^0.5.0; import "./library/PLCRVoting.sol"; import "./ReputationRegistry.sol"; import "./HyphaToken.sol"; import "./ProjectLibrary.sol"; import "./Task.sol"; import "bytes/BytesLib.sol"; import "./library/SafeMath.sol"; import "./library/Ownable.sol"; /** @title Project Registry for Distribute Network @author Team: Jessica Marshall, Ashoka Finley @notice This project uses the Project Library to manage the state of Distribute Network projects. @dev This contract must be initialized with the address of a valid Token Registry, Reputation Registry and Distribute Token */ contract ProjectRegistry is Ownable { using ProjectLibrary for address; using BytesLib for bytes; using SafeMath for uint256; // ===================================================================== // EVENTS // ===================================================================== event LogProjectCreated(address indexed projectAddress, uint256 proposerCost); event LogProjectFullyStaked(address projectAddress, bool staked); event LogTaskHashSubmitted(address projectAddress, bytes32 taskHash, address submitter, uint weighting); event LogProjectActive(address projectAddress, bytes32 topTaskHash, bool active); event LogFinalTaskCreated(address taskAddress, address projectAddress, bytes32 finalTaskHash, uint256 index); event LogTaskClaimed(address projectAddress, uint256 index, uint256 reputationVal, address claimer); event LogSubmitTaskComplete(address projectAddress, uint256 index, uint256 validationFee); event LogProjectValidate(address projectAddress, bool validate); event LogProjectVoting(address projectAddress, bool vote); event LogProjectEnd(address projectAddress, uint end); event LogRefundProposer(address projectAddress, uint256 contractCaller, address proposer, uint256 proposedCost, uint256 proposedStake); /* event ProxyDeployed(address proxyAddress, address targetAddress); */ // ===================================================================== // STATE VARIABLES // ===================================================================== PLCRVoting plcrVoting; address payable tokenRegistryAddress; address reputationRegistryAddress; address payable hyphaTokenAddress; address projectContractAddress; address taskContractAddress; uint256 projectNonce = 0; mapping (uint => address) public projectsList; mapping (address => bool) public projects; struct StakedState { bytes32 topTaskHash; mapping(address => bytes32) taskHashSubmissions; mapping(bytes32 => uint256) numSubmissionsByWeight; mapping(bytes32 => address) originator; } mapping (address => StakedState) public stakedProjects; uint[5] public validationRewardWeightings = [36, 26, 20, 16, 2]; // done this way so that 100% of the validation reward can be pulled, regardless of how many validators there are bool freeze; // ===================================================================== // MODIFIERS // ===================================================================== modifier onlyTR() { require(msg.sender == tokenRegistryAddress); _; } modifier onlyRR() { require(msg.sender == reputationRegistryAddress); _; } modifier onlyTRorRR() { require(msg.sender == tokenRegistryAddress || msg.sender == reputationRegistryAddress); _; } // ===================================================================== // CONSTRUCTOR // ===================================================================== /** @notice @dev Quasi constructor is called after thr project is deployed. Requires that all relevant contract address are not yet intialized. @param _hyphaToken Address of the hyphaToken contract @param _tokenRegistry Address of the token registry contract @param _reputationRegistry Address of the reputation registry contract @param _plcrVoting Address of the plcr voting contract */ function init( address payable _hyphaToken, address payable _tokenRegistry, address _reputationRegistry, address _plcrVoting, address _projectAddress, address _taskAddress ) public { //contract is created /* address _proxyFactory */ require( tokenRegistryAddress == address(0) && reputationRegistryAddress == address(0) && hyphaTokenAddress == address(0) ); hyphaTokenAddress = _hyphaToken; tokenRegistryAddress = _tokenRegistry; reputationRegistryAddress = _reputationRegistry; plcrVoting = PLCRVoting(_plcrVoting); projectContractAddress = _projectAddress; taskContractAddress = _taskAddress; /* proxyFactory = ProxyFactory(_proxyFactory); */ } // ===================================================================== // OWNABLE // ===================================================================== /** * @dev Freezes the distribute token contract and allows existing token holders to withdraw tokens */ function freezeContract() external onlyOwner { freeze = true; } /** * @dev Unfreezes the distribute token contract and allows existing token holders to withdraw tokens */ function unfreezeContract() external onlyOwner { freeze = false; } /** * @dev Instantiate a new instance of plcrVoting contract * @param _newPlcrVoting Address of the new plcr contract */ function updatePLCRVoting(address _newPlcrVoting) external onlyOwner { plcrVoting = PLCRVoting(_newPlcrVoting); } /** * @dev Update the address of the hyphaToken * @param _newHyphaToken Address of the new distribute token */ function updateHyphaToken(address payable _newHyphaToken) external onlyOwner { hyphaTokenAddress = _newHyphaToken; } /** * @dev Update the address of the base product proxy contract * @param _newProjectContract Address of the new project contract */ function updateProjectContract(address _newProjectContract) external onlyOwner { projectContractAddress = _newProjectContract; } /** * @dev Update the address of the base task proxy contract * @param _newTaskContract Address of the new task contract */ function updateTaskContract(address _newTaskContract) external onlyOwner { taskContractAddress = _newTaskContract; } /** * @dev Update the address of the token registry * @param _newTokenRegistry Address of the new token registry */ function updateTokenRegistry(address payable _newTokenRegistry) external onlyOwner { tokenRegistryAddress = _newTokenRegistry; } /** * @dev Update the address of the reputation registry * @param _newReputationRegistry Address of the new reputation registry */ function updateReputationRegistry(address _newReputationRegistry) external onlyOwner { reputationRegistryAddress = _newReputationRegistry; } // ===================================================================== // PROXY DEPLOYER // ===================================================================== function createProxy(address _target, bytes memory _data) internal returns (address proxyContract) { proxyContract = createProxyImpl(_target, _data); /* emit ProxyDeployed(proxyContract, _target); */ } function createProxyImpl(address _target, bytes memory _data) internal returns (address proxyContract) { assembly { let contractCode := mload(0x40) // Find empty storage location using "free memory pointer" mstore(add(contractCode, 0x14), _target) // Add target address, with a 20 bytes [i.e. 32 - (32 - 20)] offset to later accomodate first part of the bytecode mstore(contractCode, 0x000000000000000000603160008181600b9039f3600080808080368092803773) // First part of the bytecode, padded with 9 bytes of zeros to the left, overwrites left padding of target address mstore(add(contractCode, 0x34), 0x5af43d828181803e808314602f57f35bfd000000000000000000000000000000) // Final part of bytecode, offset by 52 bytes proxyContract := create(0, add(contractCode, 0x09), 60) // total length 60 bytes if iszero(extcodesize(proxyContract)) { revert(0, 0) } // check if the _data.length > 0 and if it is forward it to the newly created contract let dataLength := mload(_data) if iszero(iszero(dataLength)) { if iszero(call(gas, proxyContract, 0, add(_data, 0x20), dataLength, 0, 0)) { revert(0, 0) } } } } function createProxyProject( uint256 _cost, uint256 _costProportion, uint256 _stakingPeriod, address _proposer, uint256 _proposerType, uint256 _proposerStake, bytes memory _ipfsHash, address _reputationRegistry, address _tokenRegistry ) internal returns (address) { require(_ipfsHash.length == 46); bytes memory dataToSend; assembly { //let ipfsHashSize := mload(_ipfsHash) dataToSend := mload(0x40) // Find empty memory location using "free memory pointer" mstore(add(dataToSend, 0x4), 0xf58a1adb) // this is the function ID mstore(add(dataToSend, 0x24), _cost) mstore(add(dataToSend, 0x44), _costProportion) mstore(add(dataToSend, 0x64), _stakingPeriod) mstore(add(dataToSend, 0x84), _proposer) mstore(add(dataToSend, 0xa4), _proposerType) mstore(add(dataToSend, 0xc4), _proposerStake) mstore(add(dataToSend, 0xe4), 0x120) // <--- _ipfsHash data location part (length + contents) mstore(add(dataToSend, 0x104), _reputationRegistry) mstore(add(dataToSend, 0x124), _tokenRegistry) mstore(add(dataToSend, 0x144), 46) // <--- Length of the IPFS hash size mstore(add(dataToSend, 0x164), mload(add(_ipfsHash, 0x20))) mstore(add(dataToSend, 0x184), mload(add(_ipfsHash, 0x40))) mstore(dataToSend, 0x172) // 4 bytes (function ID) + 32 bytes per parameter * 9 + 32 bytes of "length of bytes" + first 32 bytes of bytes data + 14 bytes = 370 bytes [0x172 bytes] // updating the free memory pointer with the length of tightly packed mstore(0x40, add(dataToSend, 0x192)) // 0x192 == 0x172 + 0x20 } address projectAddress = createProxy(projectContractAddress, dataToSend); return projectAddress; } function createProxyTask( bytes32 _hash, address _tokenRegistry, address _reputationRegistry ) internal returns (address) { bytes memory dataToSend; assembly { dataToSend := mload(0x40) mstore(add(dataToSend, 0x4), 0xae4d1af6) mstore(add(dataToSend, 0x24), _hash) mstore(add(dataToSend, 0x44), _tokenRegistry) mstore(add(dataToSend, 0x64), _reputationRegistry) mstore(dataToSend, 0x64)/// 4 + 32 * 3 == 100 bytes mstore(0x40, add(dataToSend, 0x84)) } address taskAddress = createProxy(taskContractAddress, dataToSend); return taskAddress; } // ===================================================================== // STATE CHANGE // ===================================================================== /** @notice Calls the project library checkStaked function @dev Used to create the correct msg.sender to manage control @param _projectAddress Address of the project @return Boolean representing Staked status */ function checkStaked(address payable _projectAddress) external returns (bool) { require(!freeze); require(projects[_projectAddress] == true); bool staked = ProjectLibrary.checkStaked(_projectAddress); emit LogProjectFullyStaked(_projectAddress, staked); return staked; } /** @notice Calls the project library checkActive function, passing along the topTaskHash of the project at `_projectAddress` @dev Used to create the correct msg.sender to manage control @param _projectAddress Address of the project @return Boolean representing Active status */ function checkActive(address payable _projectAddress) public returns (bool) { require(!freeze); require(projects[_projectAddress] == true); bytes32 topTaskHash = stakedProjects[_projectAddress].topTaskHash; bool active = ProjectLibrary.checkActive(_projectAddress, topTaskHash, stakedProjects[_projectAddress].numSubmissionsByWeight[topTaskHash], tokenRegistryAddress, reputationRegistryAddress, hyphaTokenAddress); emit LogProjectActive(_projectAddress, topTaskHash, active); return active; } /** @notice Calls the project library checkValidate function @dev Used to create the correct msg.sender to manage control @param _projectAddress Address of the project @return Boolean representing Validate status */ function checkValidate(address payable _projectAddress) external { require(!freeze); require(projects[_projectAddress] == true); bool validate = ProjectLibrary.checkValidate(_projectAddress, tokenRegistryAddress, hyphaTokenAddress); emit LogProjectValidate(_projectAddress, validate); } /** @notice Calls the project library checkVoting function @dev Used to create the correct msg.sender to manage control @param _projectAddress Address of the project @return Boolean representing Voting status */ function checkVoting(address payable _projectAddress) external { require(!freeze); require(projects[_projectAddress] == true); bool vote = ProjectLibrary.checkVoting(_projectAddress, tokenRegistryAddress, hyphaTokenAddress, address(plcrVoting)); emit LogProjectVoting(_projectAddress, vote); } /** @notice Calls the project library checkEnd function. Burns tokens and reputation if the project fails @dev Used to create the correct msg.sender to manage control @param _projectAddress Address of the project @return uint representing Final Status */ function checkEnd(address payable _projectAddress) external { require(!freeze); require(projects[_projectAddress] == true); uint end = ProjectLibrary.checkEnd(_projectAddress, tokenRegistryAddress, hyphaTokenAddress, address(plcrVoting), reputationRegistryAddress); emit LogProjectEnd(_projectAddress, end); } // ===================================================================== // PROPOSER // ===================================================================== /** @notice Create a project with a cost of `_cost`, a ratio of `_costProportion`, a staking period length of `_stakingPeriod`, by proposer `_proposer` of type `_proposerType` with stake of `_proposerStake` defined by ipfsHash `_ipfsHash` @dev Only callable by the ReputationRegistry or TokenRegistry, after proposer stake is confirmed. @param _cost The total cost of the project in wei @param _costProportion The proportion of the project cost divided by the HyphaToken weiBal represented as integer @param _stakingPeriod The length of time this project is open for staking @param _proposer The address of the user proposing the project @param _proposerType Denotes if a proposer is using reputation or tokens, value must be 1: tokens or 2: reputation @param _proposerStake The amount of reputation or tokens needed to create the proposal @param _ipfsHash The ipfs hash of the full project description @return Address of the created project */ function createProject( uint256 _cost, uint256 _costProportion, uint256 _stakingPeriod, address _proposer, uint256 _proposerType, uint256 _proposerStake, bytes calldata _ipfsHash ) external onlyTRorRR returns (address) { require(!freeze); address projectAddress = createProxyProject( _cost, _costProportion, _stakingPeriod, _proposer, _proposerType, _proposerStake, _ipfsHash, reputationRegistryAddress, tokenRegistryAddress ); projects[projectAddress] = true; projectsList[projectNonce] = projectAddress; projectNonce += 1; emit LogProjectCreated(projectAddress, _proposerStake); return projectAddress; } /** @notice Refund a proposer if the project at `_projectAddress` is not in state: 1 Proposed or state: 8 Expired. @dev Only called by the TokenRegistry or ReputationRegistry @param _projectAddress Address of the project @return An array with the weiCost of the project and the proposers stake */ function refundProposer(address payable _projectAddress, address proposer) external onlyTRorRR returns (uint256[2] memory) { require(!freeze); require(projects[_projectAddress] == true); Project project = Project(_projectAddress); require(project.state() > 1 && project.state() != 8); require(project.proposerStake() > 0); uint256 contractCaller; msg.sender == tokenRegistryAddress ? contractCaller = 1 : contractCaller = 0; uint256[2] memory returnValues; returnValues[0] = project.proposedCost(); returnValues[1] = project.proposerStake(); project.clearProposerStake(); emit LogRefundProposer(_projectAddress, contractCaller, proposer, returnValues[0], returnValues[1]); return returnValues; } // ===================================================================== // STAKED // ===================================================================== /** @notice Submit a hash of a task list `_taskHash` to project at `_projectAddress` by staker `msg.sender`. Makes sure the Project is in the Active State, and calls stakedTaskHash. @dev This library is imported into all the Registries to manage project interactions @param _projectAddress Address of the project @param _taskHash Hash of the task list */ function addTaskHash(address payable _projectAddress, bytes32 _taskHash) external { // format of has should be 'description', 'percentage', check via js that percentages add up to 100 prior to calling contract require(!freeze); require(projects[_projectAddress] == true); Project project = Project(_projectAddress); checkActive(_projectAddress); require(project.state() == 2); ReputationRegistry rr = ReputationRegistry(reputationRegistryAddress); TokenRegistry tr = TokenRegistry(tokenRegistryAddress); uint256 networkWeight = (rr.calculateWeightOfAddress(msg.sender) + tr.calculateWeightOfAddress(msg.sender)) / 2; uint256 stakerWeight = ProjectLibrary.calculateWeightOfAddress(_projectAddress, msg.sender); uint256 totalWeight = (networkWeight + stakerWeight) / 2; require(totalWeight > 0); stakedTaskHash(_projectAddress, msg.sender, _taskHash, totalWeight); emit LogTaskHashSubmitted(_projectAddress, _taskHash, msg.sender, totalWeight); } /** @notice Calculates the taskHash that has the highest weight of all tasks hashes submitted by stakers and stores this as the top task hash. @dev Internal helper function used to calculate the top task hash. @param _projectAddress Address of the project @param _staker Address of the staker @param _taskHash Hash of the task list @param _stakerWeight Weight of the staker */ function stakedTaskHash( address _projectAddress, address _staker, bytes32 _taskHash, uint256 _stakerWeight ) internal { StakedState storage ss = stakedProjects[_projectAddress]; if(ss.taskHashSubmissions[_staker] != 0) { //Not first time submission for this particular address bytes32 submittedTaskHash = ss.taskHashSubmissions[_staker]; ss.numSubmissionsByWeight[submittedTaskHash] -= _stakerWeight; } ss.numSubmissionsByWeight[_taskHash] += _stakerWeight; ss.taskHashSubmissions[_staker] = _taskHash; if (ss.originator[_taskHash] == address(0)) { ss.originator[_taskHash] = _staker; } if(ss.numSubmissionsByWeight[_taskHash] > ss.numSubmissionsByWeight[ss.topTaskHash]) { ss.topTaskHash = _taskHash; } } /** @notice Sets the originator of a project plan to 0 after verifying msg.sender is the originator @param _projectAddress Address of the project */ function rewardOriginator( address _projectAddress, address _claimer ) onlyTR public { require(projects[_projectAddress] == true); StakedState storage ss = stakedProjects[_projectAddress]; require(_claimer == ss.originator[ss.topTaskHash]); ss.originator[ss.topTaskHash] = address(0); } // ===================================================================== // ACTIVE // ===================================================================== /** @notice Submit the final task list with hashed tasks `_hashes` for project at `_projectAddress`. Hashes the submitted task list to validate it is the top task hash list, and creates a task for each list item with the respective hash. @dev This function is an interation and requires variable gas. @param _projectAddress Address of the project @param _hashes Array of task hashes */ // Doesn't Change State Here Could Possibly move to ProjectLibrary function submitHashList(address payable _projectAddress, bytes32[] calldata _hashes) external { require(!freeze); require(projects[_projectAddress] == true); Project project = Project(_projectAddress); require(project.state() == 3); require(keccak256(abi.encodePacked(_hashes)) == stakedProjects[_projectAddress].topTaskHash); // Fail project if topTaskHash is not over 50 require(project.hashListSubmitted() == false); project.setTaskLength(_hashes.length); for (uint256 i = 0; i < _hashes.length; i++) { address newTask = createProxyTask(_hashes[i], tokenRegistryAddress, reputationRegistryAddress); project.setTaskAddress(newTask, i); emit LogFinalTaskCreated(newTask, _projectAddress, _hashes[i], i); } project.setHashListSubmitted(); } /** @notice Claim a task at index `_index` from project at `_projectAddress` with description `_taskDescription`, weighting `_weighting` by claimer `_claimer. Set the ether reward of the task to `_weiVal` and the reputation needed to claim the task to `_reputationVal` @dev Only callable by the ReputationRegistry @param _projectAddress Address of project @param _index Index of the task in task array. @param _taskDescription Description of the task. @param _claimer Address of account to claim task. @param _weighting Weighting of this particular task (proportion of project funds) @param _weiVal Ether reward of task @param _reputationVal Reputation required to claim task */ // Doesn't Change State Here Could Possibly move to ProjectLibrary function claimTask( address payable _projectAddress, uint256 _index, bytes32 _taskDescription, address _claimer, uint _weighting, uint _weiVal, uint _reputationVal ) external onlyRR { require(!freeze); Project project = Project(_projectAddress); require(project.state() == 3); Task task = Task(project.tasks(_index)); require(keccak256(abi.encodePacked(_taskDescription, _weighting)) == task.taskHash()); require( task.claimer() == address(0) || (block.timestamp > (task.claimTime() + project.turnoverTime()) && !task.complete()) ); task.setWeighting(_weighting); task.setTaskReward(_weiVal, _reputationVal, _claimer); emit LogTaskClaimed(_projectAddress, _index, _reputationVal, _claimer); } /** @notice Mark that task at index `_index` in project at `_projectAddress` as completed by the claimer `msg.sender` @param _projectAddress Address of project @param _index Index of the task in task array */ // Doesn't Change State Here Could Possibly move to ProjectLibrary function submitTaskComplete(address payable _projectAddress, uint256 _index) external { require(!freeze); Project project = Project(_projectAddress); Task task = Task(project.tasks(_index)); HyphaToken dt = HyphaToken(hyphaTokenAddress); require(task.claimer() == msg.sender); require(task.complete() == false); require(project.state() == 3); uint256 validationFee = task.setValidationEntryFee((task.weighting() * project.proposedCost() / 100) / dt.currentPrice()); task.markTaskComplete(); emit LogSubmitTaskComplete(_projectAddress, _index, validationFee); } }
Update the address of the reputation registry _newReputationRegistry Address of the new reputation registry/
function updateReputationRegistry(address _newReputationRegistry) external onlyOwner { reputationRegistryAddress = _newReputationRegistry; }
12,671,227
pragma solidity >=0.5.4 <0.6.0; interface tokenRecipient { function RECEIVEAPPROVAL172(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } //inject NONSTANDARD NAMING library SafeMath { function MUL710(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING // 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; } function DIV595(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function SUB853(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING assert(b <= a); return a - b; } function ADD540(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING c = a + b; assert(c >= a); return c; } } interface INameTAOPosition { function SENDERISADVOCATE978(address _sender, address _id) external view returns (bool); //inject NONSTANDARD NAMING function SENDERISLISTENER841(address _sender, address _id) external view returns (bool); //inject NONSTANDARD NAMING function SENDERISSPEAKER648(address _sender, address _id) external view returns (bool); //inject NONSTANDARD NAMING function SENDERISPOSITION99(address _sender, address _id) external view returns (bool); //inject NONSTANDARD NAMING function GETADVOCATE521(address _id) external view returns (address); //inject NONSTANDARD NAMING function NAMEISADVOCATE881(address _nameId, address _id) external view returns (bool); //inject NONSTANDARD NAMING function NAMEISPOSITION327(address _nameId, address _id) external view returns (bool); //inject NONSTANDARD NAMING function INITIALIZE405(address _id, address _advocateId, address _listenerId, address _speakerId) external returns (bool); //inject NONSTANDARD NAMING function DETERMINEPOSITION456(address _sender, address _id) external view returns (uint256); //inject NONSTANDARD NAMING } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event TRANSFER193(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING // This generates a public event on the blockchain that will notify clients event APPROVAL454(address indexed _owner, address indexed _spender, uint256 _value); //inject NONSTANDARD NAMING // This notifies clients about the amount burnt event BURN994(address indexed from, uint256 value); //inject NONSTANDARD NAMING constructor (uint256 initialSupply, string memory tokenName, string memory tokenSymbol) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } function _TRANSFER285(address _from, address _to, uint _value) internal { //inject NONSTANDARD NAMING // Prevent transfer to 0x0 address. Use burn() instead require(_to != address(0)); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit TRANSFER193(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function TRANSFER874(address _to, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING _TRANSFER285(msg.sender, _to, _value); return true; } function TRANSFERFROM282(address _from, address _to, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _TRANSFER285(_from, _to, _value); return true; } function APPROVE265(address _spender, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING allowance[msg.sender][_spender] = _value; emit APPROVAL454(msg.sender, _spender, _value); return true; } function APPROVEANDCALL88(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { //inject NONSTANDARD NAMING tokenRecipient spender = tokenRecipient(_spender); if (APPROVE265(_spender, _value)) { spender.RECEIVEAPPROVAL172(msg.sender, _value, address(this), _extraData); return true; } } function BURN239(uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit BURN994(msg.sender, _value); return true; } function BURNFROM882(address _from, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit BURN994(_from, _value); return true; } } contract TAO { using SafeMath for uint256; address public vaultAddress; string public name; // the name for this TAO address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address // TAO's data string public datHash; string public database; string public keyValue; bytes32 public contentId; uint8 public typeId; constructor (string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _vaultAddress ) public { name = _name; originId = _originId; datHash = _datHash; database = _database; keyValue = _keyValue; contentId = _contentId; // Creating TAO typeId = 0; vaultAddress = _vaultAddress; } modifier ONLYVAULT404 { //inject NONSTANDARD NAMING require (msg.sender == vaultAddress); _; } function () external payable { } function TRANSFERETH144(address payable _recipient, uint256 _amount) public ONLYVAULT404 returns (bool) { //inject NONSTANDARD NAMING _recipient.transfer(_amount); return true; } function TRANSFERERC20563(address _erc20TokenAddress, address _recipient, uint256 _amount) public ONLYVAULT404 returns (bool) { //inject NONSTANDARD NAMING TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress); _erc20.TRANSFER874(_recipient, _amount); return true; } } contract Name is TAO { constructor (string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _vaultAddress) TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public { // Creating Name typeId = 1; } } library AOLibrary { using SafeMath for uint256; uint256 constant private _multiplier_divisor322 = 10 ** 6; // 1000000 = 1 //inject NONSTANDARD NAMING uint256 constant private _percentage_divisor262 = 10 ** 6; // 100% = 1000000 //inject NONSTANDARD NAMING function ISTAO231(address _taoId) public view returns (bool) { //inject NONSTANDARD NAMING return (_taoId != address(0) && bytes(TAO(address(uint160(_taoId))).name()).length > 0 && TAO(address(uint160(_taoId))).originId() != address(0) && TAO(address(uint160(_taoId))).typeId() == 0); } function ISNAME781(address _nameId) public view returns (bool) { //inject NONSTANDARD NAMING return (_nameId != address(0) && bytes(TAO(address(uint160(_nameId))).name()).length > 0 && Name(address(uint160(_nameId))).originId() != address(0) && Name(address(uint160(_nameId))).typeId() == 1); } function ISVALIDERC20TOKENADDRESS312(address _tokenAddress) public view returns (bool) { //inject NONSTANDARD NAMING if (_tokenAddress == address(0)) { return false; } TokenERC20 _erc20 = TokenERC20(_tokenAddress); return (_erc20.totalSupply() >= 0 && bytes(_erc20.name()).length > 0 && bytes(_erc20.symbol()).length > 0); } function ISTHEAO403(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) { //inject NONSTANDARD NAMING return (_sender == _theAO || ( (ISTAO231(_theAO) || ISNAME781(_theAO)) && _nameTAOPositionAddress != address(0) && INameTAOPosition(_nameTAOPositionAddress).SENDERISADVOCATE978(_sender, _theAO) ) ); } function PERCENTAGE_DIVISOR218() public pure returns (uint256) { //inject NONSTANDARD NAMING return _percentage_divisor262; } function MULTIPLIER_DIVISOR371() public pure returns (uint256) { //inject NONSTANDARD NAMING return _multiplier_divisor322; } function DEPLOYTAO162(string memory _name, //inject NONSTANDARD NAMING address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _nameTAOVaultAddress ) public returns (TAO _tao) { _tao = new TAO(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress); } function DEPLOYNAME486(string memory _name, //inject NONSTANDARD NAMING address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _nameTAOVaultAddress ) public returns (Name _myName) { _myName = new Name(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress); } function CALCULATEWEIGHTEDMULTIPLIER712(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) { //inject NONSTANDARD NAMING if (_currentWeightedMultiplier > 0) { uint256 _totalWeightedIons = (_currentWeightedMultiplier.MUL710(_currentPrimordialBalance)).ADD540(_additionalWeightedMultiplier.MUL710(_additionalPrimordialAmount)); uint256 _totalIons = _currentPrimordialBalance.ADD540(_additionalPrimordialAmount); return _totalWeightedIons.DIV595(_totalIons); } else { return _additionalWeightedMultiplier; } } function CALCULATEPRIMORDIALMULTIPLIER760(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { //inject NONSTANDARD NAMING if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.SUB853(_totalPrimordialMinted)) { uint256 temp = _totalPrimordialMinted.ADD540(_purchaseAmount.DIV595(2)); uint256 multiplier = (_multiplier_divisor322.SUB853(_multiplier_divisor322.MUL710(temp).DIV595(_totalPrimordialMintable))).MUL710(_startingMultiplier.SUB853(_endingMultiplier)); return multiplier.DIV595(_multiplier_divisor322); } else { return 0; } } function CALCULATENETWORKBONUSPERCENTAGE146(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { //inject NONSTANDARD NAMING if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.SUB853(_totalPrimordialMinted)) { uint256 temp = _totalPrimordialMinted.ADD540(_purchaseAmount.DIV595(2)); uint256 bonusPercentage = (_percentage_divisor262.SUB853(_percentage_divisor262.MUL710(temp).DIV595(_totalPrimordialMintable))).MUL710(_startingMultiplier.SUB853(_endingMultiplier)).DIV595(_percentage_divisor262); return bonusPercentage; } else { return 0; } } function CALCULATENETWORKBONUSAMOUNT621(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { //inject NONSTANDARD NAMING uint256 bonusPercentage = CALCULATENETWORKBONUSPERCENTAGE146(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier); uint256 networkBonus = bonusPercentage.MUL710(_purchaseAmount).DIV595(_percentage_divisor262); return networkBonus; } function CALCULATEMAXIMUMBURNAMOUNT319(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) { //inject NONSTANDARD NAMING return (_maximumMultiplier.MUL710(_primordialBalance).SUB853(_primordialBalance.MUL710(_currentWeightedMultiplier))).DIV595(_maximumMultiplier); } function CALCULATEMULTIPLIERAFTERBURN888(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) { //inject NONSTANDARD NAMING return _primordialBalance.MUL710(_currentWeightedMultiplier).DIV595(_primordialBalance.SUB853(_amountToBurn)); } function CALCULATEMULTIPLIERAFTERCONVERSION91(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) { //inject NONSTANDARD NAMING return _primordialBalance.MUL710(_currentWeightedMultiplier).DIV595(_primordialBalance.ADD540(_amountToConvert)); } function NUMDIGITS612(uint256 number) public pure returns (uint8) { //inject NONSTANDARD NAMING uint8 digits = 0; while(number != 0) { number = number.DIV595(10); digits++; } return digits; } } contract TheAO { address public theAO; address public nameTAOPositionAddress; // Check whether an address is whitelisted and granted access to transact // on behalf of others mapping (address => bool) public whitelist; constructor() public { theAO = msg.sender; } modifier INWHITELIST24() { //inject NONSTANDARD NAMING require (whitelist[msg.sender] == true); _; } function TRANSFEROWNERSHIP920(address _theAO) public { //inject NONSTANDARD NAMING require (msg.sender == theAO); require (_theAO != address(0)); theAO = _theAO; } function SETWHITELIST120(address _account, bool _whitelist) public { //inject NONSTANDARD NAMING require (msg.sender == theAO); require (_account != address(0)); whitelist[_account] = _whitelist; } } contract TAOCurrency is TheAO { using SafeMath for uint256; // Public variables of the contract string public name; string public symbol; uint8 public decimals; // To differentiate denomination of TAO Currency uint256 public powerOfTen; uint256 public totalSupply; // This creates an array with all balances // address is the address of nameId, not the eth public address mapping (address => uint256) public balanceOf; // This generates a public event on the blockchain that will notify clients // address is the address of TAO/Name Id, not eth public address event TRANSFER193(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING // This notifies clients about the amount burnt // address is the address of TAO/Name Id, not eth public address event BURN994(address indexed from, uint256 value); //inject NONSTANDARD NAMING constructor (string memory _name, string memory _symbol, address _nameTAOPositionAddress) public { name = _name; // Set the name for display purposes symbol = _symbol; // Set the symbol for display purposes powerOfTen = 0; decimals = 0; SETNAMETAOPOSITIONADDRESS170(_nameTAOPositionAddress); } modifier ONLYTHEAO376 { //inject NONSTANDARD NAMING require (AOLibrary.ISTHEAO403(msg.sender, theAO, nameTAOPositionAddress)); _; } modifier ISNAMEORTAO154(address _id) { //inject NONSTANDARD NAMING require (AOLibrary.ISNAME781(_id) || AOLibrary.ISTAO231(_id)); _; } function TRANSFEROWNERSHIP920(address _theAO) public ONLYTHEAO376 { //inject NONSTANDARD NAMING require (_theAO != address(0)); theAO = _theAO; } function SETWHITELIST120(address _account, bool _whitelist) public ONLYTHEAO376 { //inject NONSTANDARD NAMING require (_account != address(0)); whitelist[_account] = _whitelist; } function SETNAMETAOPOSITIONADDRESS170(address _nameTAOPositionAddress) public ONLYTHEAO376 { //inject NONSTANDARD NAMING require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } function TRANSFERFROM282(address _from, address _to, uint256 _value) public INWHITELIST24 ISNAMEORTAO154(_from) ISNAMEORTAO154(_to) returns (bool) { //inject NONSTANDARD NAMING _TRANSFER285(_from, _to, _value); return true; } function MINT678(address target, uint256 mintedAmount) public INWHITELIST24 ISNAMEORTAO154(target) returns (bool) { //inject NONSTANDARD NAMING _MINT887(target, mintedAmount); return true; } function WHITELISTBURNFROM289(address _from, uint256 _value) public INWHITELIST24 ISNAMEORTAO154(_from) returns (bool success) { //inject NONSTANDARD NAMING require(balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].SUB853(_value); // Subtract from the targeted balance totalSupply = totalSupply.SUB853(_value); // Update totalSupply emit BURN994(_from, _value); return true; } function _TRANSFER285(address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].ADD540(_value) >= balanceOf[_to]); // Check for overflows uint256 previousBalances = balanceOf[_from].ADD540(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].SUB853(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].ADD540(_value); // Add the same to the recipient emit TRANSFER193(_from, _to, _value); assert(balanceOf[_from].ADD540(balanceOf[_to]) == previousBalances); } function _MINT887(address target, uint256 mintedAmount) internal { //inject NONSTANDARD NAMING balanceOf[target] = balanceOf[target].ADD540(mintedAmount); totalSupply = totalSupply.ADD540(mintedAmount); emit TRANSFER193(address(0), address(this), mintedAmount); emit TRANSFER193(address(this), target, mintedAmount); } } contract PathosGiga is TAOCurrency { constructor(string memory _name, string memory _symbol, address _nameTAOPositionAddress) TAOCurrency(_name, _symbol, _nameTAOPositionAddress) public { powerOfTen = 9; decimals = 9; } }
inject NONSTANDARD NAMING
function CALCULATENETWORKBONUSPERCENTAGE146(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
13,026,382
./partial_match/56/0x91633225efA68e71C3040565D48977deF1c4d20d/sources/ChocoToken.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), "CHOCO::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "CHOCO::delegateBySig: invalid nonce"); require(now <= expiry, "CHOCO::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
11,171,210
./full_match/43114/0x83bC0C9a5f831C9f5eEA317B0c74883Edf8D38af/sources/MM2/MOON.sol
TODO needs insert function that maintains order. TODO needs NatSpec documentation comment. Inserts new value by moving existing value at provided index to end of array and setting provided value at provided index/
function _insert(Set storage set_, uint256 index_, bytes32 valueToInsert_ ) private returns ( bool ) { require( set_._values.length > index_ ); require( !_contains( set_, valueToInsert_ ), "Remove value you wish to insert if you wish to reorder array." ); bytes32 existingValue_ = _at( set_, index_ ); set_._values[index_] = valueToInsert_; return _add( set_, existingValue_); }
4,534,344
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "../math/SafeMathU128.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** Writes a simple match function This function needs to accept as params: All the raw params of the order commitment (what NFT is sold - identified by contract and id, how much it is sold for - identified by ERC20 contract and amount, gossiper and anything else you've decided to include) seller signature of keccak256 hash of all the params (when hashing use encode not encodePacked) matcher signature of keccak256 hash of all the params The flow of operations is going to be: - The seller approves the marketplace contract to move their NFT (ERC721 approve) - The seller signs the order commitment and sends it to the gossiping node - The buyer requests the information from the matching node (getting the matcher signature, allongside all the other info) - The buyer approves the sell amount (ERC20 approve) - The buyer sends a buy tx where - The contract checks all the params and requirements - The contract checks if the order commitment is signed by the seller - The contract tries to transferFrom the NFT from the seller to the buyer - (might fail if the signer has sold it already or trasnferred it away) - The contract tries to charge the buyer for the amount via transferFrom - The contract deducts the commission fee that is distributed between the gossiper, matcher and main processor (some/all of these might be the same addresses) */ contract Marketplace { using SafeMath for uint128; // Commission allocation ratio in percentages // 1 - to the gossiping node // 2 - to the treasury // 3 - to the main processor uint8[3] public allocationRatio; // Treasury address address public treasury; // Stores canceled or matched orders mapping (bytes32 => bool) public cancelledOrMatched; constructor(uint8[3] memory _allocationRatio, address _treasury) public { require( _allocationRatio[0] + _allocationRatio[1] + _allocationRatio[2] <= 100, "Allocation ratio must sum up to 100" ); allocationRatio = _allocationRatio; treasury = _treasury; } enum OrderType { BUY, SELL } /** /* @notice An ECDSA signature */ struct MarketplaceSignature { uint8 v; bytes32 r; bytes32 s; } /** * @notice An order in the exchange */ struct Order { address signer; // Someone who signed this order commitment, both buyer and seller can sign address taker; // Someone who is taking this order commitment, i.e buyer address contractAddress; // The contract of NFT address tokenAddress; // Payment token's address uint128 nftId; address gossiper; // the node that first gossiped the order uint128 price; // the price of the NFT in payment tokens OrderType order_type; // BUY or SELL } event Match ( address indexed signer, address indexed taker, address indexed contractAddress, uint128 nftId, address gossiper, uint128 price ); function getAllocationRatio() public view returns (uint8[3] memory) { return allocationRatio; } function setAllocationRatio(uint8[3] memory _allocationRatio) public { // make sure the sum of the ratios is 100 require( _allocationRatio[0] + _allocationRatio[1] + _allocationRatio[2] <= 100, "The sum of the allocation ratios must be 100" ); allocationRatio = _allocationRatio; } /** * @notice Prepare Order for signature */ function hashForSignature(Order memory order) internal pure returns (bytes32) { return keccak256( abi.encode( order.signer, order.taker, order.contractAddress, order.tokenAddress, order.nftId, order.gossiper, order.price, order.order_type ) ); } /** * @notice Validate order, given signature and order */ function validateOrder(bytes32 hash, Order memory order, MarketplaceSignature memory signature) internal view returns (bool) { // make sure order is not already matched if (cancelledOrMatched[hash]) { return false; } if (ecrecover(hash, signature.v, signature.r, signature.s) == order.signer) { return true; } return false; } /** * @notice Validate order and create hash */ function validateOrderAndHash(Order memory order, MarketplaceSignature memory signature) internal view returns (bytes32) { bytes32 hash = hashForSignature(order); require(validateOrder(hash, order, signature), "Invalid order"); return hash; } /** * @notice Do orders match? Do basic checks */ function ordersMatch(Order memory buy, Order memory sell) internal pure returns (bool) { // taker address can be 0x00 or the address of the taker return ( buy.contractAddress == sell.contractAddress && buy.nftId == sell.nftId && buy.tokenAddress == sell.tokenAddress && buy.gossiper == sell.gossiper && buy.price == sell.price && (buy.order_type == OrderType.BUY || sell.order_type == OrderType.SELL) && (sell.taker == address(0) || sell.taker == buy.signer) && (buy.taker == address(0) || buy.taker == sell.signer) ); } /** * @notice Process commisions for matched order * @dev This function is called when the order is matched * @dev The commission is calculated as a percentage of the fee */ function processCommissions( uint128 amount, address payable gossiper, address payable matcher ) public payable returns (bool) { uint128 gossiperCommission = amount * allocationRatio[0] / 100; uint128 treasuryCommission = amount * allocationRatio[1] / 100; uint128 matcherCommission = amount * allocationRatio[2] / 100; // Gossiper commission (bool gossiperSent, bytes memory gossiperData) = gossiper.call{value: gossiperCommission}(""); require(gossiperSent, "Could not send gossiper commission"); // Main processor commission (bool matcherSent, bytes memory matcherData) = matcher.call{value: matcherCommission}(""); require(matcherSent, "Could not send matcher commission"); // Treasury commission (bool treasurySent, bytes memory treasuryData) = treasury.call{value: treasuryCommission}(""); require(treasurySent, "Could not send treasury commission"); return gossiperSent && matcherSent && treasurySent; } /** * @notice A bid in the exchange * @dev Buyer should give approval to this contract for the ERC20 tokens * @dev Seller should give approval to this contract to move the NFT */ function matchOrder( Order memory buy, MarketplaceSignature memory buySignature, Order memory sell, MarketplaceSignature memory sellSignature, address payable matcher ) public payable returns (bool) { // make sure the order is valid bytes32 buyHash; if (buy.signer != msg.sender) { buyHash = validateOrderAndHash(buy, buySignature); } // make sure the sell order is valid bytes32 sellHash; if (sell.signer != msg.sender) { sellHash = validateOrderAndHash(sell, sellSignature); } require(ordersMatch(buy, sell), "Orders do not match"); // mark the orders as matched if (msg.sender != buy.signer) { cancelledOrMatched[buyHash] = true; } if (msg.sender != sell.signer) { cancelledOrMatched[sellHash] = true; } /** Process transfer */ // transfer the NFT from the signer to the taker ERC721 nftContract = ERC721(buy.contractAddress); nftContract.safeTransferFrom(sell.signer, buy.taker, buy.nftId); // process payment ERC20 tokenContract = ERC20(buy.tokenAddress); // transfer erc20 token from taker to signer require( tokenContract.transferFrom(buy.taker, sell.signer, buy.price), "Could not transfer payment token" ); // process commissions require( processCommissions(uint128(msg.value), payable(buy.gossiper), matcher), "Could not process commissions" ); // emit match event emit Match( sell.signer, buy.taker, buy.contractAddress, buy.nftId, buy.gossiper, buy.price ); } }
Validate order, given signature and order/ make sure order is not already matched
function validateOrder(bytes32 hash, Order memory order, MarketplaceSignature memory signature) internal view returns (bool) { if (cancelledOrMatched[hash]) { return false; } if (ecrecover(hash, signature.v, signature.r, signature.s) == order.signer) { return true; } return false; }
12,755,528
./full_match/5/0xA0E69f8Cf9f8F8555e1Bd0983214871e674ac30F/sources/contracts/tenderswap/TenderSwap.sol
@inheritdoc ITenderSwap
function removeLiquidity( uint256 amount, uint256[2] calldata minAmounts, uint256 deadline ) external override nonReentrant deadlineCheck(deadline) returns (uint256[2] memory) { SwapUtils.PooledToken[2] memory tokens_ = [token0, token1]; return SwapUtils.removeLiquidity(amount, tokens_, minAmounts, lpToken); }
7,038,724
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/[email protected]/token/ERC20/IERC20.sol"; import "@openzeppelin/[email protected]/token/ERC20/SafeERC20.sol"; import "@openzeppelin/[email protected]/math/SafeMath.sol"; import "@openzeppelin/[email protected]/access/Ownable.sol"; import "./Meshcoin.sol"; // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once Meshcoin is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MeshcoinPools is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 rewardRemain; // Remain rewards // We do some fancy math here. Basically, any point in time, the amount of Meshcoins // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRewardPerShare) + user.rewardRemain - 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 calc the pending rewards and record at rewardRemain. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Meshcoins to distribute per block. uint256 lastRewardBlock; // Last block number that Meshcoins distribution occurs. uint256 accRewardPerShare; // Accumulated Meshcoins per share, times 1e18. See below. uint256 totalAmount; // Total amount of current pool deposit. uint256 pooltype; // pool type, 1 = Single ERC20 or 2 = LP Token or 3 = nft Pool } // The Meshcoin! Meshcoin public msc; // Dev address. address public devaddr; // Operater address. address public opeaddr; // Meshcoins created per block. uint256 public rewardPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // the Meshcoins distribution uint256 public rewardDistributionFactor = 1e9; // The block number when Meshcoin mining starts. uint256 public startBlock; // Reduction uint256 public reductionBlockPeriod; // 60/3*60*24*7 = 201600 uint256 public maxReductionCount; uint256 public nextReductionBlock; uint256 public reductionCounter; // Block number when bonus MSC reduction period ends. uint256 public bonusStableBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event Claim(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor ( Meshcoin _msc, address _devaddr, address _opeaddr, uint256 _rewardPerBlock, uint256 _startBlock ) public { require(_devaddr != address(0), "_devaddr address cannot be 0"); require(_opeaddr != address(0), "_opeaddr address cannot be 0"); msc = _msc; devaddr = _devaddr; opeaddr = _opeaddr; startBlock = _startBlock; rewardPerBlock = _rewardPerBlock; reductionBlockPeriod = 201600; // 60/3*60*24*7 = 201600 maxReductionCount = 12; bonusStableBlock = _startBlock.add(reductionBlockPeriod.mul(maxReductionCount)); nextReductionBlock = _startBlock.add(reductionBlockPeriod); } modifier validatePoolByPid(uint256 _pid) { require (_pid < poolInfo.length , "Pool does not exist") ; _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, uint256 _pooltype) external onlyOwner { uint256 _len = poolInfo.length; for(uint256 i = 0; i < _len; i++){ require(_lpToken != poolInfo[i].lpToken, "LPToken already exists"); } massUpdatePools(); uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0, totalAmount: 0, pooltype: _pooltype })); } // Set the number of msc produced by each block function setRewardPerBlock(uint256 _newPerBlock) external onlyOwner { massUpdatePools(); rewardPerBlock = _newPerBlock; } function setRewardDistributionFactor(uint256 _rewardDistributionFactor) external onlyOwner { massUpdatePools(); rewardDistributionFactor = _rewardDistributionFactor; } // Update the given pool's Meshcoin allocation point. Can only be called by the owner. function setAllocPoint(uint256 _pid, uint256 _allocPoint) external onlyOwner validatePoolByPid(_pid) { massUpdatePools(); totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Pooltype to set pool display type on frontend. function setPoolType(uint256 _pid, uint256 _pooltype) external onlyOwner validatePoolByPid(_pid) { poolInfo[_pid].pooltype = _pooltype; } function setReductionArgs(uint256 _reductionBlockPeriod, uint256 _maxReductionCount) external onlyOwner { nextReductionBlock = nextReductionBlock.sub(reductionBlockPeriod).add(_reductionBlockPeriod); bonusStableBlock = nextReductionBlock.add(_reductionBlockPeriod.mul(_maxReductionCount.sub(reductionCounter).sub(1))); reductionBlockPeriod = _reductionBlockPeriod; maxReductionCount = _maxReductionCount; } // Return reward multiplier over the given _from to _to block. function getBlocksReward(uint256 _from, uint256 _to) public view returns (uint256 value) { uint256 prevReductionBlock = nextReductionBlock.sub(reductionBlockPeriod); if ((_from >= prevReductionBlock && _to <= nextReductionBlock) || (_from > bonusStableBlock)) { value = getBlockReward(_to.sub(_from), rewardPerBlock, reductionCounter); } else if (_from < prevReductionBlock && _to < nextReductionBlock) { uint256 part1 = getBlockReward(_to.sub(prevReductionBlock), rewardPerBlock, reductionCounter); uint256 part2 = getBlockReward(prevReductionBlock.sub(_from), rewardPerBlock, reductionCounter.sub(1)); value = part1.add(part2); } else // if (_from > prevReductionBlock && _to > nextReductionBlock) { uint256 part1 = getBlockReward(_to.sub(nextReductionBlock), rewardPerBlock, reductionCounter.add(1)); uint256 part2 = getBlockReward(nextReductionBlock.sub(_from), rewardPerBlock, reductionCounter); value = part1.add(part2); } value = value.mul(rewardDistributionFactor).div(1e9); } // Return reward per block function getBlockReward(uint256 _blockCount, uint256 _rewardPerBlock, uint256 _reductionCounter) internal view returns (uint256) { uint256 reward = _blockCount.mul(_rewardPerBlock); if (_reductionCounter == 0) { return reward; }else if (_reductionCounter >= maxReductionCount) { return reward.mul(75).div(1000); } // _reductionCounter no more than maxReductionCount (12) return reward.mul(80 ** _reductionCounter).div(100 ** _reductionCounter); } // View function to see pending Meshcoins on frontend. function pendingRewards(uint256 _pid, address _user) public validatePoolByPid(_pid) view returns (uint256 value) { PoolInfo memory pool = poolInfo[_pid]; UserInfo memory user = userInfo[_pid][_user]; value = totalRewards(pool, user).add(user.rewardRemain).sub(user.rewardDebt); } function totalRewards(PoolInfo memory _pool, UserInfo memory _user) internal view returns (uint256 value) { uint256 accRewardPerShare = _pool.accRewardPerShare; if (block.number > _pool.lastRewardBlock && _pool.totalAmount != 0) { uint256 blockReward = getBlocksReward(_pool.lastRewardBlock, block.number); uint256 poolReward = blockReward.mul(_pool.allocPoint).div(totalAllocPoint); accRewardPerShare = accRewardPerShare.add(poolReward.mul(1e18).div(_pool.totalAmount)); } value = _user.amount.mul(accRewardPerShare).div(1e18); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public validatePoolByPid(_pid) { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } if (pool.allocPoint == 0) { return; } if (block.number > nextReductionBlock) { if(reductionCounter >= maxReductionCount) { bonusStableBlock = nextReductionBlock; }else{ nextReductionBlock = nextReductionBlock.add(reductionBlockPeriod); reductionCounter = reductionCounter.add(1); } } if (pool.totalAmount == 0) { pool.lastRewardBlock = block.number; return; } uint256 blockReward = getBlocksReward(pool.lastRewardBlock, block.number); uint256 poolReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); if(poolReward > 0) { // 1998%% for pools, 500%% for team and 200%% for business msc.liquidityMiningMint(devaddr, poolReward.mul(500).div(1998)); msc.liquidityMiningMint(opeaddr, poolReward.mul(200).div(1998)); msc.liquidityMiningMint(address(this), poolReward); } pool.accRewardPerShare = pool.accRewardPerShare.add(poolReward.mul(1e18).div(pool.totalAmount)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Meshcoin allocation. function deposit(uint256 _pid, uint256 _amount) external validatePoolByPid(_pid) { updatePool(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.amount > 0) { user.rewardRemain = pendingRewards(_pid, msg.sender); // user.rewardDebt = 0; } if(_amount > 0) { user.amount = user.amount.add(_amount); pool.totalAmount = pool.totalAmount.add(_amount); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); } user.rewardDebt = totalRewards(pool, user); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MeshcoinPool. function withdraw(uint256 _pid, uint256 _amount) external validatePoolByPid(_pid){ updatePool(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); user.rewardRemain = pendingRewards(_pid, msg.sender); if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.totalAmount = pool.totalAmount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = totalRewards(pool, user); emit Withdraw(msg.sender, _pid, _amount); } function claimAll(uint256 _pid) external validatePoolByPid(_pid) returns(uint256 value){ updatePool(_pid); value = pendingRewards(_pid, msg.sender); // require(value >= 0, "claim: not good"); if (value > 0) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; user.rewardRemain = 0; user.rewardDebt = totalRewards(pool, user); safeMscTransfer(msg.sender, value); } emit Claim(msg.sender, _pid, value); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external validatePoolByPid(_pid){ PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; user.rewardRemain = 0; pool.totalAmount = pool.totalAmount.sub(amount); pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Safe Meshcoin transfer function, just in case if rounding error causes pool to not have enough Meshcoins. function safeMscTransfer(address _to, uint256 _amount) internal { uint256 mscBalance = msc.balanceOf(address(this)); if (_amount > mscBalance) { msc.transfer(_to, mscBalance); } else { msc.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) external { require(_devaddr != address(0), "_devaddr address cannot be 0"); require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // Update ope address by the previous ope. function ope(address _opeaddr) external { require(_opeaddr != address(0), "_devaddr address cannot be 0"); require(msg.sender == opeaddr, "ope: wut?"); opeaddr = _opeaddr; } // If the user transfers TH to contract, it will revert receive() external payable { revert(); } }
Withdraw LP tokens from MeshcoinPool.
function withdraw(uint256 _pid, uint256 _amount) external validatePoolByPid(_pid){ updatePool(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); user.rewardRemain = pendingRewards(_pid, msg.sender); if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.totalAmount = pool.totalAmount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = totalRewards(pool, user); emit Withdraw(msg.sender, _pid, _amount); }
13,112,116
pragma solidity 0.5.10; import "./base/BanReasons.sol"; import "./interfaces/IBlockRewardAuRa.sol"; import "./interfaces/IGovernance.sol"; import "./interfaces/IRandomAuRa.sol"; import "./interfaces/IStakingAuRa.sol"; import "./interfaces/IValidatorSetAuRa.sol"; import "./upgradeability/UpgradeabilityAdmin.sol"; import "./libs/SafeMath.sol"; /// @dev Stores the current validator set and contains the logic for choosing new validators /// before each staking epoch. The logic uses a random seed generated and stored by the `RandomAuRa` contract. contract ValidatorSetAuRa is UpgradeabilityAdmin, BanReasons, IValidatorSetAuRa { using SafeMath for uint256; // =============================================== Storage ======================================================== // WARNING: since this contract is upgradeable, do not remove // existing storage variables, do not change their order, // and do not change their types! uint256[] internal _currentValidators; uint256[] internal _pendingValidators; uint256[] internal _previousValidators; struct ValidatorsList { bool forNewEpoch; uint256[] list; } ValidatorsList internal _finalizeValidators; bool internal _pendingValidatorsChanged; bool internal _pendingValidatorsChangedForNewEpoch; mapping(uint256 => mapping(uint256 => uint256[])) internal _maliceReportedForBlock; mapping(uint256 => mapping(uint256 => mapping(uint256 => bool))) internal _maliceReportedForBlockMapped; /// @dev How many times a given validator (pool id) was banned. mapping(uint256 => uint256) internal _banCounter; /// @dev The block number when the ban will be lifted for the specified pool id. mapping(uint256 => uint256) internal _bannedUntil; /// @dev The block number when the ban will be lifted for delegators /// of the specified pool (id). mapping(uint256 => uint256) internal _bannedDelegatorsUntil; /// @dev The reason for the latest ban of the specified pool id. See the `_removeMaliciousValidator` /// internal function description for the list of possible reasons. mapping(uint256 => bytes32) internal _banReason; /// @dev The address of the `BlockRewardAuRa` contract. address public blockRewardContract; /// @dev The serial number of a validator set change request. The counter is incremented /// every time a validator set needs to be changed. uint256 public changeRequestCount; /// @dev A boolean flag indicating whether the specified pool id is in the current validator set. /// See also the `getValidators` getter. mapping(uint256 => bool) public isValidatorById; /// @dev A boolean flag indicating whether the specified pool id was a validator in the previous set. mapping(uint256 => bool) internal _isValidatorPrevious; /// @dev A mining address bound to a specified staking address. /// See the `_addPool` internal function. mapping(address => address) public miningByStakingAddress; /// @dev The `RandomAuRa` contract address. address public randomContract; /// @dev The number of times the specified validator (pool id) reported misbehaviors during the specified /// staking epoch. Used by the `reportMaliciousCallable` getter and `reportMalicious` function to determine /// whether a validator reported too often. mapping(uint256 => mapping(uint256 => uint256)) internal _reportingCounter; /// @dev How many times all validators reported misbehaviors during the specified staking epoch. /// Used by the `reportMaliciousCallable` getter and `reportMalicious` function to determine /// whether a validator reported too often. mapping(uint256 => uint256) internal _reportingCounterTotal; /// @dev A staking address bound to a specified mining address. /// See the `_addPool` internal function. mapping(address => address) public stakingByMiningAddress; /// @dev The `StakingAuRa` contract address. IStakingAuRa public stakingContract; /// @dev The pool id of the non-removable validator. /// Returns zero if a non-removable validator is not defined. uint256 public unremovableValidator; /// @dev How many times the given pool id has become a validator. mapping(uint256 => uint256) internal _validatorCounter; /// @dev The block number when the `finalizeChange` function was called to apply /// the current validator set formed by the `newValidatorSet` function. If it is zero, /// it means the `newValidatorSet` function has already been called (a new staking epoch has been started), /// but the new staking epoch's validator set hasn't yet been finalized by the `finalizeChange` function. uint256 public validatorSetApplyBlock; /// @dev The block number of the last change in this contract. /// Can be used by Staking DApp. uint256 public lastChangeBlock; /// @dev Designates whether the specified address has ever been a mining address. /// Returns pool id which has ever be bound to the specified mining address. mapping(address => uint256) public hasEverBeenMiningAddress; /// @dev Designates whether the specified address has ever been a staking address. mapping(address => bool) public hasEverBeenStakingAddress; /// @dev A pool id bound to a specified mining address. /// See the `_addPool` internal function. mapping(address => uint256) public idByMiningAddress; /// @dev A pool id bound to a specified staking address. /// See the `_addPool` internal function. mapping(address => uint256) public idByStakingAddress; /// @dev A pool mining address bound to a specified id. /// See the `_addPool` internal function. mapping(uint256 => address) public miningAddressById; /// @dev A pool staking address bound to a specified id. /// See the `_addPool` internal function. mapping(uint256 => address) public stakingAddressById; /// @dev Stores the last pool id used for a new pool creation. /// Increments each time a new pool is created by the `addPool` function. uint256 public lastPoolId; struct MiningAddressChangeRequest { uint256 poolId; address newMiningAddress; } MiningAddressChangeRequest public miningAddressChangeRequest; /// @dev Stores pool's name as UTF-8 string. mapping(uint256 => string) public poolName; /// @dev Stores pool's short description as UTF-8 string. mapping(uint256 => string) public poolDescription; /// @dev The `Governance` contract address. IGovernance public governanceContract; // ============================================== Constants ======================================================= /// @dev The max number of validators. uint256 public constant MAX_VALIDATORS = 19; // ================================================ Events ======================================================== /// @dev Emitted by the `changeMiningAddress` function. /// @param poolId The ID of a pool for which the mining address is changed. /// @param oldMiningAddress An old mining address of the pool. /// @param newMiningAddress A new mining address of the pool. event ChangedMiningAddress( uint256 indexed poolId, address indexed oldMiningAddress, address indexed newMiningAddress ); /// @dev Emitted by the `changeStakingAddress` function. /// @param poolId The ID of a pool for which the staking address is changed. /// @param oldStakingAddress An old staking address of the pool. /// @param newStakingAddress A new staking address of the pool. event ChangedStakingAddress( uint256 indexed poolId, address indexed oldStakingAddress, address indexed newStakingAddress ); /// @dev Emitted by the `emitInitiateChange` function when a new validator set /// needs to be applied by validator nodes. See https://openethereum.github.io/Validator-Set.html /// @param parentHash Should be the parent block hash, otherwise the signal won't be recognized. /// @param newSet An array of new validators (their mining addresses). event InitiateChange(bytes32 indexed parentHash, address[] newSet); /// @dev Emitted by the `reportMalicious` function to signal that a specified validator reported /// misbehavior by a specified malicious validator at a specified block number. /// @param reportingValidator The mining address of the reporting validator. /// @param maliciousValidator The mining address of the malicious validator. /// @param blockNumber The block number at which the `maliciousValidator` misbehaved. /// @param reportingPoolId The pool id of the reporting validator. /// @param maliciousPoolId The pool id of the malicious validator. event ReportedMalicious( address reportingValidator, address maliciousValidator, uint256 indexed blockNumber, uint256 indexed reportingPoolId, uint256 indexed maliciousPoolId ); /// @dev Emitted by the `_setPoolMetadata` function when the pool's metadata is changed. /// @param poolId The unique ID of the pool. /// @param name A new name of the pool. /// @param description A new short description of the pool. event SetPoolMetadata( uint256 indexed poolId, string name, string description ); // ============================================== Modifiers ======================================================= /// @dev Ensures the `initialize` function was called before. modifier onlyInitialized { require(isInitialized()); _; } /// @dev Ensures the caller is the BlockRewardAuRa contract address. modifier onlyBlockRewardContract() { require(msg.sender == blockRewardContract); _; } /// @dev Ensures the caller is the Governance contract address. modifier onlyGovernanceContract() { require(msg.sender == address(governanceContract)); _; } /// @dev Ensures the caller is the RandomAuRa contract address. modifier onlyRandomContract() { require(msg.sender == randomContract); _; } /// @dev Ensures the caller is the StakingAuRa contract address. modifier onlyStakingContract() { require(msg.sender == address(stakingContract)); _; } /// @dev Ensures the caller is the SYSTEM_ADDRESS. See https://openethereum.github.io/Validator-Set.html modifier onlySystem() { require(msg.sender == 0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE); _; } // =============================================== Setters ======================================================== /// @dev Makes the non-removable validator removable. Can only be called by the staking address of the /// non-removable validator or by the `owner`. function clearUnremovableValidator() external onlyInitialized { require(unremovableValidator != 0); address unremovableStakingAddress = stakingAddressById[unremovableValidator]; require(msg.sender == unremovableStakingAddress || msg.sender == _admin()); stakingContract.clearUnremovableValidator(unremovableValidator); unremovableValidator = 0; lastChangeBlock = _getCurrentBlockNumber(); } /// @dev Changes pool's metadata (such as name and short description). /// Can only be called by a pool owner (staking address). /// @param _name A new name of the pool as UTF-8 string. /// @param _description A new short description of the pool as UTF-8 string. function changeMetadata(string calldata _name, string calldata _description) external onlyInitialized { uint256 poolId = idByStakingAddress[msg.sender]; require(poolId != 0); _setPoolMetadata(poolId, _name, _description); lastChangeBlock = _getCurrentBlockNumber(); } /// @dev Makes a request to change validator's mining address or changes the mining address of a candidate pool /// immediately. Will fail if there is already another request. Can be called by pool's staking address. /// If this is called by a validator pool, the function emits `InitiateChange` event, /// so the mining address change is actually applied once the `finalizeChange` function is invoked. /// A validator cannot call this function at the end of a staking epoch during the last /// two randomness collection rounds (see the `RandomAuRa` contract). /// A candidate can call this function at any time. /// @param _newMiningAddress The new mining address to set for the pool /// whose staking address called this function. The new mining address shouldn't be a former /// delegator or a pool (staking address or mining address). function changeMiningAddress(address _newMiningAddress) external onlyInitialized { address stakingAddress = msg.sender; address oldMiningAddress = miningByStakingAddress[stakingAddress]; uint256 poolId = idByStakingAddress[stakingAddress]; require(_newMiningAddress != address(0)); require(oldMiningAddress != address(0)); require(oldMiningAddress != _newMiningAddress); require(poolId != 0); require(miningAddressChangeRequest.poolId == 0); // Make sure that `_newMiningAddress` has never been a delegator before require(stakingContract.getDelegatorPoolsLength(_newMiningAddress) == 0); // Make sure that `_newMiningAddress` has never been a mining address before require(hasEverBeenMiningAddress[_newMiningAddress] == 0); // Make sure that `_newMiningAddress` has never been a staking address before require(!hasEverBeenStakingAddress[_newMiningAddress]); if (isValidatorById[poolId]) { // Since the pool is a validator at the moment, we cannot change their // mining address immediately. We create a request to change the address instead. // The request will be applied by the `finalizeChange` function once the new // validator set is applied. require(initiateChangeAllowed()); require(!_pendingValidatorsChanged); // Deny requesting on the latest two randomness collection rounds // to prevend unrevealing due to validator's mining key change. require(_getCurrentBlockNumber() < stakingContract.stakingEpochEndBlock().sub( IRandomAuRa(randomContract).collectRoundLength().mul(2) )); address[] memory newSet = getPendingValidators(); for (uint256 i = 0; i < newSet.length; i++) { if (newSet[i] == oldMiningAddress) { newSet[i] = _newMiningAddress; break; } } _finalizeValidators.list = _pendingValidators; miningAddressChangeRequest.poolId = poolId; miningAddressChangeRequest.newMiningAddress = _newMiningAddress; IRandomAuRa(randomContract).clearCommit(poolId); emit InitiateChange(blockhash(_getCurrentBlockNumber() - 1), newSet); } else { // The pool is not a validator. It is a candidate, // so we can change its mining address right now. _changeMiningAddress(oldMiningAddress, _newMiningAddress, poolId, stakingAddress); lastChangeBlock = _getCurrentBlockNumber(); } emit ChangedMiningAddress(poolId, oldMiningAddress, _newMiningAddress); } /// @dev Changes the staking address of a pool. Will fail if there is already another request /// to change mining address (see `changeMiningAddress` code). Can be called by pool's staking address. /// Can be called at any time during a staking epoch. /// @param _newStakingAddress The new staking address to set for the pool /// whose old staking address called this function. The new staking address shouldn't be a former /// delegator or a pool (staking address or mining address). function changeStakingAddress(address _newStakingAddress) external onlyInitialized { address oldStakingAddress = msg.sender; uint256 poolId = idByStakingAddress[oldStakingAddress]; require(_newStakingAddress != address(0)); require(oldStakingAddress != _newStakingAddress); require(poolId != 0); require(miningAddressChangeRequest.poolId == 0); // Make sure that `_newStakingAddress` has never been a delegator before require(stakingContract.getDelegatorPoolsLength(_newStakingAddress) == 0); // Make sure that `_newStakingAddress` has never been a mining address before require(hasEverBeenMiningAddress[_newStakingAddress] == 0); // Make sure that `_newStakingAddress` has never been a staking address before require(!hasEverBeenStakingAddress[_newStakingAddress]); address miningAddress = miningAddressById[poolId]; idByStakingAddress[oldStakingAddress] = 0; idByStakingAddress[_newStakingAddress] = poolId; miningByStakingAddress[oldStakingAddress] = address(0); miningByStakingAddress[_newStakingAddress] = miningAddress; stakingAddressById[poolId] = _newStakingAddress; stakingByMiningAddress[miningAddress] = _newStakingAddress; hasEverBeenStakingAddress[_newStakingAddress] = true; lastChangeBlock = _getCurrentBlockNumber(); emit ChangedStakingAddress(poolId, oldStakingAddress, _newStakingAddress); } /// @dev Emits the `InitiateChange` event to pass a new validator set to the validator nodes. /// Called automatically by one of the current validator's nodes when the `emitInitiateChangeCallable` getter /// returns `true` (when some validator needs to be removed as malicious or the validator set needs to be /// updated at the beginning of a new staking epoch). The new validator set is passed to the validator nodes /// through the `InitiateChange` event and saved for later use by the `finalizeChange` function. /// See https://openethereum.github.io/Validator-Set.html for more info about the `InitiateChange` event. function emitInitiateChange() external onlyInitialized { require(emitInitiateChangeCallable()); bool forNewEpoch = _unsetPendingValidatorsChanged(); if (_pendingValidators.length > 0) { emit InitiateChange(blockhash(_getCurrentBlockNumber() - 1), getPendingValidators()); _finalizeValidators.list = _pendingValidators; _finalizeValidators.forNewEpoch = forNewEpoch; lastChangeBlock = _getCurrentBlockNumber(); } } /// @dev Called by the system when an initiated validator set change reaches finality and is activated. /// This function is called at the beginning of a block (before all the block transactions). /// Only valid when msg.sender == SUPER_USER (EIP96, 2**160 - 2). Stores a new validator set saved /// before by the `emitInitiateChange` function and passed through the `InitiateChange` event. /// After this function is called, the `getValidators` getter returns the new validator set. /// If this function finalizes a new validator set formed by the `newValidatorSet` function, /// an old validator set is also stored into the `_previousValidators` array. /// The `finalizeChange` is only called once for each `InitiateChange` event emitted. The next `InitiateChange` /// event is not emitted until the previous one is not yet finalized by the `finalizeChange` /// (see the code of `emitInitiateChangeCallable` getter). /// The function has unlimited gas (according to OpenEthereum and/or Nethermind client code). function finalizeChange() external onlySystem { if (_finalizeValidators.forNewEpoch) { // Apply a new validator set formed by the `newValidatorSet` function _savePreviousValidators(); _finalizeNewValidators(true); IBlockRewardAuRa(blockRewardContract).clearBlocksCreated(); validatorSetApplyBlock = _getCurrentBlockNumber(); } else if (_finalizeValidators.list.length != 0) { // Apply the changed validator set after malicious validator is removed. // It is also called after the `changeMiningAddress` function is called for a validator. _finalizeNewValidators(false); } else { // This is the very first call of the `finalizeChange` (block #1 when starting from genesis) validatorSetApplyBlock = _getCurrentBlockNumber(); } _applyMiningAddressChangeRequest(); delete _finalizeValidators; // since this moment the `emitInitiateChange` is allowed lastChangeBlock = _getCurrentBlockNumber(); } /// @dev Initializes the network parameters. Used by the /// constructor of the `InitializerAuRa` contract. /// @param _blockRewardContract The address of the `BlockRewardAuRa` contract. /// @param _governanceContract The address of the `Governance` contract. /// @param _randomContract The address of the `RandomAuRa` contract. /// @param _stakingContract The address of the `StakingAuRa` contract. /// @param _initialMiningAddresses The array of initial validators' mining addresses. /// @param _initialStakingAddresses The array of initial validators' staking addresses. /// @param _firstValidatorIsUnremovable The boolean flag defining whether the first validator in the /// `_initialMiningAddresses/_initialStakingAddresses` array is non-removable. /// Should be `false` for a production network. function initialize( address _blockRewardContract, address _governanceContract, address _randomContract, address _stakingContract, address[] calldata _initialMiningAddresses, address[] calldata _initialStakingAddresses, bool _firstValidatorIsUnremovable ) external { require(_getCurrentBlockNumber() == 0 || msg.sender == _admin()); require(!isInitialized()); // initialization can only be done once require(_blockRewardContract != address(0)); require(_randomContract != address(0)); require(_stakingContract != address(0)); require(_initialMiningAddresses.length > 0); require(_initialMiningAddresses.length == _initialStakingAddresses.length); require(_initialMiningAddresses.length <= MAX_VALIDATORS); blockRewardContract = _blockRewardContract; governanceContract = IGovernance(_governanceContract); randomContract = _randomContract; stakingContract = IStakingAuRa(_stakingContract); lastChangeBlock = _getCurrentBlockNumber(); // Add initial validators to the `_currentValidators` array for (uint256 i = 0; i < _initialMiningAddresses.length; i++) { address miningAddress = _initialMiningAddresses[i]; address stakingAddress = _initialStakingAddresses[i]; uint256 poolId = _addPool(miningAddress, stakingAddress); _currentValidators.push(poolId); _pendingValidators.push(poolId); isValidatorById[poolId] = true; _validatorCounter[poolId]++; if (i == 0 && _firstValidatorIsUnremovable) { unremovableValidator = poolId; } } } /// @dev Implements the logic which forms a new validator set. If the number of active pools /// is greater than MAX_VALIDATORS, the logic chooses the validators randomly using a random seed generated and /// stored by the `RandomAuRa` contract. /// Automatically called by the `BlockRewardAuRa.reward` function at the latest block of the staking epoch. function newValidatorSet() external onlyBlockRewardContract { uint256[] memory poolsToBeElected = stakingContract.getPoolsToBeElected(); // Choose new validators if ( poolsToBeElected.length >= MAX_VALIDATORS && (poolsToBeElected.length != MAX_VALIDATORS || unremovableValidator != 0) ) { uint256 randomNumber = IRandomAuRa(randomContract).currentSeed(); (uint256[] memory likelihood, uint256 likelihoodSum) = stakingContract.getPoolsLikelihood(); if (likelihood.length > 0 && likelihoodSum > 0) { uint256[] memory newValidators = new uint256[]( unremovableValidator == 0 ? MAX_VALIDATORS : MAX_VALIDATORS - 1 ); uint256 poolsToBeElectedLength = poolsToBeElected.length; for (uint256 i = 0; i < newValidators.length; i++) { randomNumber = uint256(keccak256(abi.encode(randomNumber))); uint256 randomPoolIndex = _getRandomIndex(likelihood, likelihoodSum, randomNumber); newValidators[i] = poolsToBeElected[randomPoolIndex]; likelihoodSum -= likelihood[randomPoolIndex]; poolsToBeElectedLength--; poolsToBeElected[randomPoolIndex] = poolsToBeElected[poolsToBeElectedLength]; likelihood[randomPoolIndex] = likelihood[poolsToBeElectedLength]; } _setPendingValidators(newValidators); } } else { _setPendingValidators(poolsToBeElected); } // From this moment the `getPendingValidators()` returns the new validator set. // Let the `emitInitiateChange` function know that the validator set is changed and needs // to be passed to the `InitiateChange` event. _setPendingValidatorsChanged(true); if (poolsToBeElected.length != 0) { // Remove pools marked as `to be removed` stakingContract.removePools(); } stakingContract.incrementStakingEpoch(); stakingContract.setStakingEpochStartBlock(_getCurrentBlockNumber() + 1); validatorSetApplyBlock = 0; lastChangeBlock = _getCurrentBlockNumber(); } /// @dev Removes malicious validators. Called by the `RandomAuRa.onFinishCollectRound` function. /// @param _miningAddresses The mining addresses of the malicious validators. function removeMaliciousValidators(address[] calldata _miningAddresses) external onlyRandomContract { _removeMaliciousValidators(_miningAddresses, BAN_REASON_UNREVEALED); } /// @dev Removes a validator from the validator set and bans its pool. /// Can only be called by the Governance contract. /// @param _poolId A pool id of the removed validator. /// @param _banUntilBlock The number of the latest block of a ban period. /// @param _reason Can be one of the following: /// - "often block delays" /// - "often block skips" /// - "often reveal skips" /// - "unrevealed" function removeValidator(uint256 _poolId, uint256 _banUntilBlock, bytes32 _reason) external onlyGovernanceContract { if (_poolId == unremovableValidator) { return; } require(miningAddressById[_poolId] != address(0)); require(_banUntilBlock != 0); if (_banUntilBlock > _bannedUntil[_poolId]) { _bannedUntil[_poolId] = _banUntilBlock; } _banCounter[_poolId]++; _banReason[_poolId] = _reason; if (_removePool(_poolId)) { _setPendingValidatorsChanged(false); } lastChangeBlock = _getCurrentBlockNumber(); } /// @dev Reports that the malicious validator misbehaved at the specified block. /// Called by the node of each honest validator after the specified validator misbehaved. /// See https://openethereum.github.io/Validator-Set.html#reporting-contract /// Can only be called when the `reportMaliciousCallable` getter returns `true`. /// @param _maliciousMiningAddress The mining address of the malicious validator. /// @param _blockNumber The block number where the misbehavior was observed. function reportMalicious( address _maliciousMiningAddress, uint256 _blockNumber, bytes calldata ) external onlyInitialized { address reportingMiningAddress = msg.sender; uint256 reportingId = idByMiningAddress[reportingMiningAddress]; uint256 maliciousId = hasEverBeenMiningAddress[_maliciousMiningAddress]; if (isReportValidatorValid(reportingMiningAddress, true)) { _incrementReportingCounter(reportingId); } ( bool callable, bool removeReportingValidator ) = reportMaliciousCallable( reportingMiningAddress, _maliciousMiningAddress, _blockNumber ); if (!callable) { if (removeReportingValidator) { // Reporting validator reported too often, so // treat them as a malicious as well address[] memory miningAddresses = new address[](1); miningAddresses[0] = reportingMiningAddress; _removeMaliciousValidators(miningAddresses, BAN_REASON_SPAM); } return; } uint256[] storage reportedValidators = _maliceReportedForBlock[maliciousId][_blockNumber]; reportedValidators.push(reportingId); _maliceReportedForBlockMapped[maliciousId][_blockNumber][reportingId] = true; emit ReportedMalicious( reportingMiningAddress, _maliciousMiningAddress, _blockNumber, reportingId, maliciousId ); // If more than 1/2 of validators reported about malicious validator // for the same `blockNumber` if (reportedValidators.length.mul(2) > _currentValidators.length) { address[] memory miningAddresses = new address[](1); miningAddresses[0] = _maliciousMiningAddress; _removeMaliciousValidators(miningAddresses, BAN_REASON_MALICIOUS); } } /// @dev Binds a mining address to the specified staking address and vice versa, /// generates a unique ID for the newly created pool, binds it to the mining/staking addresses, /// and returns it as a result. /// Called by the `StakingAuRa.addPool` function when a user wants to become a candidate and creates a pool. /// See also the `miningByStakingAddress`, `stakingByMiningAddress`, `idByMiningAddress`, `idByStakingAddress`, /// `miningAddressById`, `stakingAddressById` public mappings. /// @param _miningAddress The mining address of the newly created pool. Cannot be equal to the `_stakingAddress` /// and should never be used as a pool or delegator before. /// @param _stakingAddress The staking address of the newly created pool. Cannot be equal to the `_miningAddress` /// and should never be used as a pool or delegator before. /// @param _name A name of the pool as UTF-8 string (max length is 256 bytes). /// @param _description A short description of the pool as UTF-8 string (max length is 1024 bytes). function addPool( address _miningAddress, address _stakingAddress, string calldata _name, string calldata _description ) external onlyStakingContract returns(uint256) { uint256 poolId = _addPool(_miningAddress, _stakingAddress); _setPoolMetadata(poolId, _name, _description); return poolId; } // =============================================== Getters ======================================================== /// @dev Returns a boolean flag indicating whether delegators of the specified pool are currently banned. /// A validator pool can be banned when they misbehave (see the `_removeMaliciousValidator` function). /// @param _miningAddress The mining address of the pool. function areDelegatorsBanned(address _miningAddress) public view returns(bool) { return _getCurrentBlockNumber() <= bannedDelegatorsUntil(_miningAddress); } /// @dev Returns a boolean flag indicating whether delegators of the specified pool are currently banned. /// A validator pool can be banned when they misbehave (see the `_removeMaliciousValidator` function). /// @param _poolId An id of the pool. function areIdDelegatorsBanned(uint256 _poolId) public view returns(bool) { return _getCurrentBlockNumber() <= _bannedDelegatorsUntil[_poolId]; } /// @dev Returns how many times a given validator was banned. /// @param _miningAddress The mining address of the validator. function banCounter(address _miningAddress) public view returns(uint256) { return _banCounter[idByMiningAddress[_miningAddress]]; } /// @dev Returns the block number when the ban will be lifted for the specified mining address. /// @param _miningAddress The mining address of the pool. function bannedUntil(address _miningAddress) public view returns(uint256) { return _bannedUntil[idByMiningAddress[_miningAddress]]; } /// @dev Returns the block number when the ban will be lifted for delegators /// of the specified pool (mining address). /// @param _miningAddress The mining address of the pool. function bannedDelegatorsUntil(address _miningAddress) public view returns(uint256) { return _bannedDelegatorsUntil[idByMiningAddress[_miningAddress]]; } /// @dev Returns the reason for the latest ban of the specified mining address. See the `_removeMaliciousValidator` /// internal function description for the list of possible reasons. /// @param _miningAddress The mining address of the pool. function banReason(address _miningAddress) public view returns(bytes32) { return _banReason[idByMiningAddress[_miningAddress]]; } /// @dev Returns a boolean flag indicating whether the `emitInitiateChange` function can be called /// at the moment. Used by a validator's node and `TxPermission` contract (to deny dummy calling). function emitInitiateChangeCallable() public view returns(bool) { return initiateChangeAllowed() && _pendingValidatorsChanged; } /// @dev Returns the current array of validators which should be passed to the `InitiateChange` event. /// The pending array is changed when a validator is removed as malicious /// or the validator set is updated by the `newValidatorSet` function. /// Every time the pending array is changed, it is marked by the `_setPendingValidatorsChanged` and then /// used by the `emitInitiateChange` function which emits the `InitiateChange` event to all /// validator nodes. function getPendingValidators() public view returns(address[] memory) { address[] memory miningAddresses = new address[](_pendingValidators.length); for (uint256 i = 0; i < miningAddresses.length; i++) { miningAddresses[i] = miningAddressById[_pendingValidators[i]]; } return miningAddresses; } /// @dev Returns the current array of validators (their pool ids). /// The pending array is changed when a validator is removed as malicious /// or the validator set is updated by the `newValidatorSet` function. /// Every time the pending array is changed, it is marked by the `_setPendingValidatorsChanged` and then /// used by the `emitInitiateChange` function which emits the `InitiateChange` event to all /// validator nodes. function getPendingValidatorsIds() public view returns(uint256[] memory) { return _pendingValidators; } /// @dev Returns the current validator set (an array of mining addresses) /// which always matches the validator set kept in validator's node. function getValidators() public view returns(address[] memory) { address[] memory miningAddresses = new address[](_currentValidators.length); for (uint256 i = 0; i < miningAddresses.length; i++) { miningAddresses[i] = miningAddressById[_currentValidators[i]]; } return miningAddresses; } /// @dev Returns the current validator set (an array of pool ids). function getValidatorsIds() public view returns(uint256[] memory) { return _currentValidators; } /// @dev A boolean flag indicating whether the `emitInitiateChange` can be called at the moment. /// Used by the `emitInitiateChangeCallable` getter. This flag is set to `false` by the `emitInitiateChange` /// and set to `true` by the `finalizeChange` function. When the `InitiateChange` event is emitted by /// `emitInitiateChange`, the next `emitInitiateChange` call is not possible until the validator set from /// the previous call is finalized by the `finalizeChange` function. function initiateChangeAllowed() public view returns(bool) { return _finalizeValidators.list.length == 0; } /// @dev Returns a boolean flag indicating if the `initialize` function has been called. function isInitialized() public view returns(bool) { return blockRewardContract != address(0); } /// @dev Returns a boolean flag indicating whether the specified mining address is in the current validator set. /// See also the `getValidators` getter. function isValidator(address _miningAddress) public view returns(bool) { return isValidatorById[idByMiningAddress[_miningAddress]]; } /// @dev Returns a boolean flag indicating whether the specified validator (mining address) /// is able to call the `reportMalicious` function or whether the specified validator (mining address) /// can be reported as malicious. This function also allows a validator to call the `reportMalicious` /// function several blocks after ceasing to be a validator. This is possible if a /// validator did not have the opportunity to call the `reportMalicious` function prior to the /// engine calling the `finalizeChange` function. /// @param _miningAddress The validator's mining address. /// @param _reportingValidator Set to true if _miningAddress belongs to reporting validator. /// Set to false, if _miningAddress belongs to malicious validator. function isReportValidatorValid(address _miningAddress, bool _reportingValidator) public view returns(bool) { uint256 poolId; if (_reportingValidator) { poolId = idByMiningAddress[_miningAddress]; } else { poolId = hasEverBeenMiningAddress[_miningAddress]; } bool isValid = isValidatorById[poolId] && !isValidatorIdBanned(poolId); if (stakingContract.stakingEpoch() == 0 || validatorSetApplyBlock == 0) { return isValid; } if (_getCurrentBlockNumber() - validatorSetApplyBlock <= MAX_VALIDATORS) { // The current validator set was finalized by the engine, // but we should let the previous validators finish // reporting malicious validator within a few blocks bool previousValidator = _isValidatorPrevious[poolId] && !isValidatorIdBanned(poolId); return isValid || previousValidator; } return isValid; } /// @dev Returns a boolean flag indicating whether the specified mining address is currently banned. /// A validator can be banned when they misbehave (see the `_removeMaliciousValidator` internal function). /// @param _miningAddress The mining address. function isValidatorBanned(address _miningAddress) public view returns(bool) { uint256 bn = bannedUntil(_miningAddress); if (bn == 0) { // Avoid returning `true` for the genesis block return false; } return _getCurrentBlockNumber() <= bn; } /// @dev Returns a boolean flag indicating whether the specified pool id is currently banned. /// A validator can be banned when they misbehave (see the `_removeMaliciousValidator` internal function). /// @param _poolId The pool id. function isValidatorIdBanned(uint256 _poolId) public view returns(bool) { uint256 bn = _bannedUntil[_poolId]; if (bn == 0) { // Avoid returning `true` for the genesis block return false; } return _getCurrentBlockNumber() <= bn; } /// @dev Returns a boolean flag indicating whether the specified pool id is a validator /// or is in the `_pendingValidators` or `_finalizeValidators` array. /// Used by the `StakingAuRa.maxWithdrawAllowed` and `StakingAuRa.maxWithdrawOrderAllowed` getters. /// @param _poolId The pool id. function isValidatorOrPending(uint256 _poolId) public view returns(bool) { if (isValidatorById[_poolId]) { return true; } uint256 i; uint256 length; length = _finalizeValidators.list.length; for (i = 0; i < length; i++) { if (_poolId == _finalizeValidators.list[i]) { // This validator waits to be finalized, // so we treat them as `pending` return true; } } length = _pendingValidators.length; for (i = 0; i < length; i++) { if (_poolId == _pendingValidators[i]) { return true; } } return false; } /// @dev Returns whether the `reportMalicious` function can be called by the specified validator with the /// given parameters. Used by the `reportMalicious` function and `TxPermission` contract. Also, returns /// a boolean flag indicating whether the reporting validator should be removed as malicious due to /// excessive reporting during the current staking epoch. /// @param _reportingMiningAddress The mining address of the reporting validator which is calling /// the `reportMalicious` function. /// @param _maliciousMiningAddress The mining address of the malicious validator which is passed to /// the `reportMalicious` function. /// @param _blockNumber The block number which is passed to the `reportMalicious` function. /// @return `bool callable` - The boolean flag indicating whether the `reportMalicious` function can be called at /// the moment. `bool removeReportingValidator` - The boolean flag indicating whether the reporting validator /// should be removed as malicious due to excessive reporting. This flag is only used by the `reportMalicious` /// function. function reportMaliciousCallable( address _reportingMiningAddress, address _maliciousMiningAddress, uint256 _blockNumber ) public view returns(bool callable, bool removeReportingValidator) { if (!isReportValidatorValid(_reportingMiningAddress, true)) return (false, false); if (!isReportValidatorValid(_maliciousMiningAddress, false)) return (false, false); uint256 reportingId = idByMiningAddress[_reportingMiningAddress]; uint256 maliciousId = hasEverBeenMiningAddress[_maliciousMiningAddress]; uint256 validatorsNumber = _currentValidators.length; if (validatorsNumber > 1) { uint256 currentStakingEpoch = stakingContract.stakingEpoch(); uint256 reportsNumber = _reportingCounter[reportingId][currentStakingEpoch]; uint256 reportsTotalNumber = _reportingCounterTotal[currentStakingEpoch]; uint256 averageReportsNumberX10 = 0; if (reportsTotalNumber >= reportsNumber) { averageReportsNumberX10 = (reportsTotalNumber - reportsNumber) * 10 / (validatorsNumber - 1); } if (reportsNumber > validatorsNumber * 50 && reportsNumber > averageReportsNumberX10) { return (false, true); } } uint256 currentBlock = _getCurrentBlockNumber(); if (_blockNumber > currentBlock) return (false, false); // avoid reporting about future blocks uint256 ancientBlocksLimit = 100; if (currentBlock > ancientBlocksLimit && _blockNumber < currentBlock - ancientBlocksLimit) { return (false, false); // avoid reporting about ancient blocks } if (_maliceReportedForBlockMapped[maliciousId][_blockNumber][reportingId]) { // Don't allow reporting validator to report about the same misbehavior more than once return (false, false); } return (true, false); } /// @dev Only used by Ethereum client (see https://github.com/openethereum/parity-ethereum/pull/11245). /// Returns a boolean flag indicating whether the specified validator /// should report about some validator's misbehaviour at the specified block. /// @param _reportingMiningAddress The mining address of validator who reports. /// @param _maliciousMiningAddress The mining address of malicious validator. /// @param _blockNumber The block number at which the validator misbehaved. function shouldValidatorReport( address _reportingMiningAddress, address _maliciousMiningAddress, uint256 _blockNumber ) public view returns(bool) { uint256 currentBlock = _getCurrentBlockNumber(); if (_blockNumber > currentBlock + 1) { // we added +1 in the condition to let validator next to the malicious one correctly report // because that validator will use the previous block state when calling this getter return false; } if (currentBlock > 100 && currentBlock - 100 > _blockNumber) { return false; } uint256 maliciousId = hasEverBeenMiningAddress[_maliciousMiningAddress]; if (isValidatorIdBanned(maliciousId)) { // We shouldn't report of the malicious validator // as it has already been reported return false; } uint256 reportingId = idByMiningAddress[_reportingMiningAddress]; return !_maliceReportedForBlockMapped[maliciousId][_blockNumber][reportingId]; } /// @dev Returns how many times the given mining address has become a validator. function validatorCounter(address _miningAddress) public view returns(uint256) { return _validatorCounter[idByMiningAddress[_miningAddress]]; } /// @dev Returns a validator set about to be finalized by the `finalizeChange` function. /// @param miningAddresses An array set by the `emitInitiateChange` function. /// @param forNewEpoch A boolean flag indicating whether the `miningAddresses` array was formed by the /// `newValidatorSet` function. The `finalizeChange` function logic depends on this flag. function validatorsToBeFinalized() public view returns(address[] memory miningAddresses, bool forNewEpoch) { miningAddresses = new address[](_finalizeValidators.list.length); for (uint256 i = 0; i < miningAddresses.length; i++) { miningAddresses[i] = miningAddressById[_finalizeValidators.list[i]]; } return (miningAddresses, _finalizeValidators.forNewEpoch); } /// @dev Returns a validator set about to be finalized by the `finalizeChange` function. function validatorsToBeFinalizedIds() public view returns(uint256[] memory) { return _finalizeValidators.list; } // ============================================== Internal ======================================================== /// @dev Called by `finalizeChange` function to apply mining address change /// requested by a validator through `changeMiningAddress` function. function _applyMiningAddressChangeRequest() internal { // If there was a request from a validator to change their mining address uint256 poolId = miningAddressChangeRequest.poolId; if (poolId != 0) { address oldMiningAddress = miningAddressById[poolId]; address newMiningAddress = miningAddressChangeRequest.newMiningAddress; address stakingAddress = stakingAddressById[poolId]; _changeMiningAddress(oldMiningAddress, newMiningAddress, poolId, stakingAddress); } delete miningAddressChangeRequest; } /// @dev Updates mappings to change mining address of a pool. /// Used by the `changeMiningAddress` and `finalizeChange` functions. /// @param _oldMiningAddress An old mining address of the pool. /// @param _newMiningAddress A new mining address of the pool. /// @param _poolId The pool id for which the mining address is being changed. /// @param _stakingAddress The current staking address of the pool. function _changeMiningAddress( address _oldMiningAddress, address _newMiningAddress, uint256 _poolId, address _stakingAddress ) internal { idByMiningAddress[_oldMiningAddress] = 0; idByMiningAddress[_newMiningAddress] = _poolId; miningAddressById[_poolId] = _newMiningAddress; miningByStakingAddress[_stakingAddress] = _newMiningAddress; stakingByMiningAddress[_oldMiningAddress] = address(0); stakingByMiningAddress[_newMiningAddress] = _stakingAddress; hasEverBeenMiningAddress[_newMiningAddress] = _poolId; } /// @dev Updates the total reporting counter (see the `_reportingCounterTotal` mapping) for the current /// staking epoch after the specified validator is removed as malicious. The `reportMaliciousCallable` getter /// uses this counter for reporting checks so it must be up-to-date. Called by the `_removeMaliciousValidators` /// internal function. /// @param _miningAddress The mining address of the removed malicious validator. function _clearReportingCounter(address _miningAddress) internal { uint256 poolId = hasEverBeenMiningAddress[_miningAddress]; uint256 currentStakingEpoch = stakingContract.stakingEpoch(); uint256 total = _reportingCounterTotal[currentStakingEpoch]; uint256 counter = _reportingCounter[poolId][currentStakingEpoch]; _reportingCounter[poolId][currentStakingEpoch] = 0; if (total >= counter) { _reportingCounterTotal[currentStakingEpoch] -= counter; } else { _reportingCounterTotal[currentStakingEpoch] = 0; } } /// @dev Sets a new validator set stored in `_finalizeValidators.list` array. /// Called by the `finalizeChange` function. /// @param _newStakingEpoch A boolean flag defining whether the validator set was formed by the /// `newValidatorSet` function. function _finalizeNewValidators(bool _newStakingEpoch) internal { uint256[] memory validators; uint256 i; validators = _currentValidators; for (i = 0; i < validators.length; i++) { isValidatorById[validators[i]] = false; } _currentValidators = _finalizeValidators.list; validators = _currentValidators; for (i = 0; i < validators.length; i++) { uint256 poolId = validators[i]; isValidatorById[poolId] = true; if (_newStakingEpoch) { _validatorCounter[poolId]++; } } } /// @dev Marks the pending validator set as changed to be used later by the `emitInitiateChange` function. /// Called when a validator is removed from the set as malicious or when a new validator set is formed by /// the `newValidatorSet` function. /// @param _newStakingEpoch A boolean flag defining whether the pending validator set was formed by the /// `newValidatorSet` function. The `finalizeChange` function logic depends on this flag. function _setPendingValidatorsChanged(bool _newStakingEpoch) internal { _pendingValidatorsChanged = true; if (_newStakingEpoch && _pendingValidators.length != 0) { _pendingValidatorsChangedForNewEpoch = true; } changeRequestCount++; } /// @dev Marks the pending validator set as unchanged before passing it to the `InitiateChange` event /// (and then to the `finalizeChange` function). Called by the `emitInitiateChange` function. function _unsetPendingValidatorsChanged() internal returns(bool) { bool forNewEpoch = _pendingValidatorsChangedForNewEpoch; _pendingValidatorsChanged = false; _pendingValidatorsChangedForNewEpoch = false; return forNewEpoch; } /// @dev Sets pool metadata (such as name and short description). /// @param _poolId The unique ID of the pool. /// @param _name A name of the pool as UTF-8 string (256 bytes max). /// @param _description A short description of the pool as UTF-8 string (1024 bytes max). function _setPoolMetadata(uint256 _poolId, string memory _name, string memory _description) internal { require(bytes(_name).length <= 256); require(bytes(_description).length <= 1024); poolName[_poolId] = _name; poolDescription[_poolId] = _description; emit SetPoolMetadata(_poolId, _name, _description); } /// @dev Increments the reporting counter for the specified validator and the current staking epoch. /// See the `_reportingCounter` and `_reportingCounterTotal` mappings. Called by the `reportMalicious` /// function when the validator reports a misbehavior. /// @param _reportingId The pool id of reporting validator. function _incrementReportingCounter(uint256 _reportingId) internal { uint256 currentStakingEpoch = stakingContract.stakingEpoch(); _reportingCounter[_reportingId][currentStakingEpoch]++; _reportingCounterTotal[currentStakingEpoch]++; } /// @dev Removes the specified validator as malicious. Used by the `_removeMaliciousValidators` internal function. /// @param _miningAddress The removed validator mining address. /// @param _reason A short string of the reason why the mining address is treated as malicious: /// "unrevealed" - the validator didn't reveal their number at the end of staking epoch or skipped /// too many reveals during the staking epoch; /// "spam" - the validator made a lot of `reportMalicious` callings compared with other validators; /// "malicious" - the validator was reported as malicious by other validators with the `reportMalicious` function. /// @return Returns `true` if the specified validator has been removed from the pending validator set. /// Otherwise returns `false` (if the specified validator has already been removed or cannot be removed). function _removeMaliciousValidator(address _miningAddress, bytes32 _reason) internal returns(bool) { uint256 poolId = hasEverBeenMiningAddress[_miningAddress]; if (poolId == unremovableValidator) { return false; } bool isBanned = isValidatorIdBanned(poolId); // Ban the malicious validator for the next 3 months _banCounter[poolId]++; _bannedUntil[poolId] = _banUntil(); _banReason[poolId] = _reason; if (isBanned) { // The validator is already banned return false; } else { _bannedDelegatorsUntil[poolId] = _banUntil(); } // Remove the malicious validator return _removePool(poolId); } /// @dev Removes the specified validators as malicious from the pending validator set and marks the updated /// pending validator set as `changed` to be used by the `emitInitiateChange` function. Does nothing if /// the specified validators are already banned, non-removable, or don't exist in the pending validator set. /// @param _miningAddresses The mining addresses of the malicious validators. /// @param _reason A short string of the reason why the mining addresses are treated as malicious, /// see the `_removeMaliciousValidator` internal function description for possible values. function _removeMaliciousValidators(address[] memory _miningAddresses, bytes32 _reason) internal { // Temporarily turned off as all validators known /* bool removed = false; for (uint256 i = 0; i < _miningAddresses.length; i++) { if (_removeMaliciousValidator(_miningAddresses[i], _reason)) { // From this moment `getPendingValidators()` returns the new validator set _clearReportingCounter(_miningAddresses[i]); removed = true; } } if (removed) { _setPendingValidatorsChanged(false); } */ lastChangeBlock = _getCurrentBlockNumber(); } /// @dev Stores previous validators. Used by the `finalizeChange` function. function _savePreviousValidators() internal { uint256 length; uint256 i; // Save the previous validator set length = _previousValidators.length; for (i = 0; i < length; i++) { _isValidatorPrevious[_previousValidators[i]] = false; } length = _currentValidators.length; for (i = 0; i < length; i++) { _isValidatorPrevious[_currentValidators[i]] = true; } _previousValidators = _currentValidators; } /// @dev Sets a new validator set as a pending (which is not yet passed to the `InitiateChange` event). /// Called by the `newValidatorSet` function. /// @param _poolIds The array of the new validators' pool ids. function _setPendingValidators( uint256[] memory _poolIds ) internal { if (_poolIds.length == 0) { // If there are no `poolsToBeElected`, we remove the // validators which want to exit from the validator set for (uint256 i = 0; i < _pendingValidators.length; i++) { uint256 pendingValidatorId = _pendingValidators[i]; if (pendingValidatorId == unremovableValidator) { continue; // don't touch unremovable validator } if ( stakingContract.isPoolActive(pendingValidatorId) && stakingContract.orderedWithdrawAmount(pendingValidatorId, address(0)) == 0 ) { // The validator has an active pool and is not going to withdraw their // entire stake, so this validator doesn't want to exit from the validator set continue; } if (_pendingValidators.length == 1) { break; // don't remove one and only validator } // Remove the validator _pendingValidators[i] = _pendingValidators[_pendingValidators.length - 1]; _pendingValidators.length--; i--; } } else { // If there are some `poolsToBeElected`, we remove all // validators which are not in the `poolsToBeElected` or // not selected by randomness delete _pendingValidators; if (unremovableValidator != 0) { // Keep unremovable validator _pendingValidators.push(unremovableValidator); } for (uint256 i = 0; i < _poolIds.length; i++) { _pendingValidators.push(_poolIds[i]); } } } /// @dev Binds a mining address to the specified staking address and vice versa, /// generates a unique ID for the newly created pool, binds it to the mining/staking addresses, and /// returns it as a result. /// Used by the `addPool` function. See also the `miningByStakingAddress`, `stakingByMiningAddress`, /// `idByMiningAddress`, `idByStakingAddress`, `miningAddressById`, `stakingAddressById` public mappings. /// @param _miningAddress The mining address of the newly created pool. Cannot be equal to the `_stakingAddress` /// and should never be used as a pool or delegator before. /// @param _stakingAddress The staking address of the newly created pool. Cannot be equal to the `_miningAddress` /// and should never be used as a pool or delegator before. function _addPool(address _miningAddress, address _stakingAddress) internal returns(uint256) { require(miningAddressChangeRequest.poolId == 0); require(_miningAddress != address(0)); require(_stakingAddress != address(0)); require(_miningAddress != _stakingAddress); require(miningByStakingAddress[_stakingAddress] == address(0)); require(miningByStakingAddress[_miningAddress] == address(0)); require(stakingByMiningAddress[_stakingAddress] == address(0)); require(stakingByMiningAddress[_miningAddress] == address(0)); // Make sure that `_miningAddress` and `_stakingAddress` have never been a delegator before require(stakingContract.getDelegatorPoolsLength(_miningAddress) == 0); require(stakingContract.getDelegatorPoolsLength(_stakingAddress) == 0); // Make sure that `_miningAddress` and `_stakingAddress` have never been a mining address before require(hasEverBeenMiningAddress[_miningAddress] == 0); require(hasEverBeenMiningAddress[_stakingAddress] == 0); // Make sure that `_miningAddress` and `_stakingAddress` have never been a staking address before require(!hasEverBeenStakingAddress[_miningAddress]); require(!hasEverBeenStakingAddress[_stakingAddress]); uint256 poolId = ++lastPoolId; idByMiningAddress[_miningAddress] = poolId; idByStakingAddress[_stakingAddress] = poolId; miningAddressById[poolId] = _miningAddress; miningByStakingAddress[_stakingAddress] = _miningAddress; stakingAddressById[poolId] = _stakingAddress; stakingByMiningAddress[_miningAddress] = _stakingAddress; hasEverBeenMiningAddress[_miningAddress] = poolId; hasEverBeenStakingAddress[_stakingAddress] = true; return poolId; } /// @dev Removes validator pool from the list of active pools /// and from the `_pendingValidators` array. Returns `true` if the removal /// was successful, `false` - otherwise. /// @param _poolId The pool id. function _removePool(uint256 _poolId) internal returns(bool) { stakingContract.removePool(_poolId); uint256 length = _pendingValidators.length; if (length == 1) { // If the removed validator is one and only in the validator set, don't let remove them return false; } for (uint256 i = 0; i < length; i++) { if (_pendingValidators[i] == _poolId) { // Remove the malicious validator from `_pendingValidators` _pendingValidators[i] = _pendingValidators[length - 1]; _pendingValidators.length--; return true; } } return false; } /// @dev Returns the future block number until which a validator is banned. /// Used by the `_removeMaliciousValidator` internal function. function _banUntil() internal view returns(uint256) { uint256 blocksUntilEnd = stakingContract.stakingEpochEndBlock() - _getCurrentBlockNumber(); // ~90 days, at least 12 full staking epochs (for 5 seconds block) return _getCurrentBlockNumber() + 12 * stakingContract.stakingEpochDuration() + blocksUntilEnd; } /// @dev Returns the current block number. Needed mostly for unit tests. function _getCurrentBlockNumber() internal view returns(uint256) { return block.number; } /// @dev Returns an index of a pool in the `poolsToBeElected` array /// (see the `StakingAuRa.getPoolsToBeElected` public getter) /// by a random number and the corresponding probability coefficients. /// Used by the `newValidatorSet` function. /// @param _likelihood An array of probability coefficients. /// @param _likelihoodSum A sum of probability coefficients. /// @param _randomNumber A random number. function _getRandomIndex(uint256[] memory _likelihood, uint256 _likelihoodSum, uint256 _randomNumber) internal pure returns(uint256) { uint256 random = _randomNumber % _likelihoodSum; uint256 sum = 0; uint256 index = 0; while (sum <= random) { sum += _likelihood[index]; index++; } return index - 1; } }
Returns the current validator set (an array of mining addresses) which always matches the validator set kept in validator's node.
function getValidators() public view returns(address[] memory) { address[] memory miningAddresses = new address[](_currentValidators.length); for (uint256 i = 0; i < miningAddresses.length; i++) { miningAddresses[i] = miningAddressById[_currentValidators[i]]; } return miningAddresses; }
2,495,666
//SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ITheSpace.sol"; import "./ITheSpaceRegistry.sol"; contract TheSpaceRegistry is ITheSpaceRegistry, ERC721Enumerable, Ownable { /** * @dev Total possible number of ERC721 token */ uint256 private _totalSupply; /** * @dev ERC20 token used as currency */ ERC20 public immutable currency; /** * @dev Record for all tokens (tokenId => TokenRecord). */ mapping(uint256 => TokenRecord) public tokenRecord; /** * @dev Color of each token. */ mapping(uint256 => uint256) public pixelColor; /** * @dev Tax configuration of market. */ mapping(ConfigOptions => uint256) public taxConfig; /** * @dev Global state of tax and treasury. */ TreasuryRecord public treasuryRecord; /** * @dev Create Property contract, setup attached currency contract, setup tax rate. */ constructor( string memory propertyName_, string memory propertySymbol_, uint256 totalSupply_, uint256 taxRate_, uint256 treasuryShare_, uint256 mintTax_, address currencyAddress_ ) ERC721(propertyName_, propertySymbol_) { // initialize total supply _totalSupply = totalSupply_; // initialize currency contract currency = ERC20(currencyAddress_); // initialize tax config taxConfig[ConfigOptions.taxRate] = taxRate_; emit Config(ConfigOptions.taxRate, taxRate_); taxConfig[ConfigOptions.treasuryShare] = treasuryShare_; emit Config(ConfigOptions.treasuryShare, treasuryShare_); taxConfig[ConfigOptions.mintTax] = mintTax_; emit Config(ConfigOptions.mintTax, mintTax_); } ////////////////////////////// /// Getters & Setters ////////////////////////////// /** * @notice See {IERC20-totalSupply}. * @dev Always return total possible amount of supply, instead of current token in circulation. */ function totalSupply() public view override(ERC721Enumerable, IERC721Enumerable) returns (uint256) { return _totalSupply; } ////////////////////////////// /// Setters for global variables ////////////////////////////// /// @inheritdoc ITheSpaceRegistry function setTotalSupply(uint256 totalSupply_) external onlyOwner { emit TotalSupply(_totalSupply, totalSupply_); _totalSupply = totalSupply_; } /// @inheritdoc ITheSpaceRegistry function setTaxConfig(ConfigOptions option_, uint256 value_) external onlyOwner { taxConfig[option_] = value_; emit Config(option_, value_); } /// @inheritdoc ITheSpaceRegistry function setTreasuryRecord( uint256 accumulatedUBI_, uint256 accumulatedTreasury_, uint256 treasuryWithdrawn_ ) external onlyOwner { treasuryRecord = TreasuryRecord(accumulatedUBI_, accumulatedTreasury_, treasuryWithdrawn_); } /// @inheritdoc ITheSpaceRegistry function setTokenRecord( uint256 tokenId_, uint256 price_, uint256 lastTaxCollection_, uint256 ubiWithdrawn_ ) external onlyOwner { tokenRecord[tokenId_] = TokenRecord(price_, lastTaxCollection_, ubiWithdrawn_); } /// @inheritdoc ITheSpaceRegistry function setColor( uint256 tokenId_, uint256 color_, address owner_ ) external onlyOwner { pixelColor[tokenId_] = color_; emit Color(tokenId_, color_, owner_); } ////////////////////////////// /// Event emission ////////////////////////////// /// @inheritdoc ITheSpaceRegistry function emitTax( uint256 tokenId_, address taxpayer_, uint256 amount_ ) external onlyOwner { emit Tax(tokenId_, taxpayer_, amount_); } /// @inheritdoc ITheSpaceRegistry function emitPrice( uint256 tokenId_, uint256 price_, address operator_ ) external onlyOwner { emit Price(tokenId_, price_, operator_); } /// @inheritdoc ITheSpaceRegistry function emitUBI( uint256 tokenId_, address recipient_, uint256 amount_ ) external onlyOwner { emit UBI(tokenId_, recipient_, amount_); } /// @inheritdoc ITheSpaceRegistry function emitTreasury(address recipient_, uint256 amount_) external onlyOwner { emit Treasury(recipient_, amount_); } /// @inheritdoc ITheSpaceRegistry function emitDeal( uint256 tokenId_, address from_, address to_, uint256 amount_ ) external onlyOwner { emit Deal(tokenId_, from_, to_, amount_); } ////////////////////////////// /// ERC721 property related ////////////////////////////// /// @inheritdoc ITheSpaceRegistry function mint(address to_, uint256 tokenId_) external onlyOwner { if (tokenId_ > _totalSupply || tokenId_ < 1) revert InvalidTokenId(1, _totalSupply); _safeMint(to_, tokenId_); } /// @inheritdoc ITheSpaceRegistry function burn(uint256 tokenId_) external onlyOwner { _burn(tokenId_); } /// @inheritdoc ITheSpaceRegistry function safeTransferByMarket( address from_, address to_, uint256 tokenId_ ) external onlyOwner { _safeTransfer(from_, to_, tokenId_, ""); } /// @inheritdoc ITheSpaceRegistry function exists(uint256 tokenId_) external view returns (bool) { return _exists(tokenId_); } /// @inheritdoc ITheSpaceRegistry function isApprovedOrOwner(address spender_, uint256 tokenId_) external view returns (bool) { return _isApprovedOrOwner(spender_, tokenId_); } /** * @notice See {IERC721-transferFrom}. * @dev Override to collect tax and set price before transfer. */ function transferFrom( address from_, address to_, uint256 tokenId_ ) public override(ERC721, IERC721) { safeTransferFrom(from_, to_, tokenId_, ""); } /** * @notice See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from_, address to_, uint256 tokenId_, bytes memory data_ ) public override(ERC721, IERC721) { // solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved"); ITheSpace market = ITheSpace(owner()); bool success = market._beforeTransferByRegistry(tokenId_); if (success) { _safeTransfer(from_, to_, tokenId_, data_); } } /** * @notice See {IERC721-tokenURI}. */ function tokenURI(uint256 tokenId_) public view override returns (string memory uri) { ITheSpace market = ITheSpace(owner()); uri = market._tokenURI(tokenId_); } ////////////////////////////// /// ERC20 currency related ////////////////////////////// /// @inheritdoc ITheSpaceRegistry function transferCurrency(address to_, uint256 amount_) external onlyOwner { currency.transfer(to_, amount_); } /// @inheritdoc ITheSpaceRegistry function transferCurrencyFrom( address from_, address to_, uint256 amount_ ) external onlyOwner { currency.transferFrom(from_, to_, amount_); } }
@inheritdoc ITheSpaceRegistry
function setTokenRecord( uint256 tokenId_, uint256 price_, uint256 lastTaxCollection_, uint256 ubiWithdrawn_ ) external onlyOwner { tokenRecord[tokenId_] = TokenRecord(price_, lastTaxCollection_, ubiWithdrawn_); }
12,728,646
pragma solidity ^0.4.17; contract CampaignFactory { address[] public deployedCampaigns; function createCampaign(uint minimumContribution) public { // deploy a new Campaign contract // msg.sender for Campaign will be this // factory contract, therefore we need to // pass the sender address to Campaign contract address newCampaign = new Campaign(minimumContribution, msg.sender); // add to deployedCampaigns list deployedCampaigns.push(newCampaign); } function getDeployedCampaigns() public view returns (address[]) { return deployedCampaigns; } } contract Campaign { struct Request { string description; uint value; address recipient; bool complete; uint approvalCount; mapping(address => bool) approvals; } Request[] public requests; address public manager; uint public minimumContribution; mapping(address => bool) public approvers; uint public approversCount; constructor(uint minimum, address creator) public { manager = creator; minimumContribution = minimum; } modifier restricted() { require(msg.sender == manager); _; } // mark the function as payable as // user needs to pay to contribute function contribute() public payable { // check if money contributed // is greater than minimum minimumContribution require(msg.value >= minimumContribution); // change status of approver address in // mapping approvers[msg.sender] = true; approversCount++; } // Create a request function // only to be called by the manager function createRequest(string description, uint value, address recipient) public restricted { // canot use storage keyword // We just need to initialize value properties // mapping is a reference property // therefore no need to initialize Request memory newRequest = Request({ description: description, value: value, recipient: recipient, complete: false, approvalCount: 0 }); requests.push(newRequest); } // approve request function approveRequest(uint index) public { // create a storage local variable Request storage request = requests[index]; // check if person has contributed require(approvers[msg.sender]); // check if the sender has not approved before // sender has not voted before for this request require(!request.approvals[msg.sender]); // add to voted list request.approvals[msg.sender] = true; // increment approvalCount for this request request.approvalCount++; } // Only manager can call this. // This will allocate money to the owner of the request function finalizeRequest(uint index) public restricted { // create a storage local variable Request storage request = requests[index]; // check if votes are more than 50% require(request.approvalCount > (approversCount / 2)); // check if request has been already completed require(!request.complete); // transfer requested value request.recipient.transfer(request.value); // set request as complete request.complete = true; } // get summary about the campaign function getSummary() public view returns ( uint, uint, uint, uint, address ) { return ( minimumContribution, this.balance, requests.length, approversCount, manager ); } // get the count of the requests function getRequestsCount() public view returns (uint) { return requests.length; } }
Create a request function only to be called by the manager canot use storage keyword We just need to initialize value properties mapping is a reference property therefore no need to initialize
function createRequest(string description, uint value, address recipient) public restricted { Request memory newRequest = Request({ description: description, value: value, recipient: recipient, complete: false, approvalCount: 0 }); requests.push(newRequest); }
13,116,129
./full_match/80001/0xB5E7bb79bCFd916b319b3320C63B98e617BFd023/sources/project_/contracts/LockUps.sol
Updates the lockUps of the `_account` according to timestamps. If the time to unlock certain amount of tokens has come, it makes these tokens "free". Function loops through the array of pairs with data about locked tokens: {PersonalInfo.personalLockUps} If the [0]indexed parametr of pair (timestamp to unlock) is less then current timestamp - {block.timestamp} => it will be deleted from the array and the [1]indexed amount of tokens will be unlocked in such a way and Event {UnlockTokens} emits. Otherwise - this pair is passed and tokens stay locked. _account address to update its LockUps return true if function passed successfully
function updateDataOfLockedTokensOf( address _account ) public returns (bool) { if (userData[_account].personalLockUps.length == 0) { return true; uint count = 0; uint256[2][] memory memoryArray = new uint256[2][]( userData[_account].personalLockUps.length ); for (uint256 i = 0; i < memoryArray.length; i++) { if ( userData[_account].personalLockUps[i][0] <= block.timestamp ) { emit UnlockTokens( _account, block.timestamp, userData[_account].personalLockUps[i][1] ); memoryArray[i] = userData[_account].personalLockUps[i]; count++; } } uint256[2][] memory finalArray = new uint256[2][](count); uint k = 0; for (uint256 i = 0; i < memoryArray.length; i++) { if (memoryArray[i][0] > 0) { finalArray[k] = memoryArray[i]; k++; } } userData[_account].personalLockUps = finalArray; return true; } }
842,575
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './ERC721Enumerable.sol'; import './Strings.sol'; import './INiftyNafty.sol'; import './INiftyNaftyMetadata.sol'; contract NiftyNafty is ERC721Enumerable, INiftyNafty, INiftyNaftyMetadata { using Strings for uint256; uint256 private constant startIDFrom=1;// The initial token ID uint256 public constant COUNT_PRESALE = 250; uint256 public constant PUBLIC_MAX = 8999; uint256 public constant GIFT_MAX = 1000; uint256 public constant PURCHASE_LIMIT = 3; uint256 public saleMode = 0;//0-none, 1-presale, 2-public uint256 public PRICE_PRESALE = 0.05 ether; uint256 public PRICE_WHITE = 0.07 ether; uint256 public PRICE = 0.08 ether; bool public isActive = true; bool public isAllowListActive = false; string public proof; uint256 public allowListMaxMint = 3; uint256 public totalGiftSupply; uint256 public totalPublicSupply; uint256 public startDate; address[] internal _ownersList; mapping(address => bool) private _allowList; mapping(address => uint256) private _claimed; string private _contractURI = ''; string private _tokenBaseURI = ''; string private _tokenRevealedBaseURI = ''; //---------------------------------------------------------------------------------------------------------------new // Used for random index assignment mapping(uint256 => uint256) private tokenMatrix; address public addressDAO; uint256 public constant DAO_PERCENT = 55;// 1/1000 uint256 private _allBalance; uint256 private _sentDAO; bytes32 public lastOperation; address public lastOwner; bool public revealed = false; string public notRevealedUri; constructor(string memory name, string memory symbol) ERC721(name, symbol) { _ownersList.push(_msgSender()); } function updateOwnersList(address[] calldata addresses) external override onlyTwoOwners { _ownersList = addresses; } function onOwnersList(address addr) external view override returns (bool) { for(uint i = 0; i < _ownersList.length; i++) { if (_ownersList[i] == addr) { return true; } } return false; } function addToAllowList(address[] calldata addresses) external override onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Can't add the null address"); _allowList[addresses[i]] = true; _claimed[addresses[i]] > 0 ? _claimed[addresses[i]] : 0; } } function onAllowList(address addr) external view override returns (bool) { return _allowList[addr]; } function removeFromAllowList(address[] calldata addresses) external override onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Can't add the null address"); _allowList[addresses[i]] = false; } } function setPricePreSale(uint256 newPrice) external onlyOwner { PRICE_PRESALE = newPrice; } function setPriceWhite(uint256 newPrice) external onlyOwner { PRICE_WHITE = newPrice; } function setPrice(uint256 newPrice) external override onlyOwner { PRICE = newPrice; } function setStartDate(uint256 newDate) external override onlyOwner { startDate = newDate; } function claimedBy(address addr) external view override returns (uint256){ require(addr != address(0), "Can't check the null address"); return _claimed[addr]; } function purchase(uint256 numberOfTokens) external override payable { require(block.timestamp > startDate, 'Sale not started'); require(isActive, 'Contract is not active'); require(saleMode>0, 'The sale mode is not enabled'); require(numberOfTokens <= PURCHASE_LIMIT, 'Would exceed PURCHASE_LIMIT'); if (isAllowListActive) { require(_allowList[msg.sender], 'You are not on the Allow List'); } //Mechanics of price selection uint256 Price=PRICE; if (saleMode == 1) { Price=PRICE_PRESALE; } else if(_allowList[msg.sender]){ Price=PRICE_WHITE; } //optimistic set uint256 tokenCount=totalPublicSupply; _allBalance += msg.value; _claimed[msg.sender] += numberOfTokens; totalPublicSupply += numberOfTokens; //Mechanics of determining the end of the pre sale if (saleMode == 1) { require(totalPublicSupply <= COUNT_PRESALE, 'All PRESALE tokens have been minted'); if(totalPublicSupply >= COUNT_PRESALE) saleMode=0; } require(_claimed[msg.sender] <= allowListMaxMint, 'Purchase exceeds max allowed'); require(totalPublicSupply <= PUBLIC_MAX, 'Purchase would exceed PUBLIC_MAX'); require(Price * numberOfTokens <= msg.value, 'ETH amount is not sufficient'); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = nextToken(tokenCount); tokenCount+=1; _safeMint(msg.sender, tokenId); } } function gift(address[] calldata to) external override onlyTwoOwners { require(totalGiftSupply + to.length <= GIFT_MAX, 'Not enough tokens left to gift'); uint256 tokenCount=totalGiftSupply; totalGiftSupply += to.length; for(uint256 i = 0; i < to.length; i++) { uint256 tokenId = tokenCount + PUBLIC_MAX + 1 + i; _safeMint(to[i], tokenId); } } function setIsActive(bool _isActive) external override onlyOwner { isActive = _isActive; } function setIsAllowListActive(bool _isAllowListActive) external override onlyOwner { isAllowListActive = _isAllowListActive; } function setSaleMode(uint256 _Mode) external onlyOwner { saleMode = _Mode; } function setAllowListMaxMint(uint256 maxMint) external override onlyOwner { allowListMaxMint = maxMint; } function setProof(string calldata proofString) external override onlyOwner { proof = proofString; } function withdraw() external override onlyTwoOwners { require(_ownersList.length > 0, "Can't withdraw where owners list empty"); int256 balance=int256(address(this).balance)-int256(getProfitDAO()); require(balance>0, "Can't withdraw - no funds available"); uint256 part = uint256(balance) / _ownersList.length; if(part>0) { for(uint256 i = 0; i < _ownersList.length; i++) { payable(_ownersList[i]).transfer(part); } } } function setContractURI(string calldata URI) external override onlyOwner { _contractURI = URI; } function setBaseURI(string calldata URI) external override onlyOwner { _tokenBaseURI = URI; } function setRevealedBaseURI(string calldata revealedBaseURI) external override onlyOwner { _tokenRevealedBaseURI = revealedBaseURI; } function contractURI() public view override returns (string memory) { return _contractURI; } function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) { require(_exists(tokenId), 'Token does not exist'); if(revealed == false) { return notRevealedUri; } string memory revealedBaseURI = _tokenRevealedBaseURI; return bytes(revealedBaseURI).length > 0 ? string(abi.encodePacked(revealedBaseURI, tokenId.toString(), '.json')) : _tokenBaseURI; } function reveal() public onlyOwner { revealed = true; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } //---------------------------------------------------------------------------------------------------------------new function setDAO(address setAddress) external onlyOwner { require(setAddress != address(0), "Can't check the null address"); addressDAO = setAddress; } function withdrawDAO() external onlyTwoOwners { uint256 ProfitDAO=getProfitDAO(); require(ProfitDAO>0, "Can't withdraw - no funds available"); require(addressDAO!= address(0), "Can't withdraw - DAO not set"); (bool success,) = payable(addressDAO).call{value:ProfitDAO, gas: 100000}(""); if(success) { _sentDAO += ProfitDAO; } } function getProfitDAO() public view returns (uint256 ProfitDAO) { int256 Balance = int256(_allBalance * DAO_PERCENT/1000) - int256(_sentDAO); if(Balance>0) ProfitDAO=uint256(Balance); else ProfitDAO=0; } /// Get the next token ID /// @dev Randomly gets a new token ID and keeps track of the ones that are still available. /// @return the next token ID function nextToken(uint256 tokenCount) internal returns (uint256) { uint256 maxIndex = PUBLIC_MAX - tokenCount; uint256 random = uint256(keccak256( abi.encodePacked( msg.sender, block.coinbase, block.difficulty, block.gaslimit, block.timestamp ) )) % maxIndex; uint256 value = 0; if (tokenMatrix[random] == 0) { // If this matrix position is empty, set the value to the generated random number. value = random; } else { // Otherwise, use the previously stored number from the matrix. value = tokenMatrix[random]; } // If the last available tokenID is still unused... if (tokenMatrix[maxIndex - 1] == 0) { // ...store that ID in the current matrix position. tokenMatrix[random] = maxIndex - 1; } else { // ...otherwise copy over the stored number to the current matrix position. tokenMatrix[random] = tokenMatrix[maxIndex - 1]; } return value + startIDFrom; } //---------------------------------------------------------------------------------------------------------MultSig 2/N // MODIFIERS /** * @dev Allows to perform method by any of the owners */ modifier onlyOwner { require(isOwner(), "onlyOwner: caller is not the owner"); _; } /** * @dev Allows to perform method only after many owners call it with the same arguments */ modifier onlyTwoOwners { require(isOwner(), "onlyTwoOwners: caller is not the owner"); bytes32 operation = keccak256(msg.data); if(_ownersList.length == 1 || (lastOperation == operation && lastOwner != msg.sender)) { resetVote(); _; } else if(lastOperation != operation || lastOwner == msg.sender) { //new vote lastOperation = operation; lastOwner = msg.sender; } } /** * @dev Returns the address of the current owner */ function owner() public view virtual returns (address) { return _ownersList[0]; } /** * @dev Returns a list of owners addresses */ function owners() public view virtual returns (address [] memory) { return _ownersList; } function isOwner()internal view returns(bool) { for(uint256 i = 0; i < _ownersList.length; i++) { if(_ownersList[i]==msg.sender) { return true; } } return false; } function resetVote()internal{ lastOperation=0; lastOwner=address(0); } /** * @dev Allows owners to change their mind by cacnelling vote operations */ function cancelVote() public onlyOwner { resetVote(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @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(); } } // SPDX-License-Identifier: MIT 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); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INiftyNafty { function updateOwnersList(address[] calldata addresses) external; function onOwnersList(address addr) external returns (bool); function addToAllowList(address[] calldata addresses) external; function onAllowList(address addr) external returns (bool); function removeFromAllowList(address[] calldata addresses) external; function claimedBy(address owner) external returns (uint256); function purchase(uint256 numberOfTokens) external payable; function gift(address[] calldata to) external; function setIsActive(bool isActive) external; function setPrice(uint256 newPrice) external; //function setMaxTotalSupply(uint256 newCount) external; function setStartDate(uint256 newDate) external; function setIsAllowListActive(bool isAllowListActive) external; function setAllowListMaxMint(uint256 maxMint) external; function setProof(string memory proofString) external; function withdraw() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INiftyNaftyMetadata { function setContractURI(string calldata URI) external; function setBaseURI(string calldata URI) external; function setRevealedBaseURI(string calldata revealedBaseURI) external; function contractURI() external view returns(string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./IERC721Metadata.sol"; import "./Address.sol"; import "./Context.sol"; import "./Strings.sol"; import "./ERC165.sol"; /** * @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) internal _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 { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_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); } /** * @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); } /** * @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 of token that is not own"); 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); } /** * @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 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(to).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 {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @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 tokenId); /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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 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 pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @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); } // 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; /* * @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 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.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); }
Returns a list of owners addresses/
function owners() public view virtual returns (address [] memory) { return _ownersList; }
14,813,830
./full_match/1/0x8abC21a84992b8C50c086D5133D6B428b8FC7439/sources/contracts/KH87A/PixelPioneerArtworkBase.sol
Get the Art Asset for a TokenType as an SVG encoded into a data URI. tokenType the token type of the art piece./
function getSvgArt(uint256 tokenType) external view returns (string memory) { return _getSvgDataURI(tokenType); }
4,954,282
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.9; import { IERC20 } from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import { IClearingHouse } from '../../interfaces/IClearingHouse.sol'; import { IClearingHouseView } from '../../interfaces/clearinghouse/IClearingHouseView.sol'; import { IVQuote } from '../../interfaces/IVQuote.sol'; import { IVToken } from '../../interfaces/IVToken.sol'; import { Account } from '../../libraries/Account.sol'; import { AddressHelper } from '../../libraries/AddressHelper.sol'; import { Protocol } from '../../libraries/Protocol.sol'; import { ClearingHouseStorage } from './ClearingHouseStorage.sol'; import { Extsload } from '../../utils/Extsload.sol'; abstract contract ClearingHouseView is IClearingHouse, ClearingHouseStorage, Extsload { using Account for Account.Info; using AddressHelper for address; using AddressHelper for IVToken; using Protocol for Protocol.Info; /// @inheritdoc IClearingHouseView function getAccountInfo(uint256 accountId) public view returns ( address owner, int256 vQuoteBalance, CollateralDepositView[] memory collateralDeposits, VTokenPositionView[] memory tokenPositions ) { return accounts[accountId].getInfo(protocol); } /// @inheritdoc IClearingHouseView function getAccountMarketValueAndRequiredMargin(uint256 accountId, bool isInitialMargin) public view returns (int256 marketValue, int256 requiredMargin) { (marketValue, requiredMargin) = accounts[accountId].getAccountValueAndRequiredMargin(isInitialMargin, protocol); } /// @inheritdoc IClearingHouseView function getAccountNetProfit(uint256 accountId) public view returns (int256 accountNetProfit) { accountNetProfit = accounts[accountId].getAccountPositionProfits(protocol); } /// @inheritdoc IClearingHouseView function getAccountNetTokenPosition(uint256 accountId, uint32 poolId) public view returns (int256 netPosition) { return accounts[accountId].getNetPosition(poolId, protocol); } /// @inheritdoc IClearingHouseView function getCollateralInfo(uint32 collateralId) public view returns (Collateral memory) { return protocol.collaterals[collateralId]; } /// @inheritdoc IClearingHouseView function getPoolInfo(uint32 poolId) public view returns (Pool memory) { return protocol.pools[poolId]; } /// @inheritdoc IClearingHouseView function getProtocolInfo() public view returns ( IERC20 settlementToken, IVQuote vQuote, LiquidationParams memory liquidationParams, uint256 minRequiredMargin, uint256 removeLimitOrderFee, uint256 minimumOrderNotional ) { settlementToken = protocol.settlementToken; vQuote = protocol.vQuote; liquidationParams = protocol.liquidationParams; minRequiredMargin = protocol.minRequiredMargin; removeLimitOrderFee = protocol.removeLimitOrderFee; minimumOrderNotional = protocol.minimumOrderNotional; } /// @inheritdoc IClearingHouseView function getRealTwapPriceX128(uint32 poolId) public view returns (uint256 realPriceX128) { realPriceX128 = protocol.getRealTwapPriceX128(poolId); } /// @inheritdoc IClearingHouseView function getVirtualTwapPriceX128(uint32 poolId) public view returns (uint256 virtualPriceX128) { virtualPriceX128 = protocol.getVirtualTwapPriceX128(poolId); } /// @inheritdoc IClearingHouseView function isPoolIdAvailable(uint32 poolId) external view returns (bool) { return protocol.pools[poolId].vToken.isZero(); } }
@inheritdoc IClearingHouseView
function getRealTwapPriceX128(uint32 poolId) public view returns (uint256 realPriceX128) { realPriceX128 = protocol.getRealTwapPriceX128(poolId); }
13,068,421
./full_match/1/0x4361b1B8aE2E4f96bFB7A2BC95D6aB748882fdbB/sources/src/FiefdomProxy.sol
Defer all functionality to the given archetype contract Invoke the preInitialize function on itself, as defined by the archetype contract
constructor() { address fiefdomArchetype = Fiefdoms(msg.sender).fiefdomArchetype(); uint256 fiefdomId = Fiefdoms(msg.sender).totalSupply(); getAddressSlot(_IMPLEMENTATION_SLOT).value = fiefdomArchetype; Address.functionDelegateCall( fiefdomArchetype, abi.encodeWithSignature("initialize(address,uint256)", msg.sender, fiefdomId), "Address: low-level delegate call failed" ); }
4,962,773
./partial_match/1/0xAE99862CB922CF20F341f4292af82cf673DF0dB6/sources/FeeDistributor.sol
Withdraws the specified tokens or ETH tokens Array of tokens to withdraw tokens Array of amounts to withdraw for each token/
function withdraw(IERC20[] calldata tokens) external { for (uint256 i = 0; i < tokens.length; i++) { IERC20 token = tokens[i]; uint256 amount = available(token, msg.sender); _withdrawn[token][msg.sender] += amount; _totalWithdrawn[token] += amount; _transfer(token, amount); } emit Withdrawal(tokens, msg.sender); }
15,718,441
./full_match/56/0xa83B3E821F6CF63Cde35c9aC7012c00bF57a438D/sources/contracts/NewAlver.sol
Get total fee's or multiplication of fees
function getTotalFee(bool selling) public view returns (uint256) { return totalFee; }
3,245,846
// SPDX-License-Identifier: MIT // _____ _____ _______ _____ _____ _____ // /\ \ /\ \ /::\ \ /\ \ /\ \ /\ \ // /::\ \ /::\ \ /::::\ \ /::\____\ /::\ \ /::\____\ // /::::\ \ \:::\ \ /::::::\ \ /:::/ / /::::\ \ /::::| | // /::::::\ \ \:::\ \ /::::::::\ \ /:::/ / /::::::\ \ /:::::| | // /:::/\:::\ \ \:::\ \ /:::/~~\:::\ \ /:::/ / /:::/\:::\ \ /::::::| | // /:::/__\:::\ \ \:::\ \ /:::/ \:::\ \ /:::/ / /:::/__\:::\ \ /:::/|::| | // \:::\ \:::\ \ /::::\ \ /:::/ / \:::\ \ /:::/ / /::::\ \:::\ \ /:::/ |::| | // ___\:::\ \:::\ \ /::::::\ \ /:::/____/ \:::\____\ /:::/ / /::::::\ \:::\ \ /:::/ |::| | _____ // /\ \:::\ \:::\ \ /:::/\:::\ \ |:::| | |:::| | /:::/ / /:::/\:::\ \:::\ \ /:::/ |::| |/\ \ ///::\ \:::\ \:::\____\ /:::/ \:::\____\|:::|____| |:::| |/:::/____/ /:::/__\:::\ \:::\____\/:: / |::| /::\____\ //\:::\ \:::\ \::/ / /:::/ \::/ / \:::\ \ /:::/ / \:::\ \ \:::\ \:::\ \::/ /\::/ /|::| /:::/ / // \:::\ \:::\ \/____/ /:::/ / \/____/ \:::\ \ /:::/ / \:::\ \ \:::\ \:::\ \/____/ \/____/ |::| /:::/ / // \:::\ \:::\ \ /:::/ / \:::\ /:::/ / \:::\ \ \:::\ \:::\ \ |::|/:::/ / // \:::\ \:::\____\ /:::/ / \:::\__/:::/ / \:::\ \ \:::\ \:::\____\ |::::::/ / // \:::\ /:::/ / \::/ / \::::::::/ / \:::\ \ \:::\ \::/ / |:::::/ / // \:::\/:::/ / \/____/ \::::::/ / \:::\ \ \:::\ \/____/ |::::/ / // \::::::/ / \::::/ / \:::\ \ \:::\ \ /:::/ / // \::::/ / \::/____/ \:::\____\ \:::\____\ /:::/ / // \::/ / ~~ \::/ / \::/ / \::/ / // \/____/ \/____/ \/____/ \/____/ pragma solidity ^0.8.0; library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } 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" ); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } 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" ); } 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); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } 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); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } 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); } } } } abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { _setOwner(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } 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); } } interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } interface IERC721 is IERC165 { event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } abstract contract ERC165 is IERC165 { function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } interface ITheStolenGenerator { struct FactionImage{ bool fillFaction; bool fillOwner; bool fillHighscore; uint16 member; string factionName; address owner; uint256 highscore; uint256 factionSteals; uint256 steals; uint256 current; } function factionTokenURI(FactionImage memory tokenData) external view returns (string memory); function flagTokenURI(string memory factionName, uint current) external view returns (string memory); } contract TheStolen is Ownable, ERC165, IERC721, IERC721Metadata, ReentrancyGuard { using Address for address; //Image Generator ITheStolenGenerator stolenImage; //FactionToken Ownership struct FactionToken { address owner; uint16 factionId; bytes1 isRogue; bytes1 isBurned; } //Flag Ownership struct Flag { address owner; uint16 factionId; bytes1 vulnerable; bytes1 withoutFaction; } //Address ID Data struct AddressID { uint16 factionId; uint16 factionTokenId; uint16 factionLastTokenId; uint8 factionBalance; bytes1 hasMinted; } //Address Data struct AddressData { bytes1 hasRogue; bytes1 hasFlag; bytes1 withoutFaction; uint16 rogueId; uint256 stolen; uint256 switchedFaction; } //Faction ID Data struct FactionID { uint16 factionId; uint16 memberCount; string name; } //Faction Data struct FactionData { uint256 stolen; uint256 currentHoldtime; uint256 highscore; } //Faction Name ID struct FactionNameId { uint16 factionId; address contractAddress; } uint256 private _mintStarttime = 1; uint256 private _mintTime = 1; bytes1 private _locked = 0x00; bytes1 private _open = 0x00; uint16 private _currentIndex = 1; uint16 private _burnedCount = 0; uint16 private _currentFactionIndex = 1; uint256 private _flagLastTransferTime = 1; uint16 private _currentFactionHolding; uint16 private _currentLeader; uint256 private _currentLongestHoldtime; uint16 internal immutable _flagStealTime; uint16 internal immutable _flagFastStealTime; uint16 internal immutable collectionSize; uint8 internal immutable maxBatchSize; uint16 internal constant _freeMintCount = 1000; uint256 internal immutable mintPrice; uint256 internal flagPrice; // Token name string private _name; // Token symbol string private _symbol; //THE FLAG Flag private _flag; // Mapping from token ID to ownership mapping(uint16 => FactionToken) private _factionOwnerships; // Mapping owner address to address ID and data mapping(address => AddressID) private _addressIDs; mapping(address => AddressData) private _addressData; // Mapping from factionId to faction ID and data mapping(uint16 => FactionID) private _factionIDs; mapping(uint16 => FactionData) private _factionData; // Mapping from factionName to faction name ID mapping(string => FactionNameId) private _factionNameId; // Mapping from token ID to approved address mapping(uint16 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; event GotStolen(address from, address to); event GotFlag(address from, address to); event MintedFlag(address to); event NewLeader(uint16 prevLeader, uint16 newLeader); event NewFactionHolding(uint16 newHolding); event Merge(address owner, uint256 oldTokenId); constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require(collectionSize_ > 0, "collection must have a nonzero supply"); require(maxBatchSize_ > 0, "max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = uint8(maxBatchSize_ + 1); collectionSize = uint16(collectionSize_ + 1); mintPrice = 0.03 ether; flagPrice = 0.00 ether; _mintTime = 604800; _flagStealTime = 21600; _flagFastStealTime = 600; string[10] memory rfn = [ "AZUKI", "DOODLES", "PUNKS", "COOLMANSUNIVERSE", "COOLCATS", "MFERS", "FLUF", "WORLDOFWOMEN", "DYSTOAPEZ", "CRYPTOMORIES" ]; address[10] memory rfa = [ 0xED5AF388653567Af2F388E6224dC7C4b3241C544, 0x8a90CAb2b38dba80c64b7734e58Ee1dB38B8992e, 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB, 0xa5C0Bd78D1667c13BFB403E2a3336871396713c5, 0x1A92f7381B9F03921564a437210bB9396471050C, 0x79FCDEF22feeD20eDDacbB2587640e45491b757f, 0xCcc441ac31f02cD96C153DB6fd5Fe0a2F4e6A68d, 0xe785E82358879F061BC3dcAC6f0444462D4b5330, 0x648E8428e0104Ec7D08667866a3568a72Fe3898F, 0x1a2F71468F656E97c2F86541E57189F59951efe7 ]; FactionID memory faction = FactionID(_currentFactionIndex - 1, 0, ""); uint16 maxIndex = uint16(_currentFactionIndex+rfn.length); for(uint i = 0; i < rfn.length; i++){ faction.name = rfn[i]; faction.factionId++; _factionNameId[rfn[i]] = FactionNameId(faction.factionId, rfa[i]); _factionIDs[faction.factionId] = faction; } _currentFactionIndex = maxIndex; } //Set the Contract for image generation if mint not started and not locked function setImageContract(address imageContract) private { require(_open != 0x01 && _locked != 0x01, "The Stolen: contract open or locked"); stolenImage = ITheStolenGenerator(imageContract); } /////////////////////////////////////////////////// // MODIFIER modifier isOpen() { require(_open == 0x01, "The Stolen: mint not open."); _; } modifier unlocked(uint8 quantity) { require( _locked != 0x01 && _currentIndex + quantity < collectionSize + 1 && block.timestamp < _mintStarttime + _mintTime, "The Stolen: faction mint locked" ); _; } modifier locked() { require( (_mintStarttime > 1 && block.timestamp > _mintStarttime + _mintTime) || _locked == 0x01 || _currentIndex == collectionSize - 1 , "The Stolen: flag mint locked" ); _; } // MODIFIER /////////////////////////////////////////////////// /////////////////////////////////////////////////// // PUBLIC VIEW function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { bytes4 _ERC165_ = 0x01ffc9a7; bytes4 _ERC721_ = 0x80ac58cd; bytes4 _ERC721Metadata_ = 0x5b5e139f; return interfaceId == _ERC165_ || interfaceId == _ERC721_ || interfaceId == _ERC721Metadata_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function totalSupply() public view returns (uint256) { return (_currentIndex - _burnedCount); } function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "The Stolen: balance query for the zero address"); return uint256(_addressIDs[owner].factionBalance); } function ownerOf(uint256 tokenId) public view override returns (address) { require(_existed(uint16(tokenId)), "The Stolen: nonexistent token"); if (tokenId == 0) { if (flagReleased()) { return _flag.owner; } } return _ownershipOf(uint16(tokenId)).owner; } function exists(uint16 tokenId) public view returns (bool) { return _existed(tokenId) && !_burned(tokenId); } function burned(uint16 tokenId) public view returns (bool) { return _burned(tokenId); } /////////////////////////////////////////////////// function freeMintLeft() public view returns (uint16) { require(_freeMintCount - (_currentIndex-1) > 0, "The Stolen: 1000 free mints reached."); return _freeMintCount - (_currentIndex-1); } function factionMintCost() public view returns (uint256) { return mintPrice; } function flagReleased() public view returns (bool) { return (_locked == 0x01 || _currentIndex == collectionSize || (_mintStarttime > 1 && block.timestamp > _mintStarttime + _mintTime)); } function flagMintPrice() public view returns (uint256) { return (flagPrice * 11)/10; } /////////////////////////////////////////////////// function getAddressData(address a) public view returns (AddressID memory, AddressData memory) { return (_addressIDs[a], _addressData[a]); } function getFactionData(uint16 factionId) public view returns (FactionID memory id, FactionData memory data, FactionNameId memory nameId) { require(factionId < _currentFactionIndex, "The Stolen: faction doesnt exist"); id = _factionIDs[factionId]; data = _factionData[factionId]; nameId = _factionNameId[id.name]; } function getTokenData(uint16 tokenId) public view returns (FactionToken memory) { require(_existed(tokenId), "The Stolen: token doesnt exist"); return _factionOwnerships[tokenId]; } function getHolderFactionId() public view returns (uint16) { require( _flag.owner != address(0) && _flag.factionId > 0, "The Stolen: no faction owns the flag right now." ); return _flag.factionId; } function getLeaderHoldtime() public view returns (uint256) { require(_flagLastTransferTime != 1, "The Stolen: no scores yet"); Flag memory flag = _flag; uint256 currentHolderHoldtime = _factionData[flag.factionId] .currentHoldtime + (block.timestamp - _flagLastTransferTime); if(flag.factionId == 0){ currentHolderHoldtime = 0; } uint256 currentLongestHoldtime = _currentLongestHoldtime; if ( flag.factionId != _currentLeader && currentLongestHoldtime > currentHolderHoldtime ) { return currentLongestHoldtime; } else { require(flag.factionId > 0, "The Stolen: Flag factionless."); return currentHolderHoldtime; } } function getLeaderName() public view returns (string memory) { require(_flagLastTransferTime != 1, "The Stolen: no scores yet"); Flag memory flag = _flag; uint16 currentLeader = _currentLeader; uint256 currentHolderHoldtime = _factionData[flag.factionId] .currentHoldtime + (block.timestamp - _flagLastTransferTime); if(flag.factionId == 0){ currentHolderHoldtime = 0; } if ( flag.factionId != currentLeader && _currentLongestHoldtime > currentHolderHoldtime ) { return _factionIDs[currentLeader].name; } else { require(flag.factionId > 0, "The Stolen: Flag factionless."); return _factionIDs[flag.factionId].name; } } function getCurrentHoldtime() public view returns (uint256) { uint16 holderId = _flag.factionId; if (_flagLastTransferTime == 1 || _flag.withoutFaction == 0x01) { return 0; } return _factionData[holderId].currentHoldtime + (block.timestamp - _flagLastTransferTime); } function validateFactionName(string memory message) public pure returns (bool) { bytes memory messageBytes = bytes(message); // Max length 16, A-Z only require( messageBytes.length > 2 && messageBytes.length < 17, "The Stolen: faction name length unfit" ); require( messageBytes[0] != 0x20 && messageBytes[messageBytes.length - 1] != 0x20, "The Stolen: Invalid characters" ); for (uint256 i = 0; i < messageBytes.length; i++) { bytes1 char = messageBytes[i]; if (!(char >= 0x41 && char <= 0x5A) || char == 0x20) { revert("The Stolen: Invalid character"); } } return true; } function flagVulnerable() public view returns (bool) { uint256 lastTransfer = _flagLastTransferTime; return (_flag.vulnerable == 0x01 && lastTransfer + _flagFastStealTime > block.timestamp) || (lastTransfer > 1 && lastTransfer + _flagStealTime < block.timestamp); } // PUBLIC VIEW /////////////////////////////////////////////////// /////////////////////////////////////////////////// // INTERNAL VIEW function _ownershipOf(uint16 tokenId, uint16 lowestToCheck) internal view returns (FactionToken memory) { FactionToken memory ft = _factionOwnerships[tokenId]; lowestToCheck--; for (uint16 curr = tokenId; curr > lowestToCheck; curr--) { ft = _factionOwnerships[curr]; if (ft.isBurned != 0x01 && ft.owner != address(0)) { return ft; } } revert("The Stolen: unable to determine the owner of token"); } function _ownershipOf(uint16 tokenId) internal view returns (FactionToken memory) { FactionToken memory ft = _factionOwnerships[tokenId]; if(ft.isBurned == 0x01){ return ft; } uint16 lowestToCheck; if (tokenId >= maxBatchSize) { lowestToCheck = tokenId - maxBatchSize + 1; } for (uint16 curr = tokenId; curr > lowestToCheck; curr--) { ft = _factionOwnerships[curr]; if (curr > 0 && ft.isBurned != 0x01 && ft.owner != address(0)) { return ft; } } revert("The Stolen: unable to determine the owner of token"); } function _existed(uint16 tokenId) internal view returns (bool) { if (tokenId == 0) { return _flag.owner != address(0); } else { return tokenId < _currentIndex; } } function _burned(uint16 tokenId) internal view returns (bool) { if (tokenId == 0) { return _flag.owner == address(0); } return _factionOwnerships[tokenId].isBurned == 0x01 ? true : false; } // INTERNAL VIEW /////////////////////////////////////////////////// /////////////////////////////////////////////////// // APPROVAL function approve(address to, uint256 tokenId) public override { address owner = ownerOf(tokenId); require(to != owner, "The Stolen: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "The Stolen: approve caller is not owner nor approved for all" ); _approve(owner, to, uint16(tokenId)); } function _approve( address owner, address to, uint16 tokenId ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } function getApproved(uint256 tokenId) public view override returns (address) { uint16 tId = uint16(tokenId); require(_existed(tId), "The Stolen: approved query for nonexistent token"); return _tokenApprovals[tId]; } function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "The Stolen: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function _isApprovedOrOwner(address spender, uint16 tokenId) internal view virtual returns (address owner, bool isApprovedOrOwner) { owner = ownerOf(tokenId); require(owner != address(0), "The Stolen: nonexistent token"); isApprovedOrOwner = (spender == owner || _tokenApprovals[tokenId] == spender || isApprovedForAll(owner, spender)); } // APPROVAL /////////////////////////////////////////////////// /////////////////////////////////////////////////// // TRANSFER //Either get Flag from previous owner //Or Transfer Faction Token function _transfer( address from, address to, uint16 tokenId ) private { require(to != address(0), "The Stolen: transfer to the zero address"); require(from != to, "The Stolen: transfer to the zero address"); // Clear approvals from the previous owner if (tokenId == 0) { Flag memory flag = _flag; bool isApprovedOrOwner = (_msgSender() == flag.owner || getApproved(tokenId) == _msgSender() || isApprovedForAll(flag.owner, _msgSender())); require( isApprovedOrOwner, "The Stolen: transfer caller is not owner nor approved" ); _approve(flag.owner, address(0), tokenId); uint8 chanceForStealing = uint8( uint256( keccak256( abi.encodePacked((block.difficulty + block.timestamp)) ) ) % 100 ); if (chanceForStealing < 20) { _flag.vulnerable = 0x01; } _getFlag(to, 0x00); } else { FactionToken memory prevOwnership = _ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.owner || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.owner, _msgSender())); require( isApprovedOrOwner, "The Stolen: transfer caller is not owner nor approved" ); _transferFaction(from, to, tokenId, prevOwnership); } } function transferFrom( address from, address to, uint256 tokenId ) public override { uint16 tId = uint16(tokenId); (, bool isApprovedOrOwner) = _isApprovedOrOwner(_msgSender(), tId); require( isApprovedOrOwner, "The Stolen: transfer caller is not owner nor approved" ); _transfer(from, to, tId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { transferFrom(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "The Stolen: transfer to non ERC721Receiver implementer" ); } /////////////////////////////////////////////////// //Remove Faction Token from previous Owner //Add to new Owners wallet, merge accordingly function _transferFaction( address prevOwner, address newOwner, uint16 tokenId, FactionToken memory ft ) private { _removeFrom(prevOwner, tokenId, ft); emit Transfer(prevOwner, newOwner, tokenId); //Read Owner Data AddressData memory no = _addressData[newOwner]; AddressID memory noID = _addressIDs[newOwner]; //save Time if (no.hasFlag == 0x01) { _saveOwnerTime(); } //Merge with Existing Rogue Faction Token if (no.hasRogue == 0x01) { _burn( newOwner, no.rogueId ); no.hasRogue = 0x00; } ft.owner = newOwner; //if Wallet owns other Faction Token, merge with old Faction token if (noID.factionBalance > 0) { _burn( newOwner, noID.factionLastTokenId ); emit Merge(newOwner, noID.factionLastTokenId); } //set new Rogue Faction Token or Faction Token if (noID.factionBalance > 1) { noID = _checkNewLast(noID, ft, noID.factionLastTokenId); noID.factionBalance--; no.hasRogue = 0x01; no.rogueId = tokenId; ft.isRogue = 0x01; _addressIDs[newOwner] = noID; } else { ft.isRogue = 0x00; noID.factionBalance = 1; noID.factionId = ft.factionId; _factionIDs[ft.factionId].memberCount++; noID.factionLastTokenId = tokenId; noID.factionTokenId = tokenId; _addressIDs[newOwner] = noID; if (no.hasFlag == 0x01) { (no) = _changeFlagOwner(no, newOwner, 0x00); } } //Write Owner Data and Faction Token Ownership _addressData[newOwner] = no; _factionOwnerships[tokenId] = ft; } //Remove from previous owner //If wallet owns rogue or no further Faction Token, set wallet state accordingly function _removeFrom( address prevOwner, uint16 tokenId, FactionToken memory ft ) private { //Read previous Owner Data AddressData memory po = _addressData[prevOwner]; AddressID memory poID = _addressIDs[prevOwner]; _approve(prevOwner, address(0), tokenId); //remove from wallet if (po.hasRogue == 0x01 && po.rogueId == tokenId) { po.hasRogue = 0x00; } else { poID.factionBalance--; } //save Time if (po.hasFlag == 0x01) { _saveOwnerTime(); } //Make Flag Factionless if no further Faction Token exist //or set new IDs if (poID.factionBalance == 0) { _factionIDs[poID.factionId].memberCount--; (poID, po) = _checkRogue(poID, po); if (po.hasFlag == 0x01) { (po) = _changeFlagOwner(po, prevOwner, 0x00); } } else { if (tokenId == poID.factionLastTokenId) { poID = _checkNewLast(poID, ft, tokenId); } else { uint16 nextId = tokenId + 1; FactionToken memory ft2 = _factionOwnerships[nextId]; if (_existed(nextId)) { if (ft2.isBurned != 0x01 && ft2.owner == address(0)) { _factionOwnerships[nextId] = ft; } } } if (tokenId == poID.factionTokenId) { poID = _checkNewFirst(poID, ft, tokenId); } } //Write previous Owner Data _addressIDs[prevOwner] = poID; _addressData[prevOwner] = po; } //Check For Rogue Faction token in Wallet function _checkRogue(AddressID memory ownerID, AddressData memory ownerData) private returns (AddressID memory oID, AddressData memory o) { //Initialize Return Variables o = ownerData; oID = ownerID; //If has a Rogue Faction Token, make it new Faction Token //else set Factionless if (o.hasRogue == 0x01) { FactionToken memory r = _ownershipOf(o.rogueId); oID.factionId = r.factionId; _factionIDs[r.factionId].memberCount++; r.isRogue = 0x00; _factionOwnerships[o.rogueId] = r; oID.factionTokenId = o.rogueId; oID.factionLastTokenId = o.rogueId; o.rogueId = 0; } else { o.withoutFaction = 0x01; oID.factionLastTokenId = 0; oID.factionTokenId = 0; oID.factionId = 0; } } function _checkNewLast( AddressID memory ownerID, FactionToken memory ft, uint16 tokenId ) private returns (AddressID memory oID) { oID = ownerID; uint16 prevTokenId = tokenId - 1; if (prevTokenId != 0) { if (prevTokenId == oID.factionTokenId) { oID.factionLastTokenId = prevTokenId; return oID; } FactionToken memory ft2 = _ownershipOf( prevTokenId, oID.factionTokenId ); if (ft2.isBurned != 0x01 && ft2.owner == address(0)) { _factionOwnerships[prevTokenId] = ft; oID.factionLastTokenId = prevTokenId; return oID; } else { for ( uint16 curr = prevTokenId; curr >= oID.factionTokenId; curr-- ) { ft2 = _ownershipOf(curr, oID.factionTokenId); if ( ft2.isBurned != 0x01 && (ft2.owner == address(0) || ft2.owner == ft.owner) ) { _factionOwnerships[curr] = ft; oID.factionLastTokenId = curr; return oID; } } } } oID.factionLastTokenId = 0; oID.factionTokenId = 0; return oID; } function _checkNewFirst( AddressID memory ownerID, FactionToken memory ft, uint16 tokenId ) private returns (AddressID memory oID) { oID = ownerID; uint16 nextTokenId = tokenId + 1; if (nextTokenId == oID.factionLastTokenId) { oID.factionTokenId = nextTokenId; return oID; } FactionToken memory ft2 = _ownershipOf(nextTokenId, oID.factionTokenId); if (ft2.isBurned != 0x01 && ft2.owner == address(0)) { _factionOwnerships[nextTokenId] = ft; oID.factionTokenId = nextTokenId; return oID; } else { for ( uint16 curr = nextTokenId; curr <= oID.factionLastTokenId; curr++ ) { ft2 = _ownershipOf(curr, oID.factionTokenId); if ( ft2.isBurned != 0x01 && (ft2.owner == address(0) || ft2.owner == ft.owner) ) { _factionOwnerships[curr] = ft; oID.factionTokenId = curr; return oID; } } } oID.factionLastTokenId = 0; oID.factionTokenId = 0; return oID; } // TRANSFER /////////////////////////////////////////////////// /////////////////////////////////////////////////// // MINT FACTION //Return newly created or existing Faction (reserved restricted access) function _addToFaction(string memory factionName) private returns (uint16) { validateFactionName(factionName); FactionNameId memory factionNameID = _factionNameId[factionName]; FactionID memory faction; if (factionNameID.factionId != 0) { _factionIDs[factionNameID.factionId].memberCount++; faction = _factionIDs[factionNameID.factionId]; if (factionNameID.contractAddress != address(0)) { IERC721 c = IERC721(factionNameID.contractAddress); require( c.balanceOf(msg.sender) > 0, "The Stolen: must own reserved faction nft" ); } } else { faction = FactionID(_currentFactionIndex, 0, factionName); _factionNameId[factionName].factionId = _currentFactionIndex; _currentFactionIndex++; faction.memberCount++; _factionIDs[faction.factionId] = faction; } return faction.factionId; } //Mint Quantity Faction Token with Faction Name function factionMint(uint8 quantity, string memory factionName) external payable isOpen unlocked(quantity) { require( msg.sender != address(0), "The Stolen: Mint to the zero address not supported" ); require(msg.sender == tx.origin, "The Stolen: No Bot minting!"); if (_currentIndex-1<_freeMintCount) { require( msg.value == mintPrice * (quantity - 1), "The Stolen: invalid mint price" ); } else { require(msg.value == mintPrice * quantity, "The Stolen: invalid mint price"); } uint16 factionId = _addToFaction(factionName); uint16 startTokenId = _currentIndex; uint16 endTokenId = _currentIndex + quantity; require(quantity < maxBatchSize, "The Stolen: quantity too high"); require( _addressIDs[msg.sender].hasMinted != 0x01, "The Stolen: address already used its chance" ); if(_addressIDs[msg.sender].factionBalance > 0){ uint16 lastId = _addressIDs[msg.sender].factionLastTokenId; _burn(msg.sender,lastId); emit Merge(msg.sender, lastId); } _addressIDs[msg.sender] = AddressID( factionId, startTokenId, endTokenId - 1, quantity, 0x01 ); _factionOwnerships[startTokenId] = FactionToken( msg.sender, factionId, 0x00, 0x00 ); for (uint16 i = startTokenId; i < endTokenId; i++) { emit Transfer(address(0), msg.sender, i); } _currentIndex = endTokenId; } // MINT FACTION // MINT FLAG //Mint or Get the Flag function huntFlag() external payable locked { require( msg.sender != address(0), "The Stolen: Mint to the zero address not supported" ); require(msg.sender == tx.origin, "The Stolen: No Bot minting!"); address currentFlagOwner = _flag.owner; require(msg.sender != currentFlagOwner, "The Stolen: No Self minting!"); //If Flag is not stealable if (!flagVulnerable()) { uint256 currentMintPrice = (flagPrice * 11)/10; require(msg.value == currentMintPrice, "The Stolen: invalid get price"); flagPrice = currentMintPrice; //change price //If not minting Flag if (currentFlagOwner != address(0)) { _getFlag(msg.sender, 0x00); } else { _flagLastTransferTime = block.timestamp; _addressData[msg.sender] = _changeFlagOwner( _addressData[msg.sender], msg.sender, 0x00 ); emit MintedFlag(msg.sender); } } else { _getFlag(msg.sender, 0x01); } } // MINT FLAG /////////////////////////////////////////////////// /////////////////////////////////////////////////// // FLAG TRANSFER //save last Owner Score, set new Owner with stolen variable function _getFlag(address newOwner, bytes1 stolen) private { _saveOwnerTime(); _flagLastTransferTime = block.timestamp; _changeFlagOwner(newOwner, _flag.owner, stolen); } //save new Score, and if applicable, as Highscore and Leader score. //sets current Leader accordingly function _saveOwnerTime() private { if (_flag.withoutFaction == 0x00 && _flagLastTransferTime != 1) { uint16 fof = _flag.factionId; uint256 currentHoldtime = _factionData[fof].currentHoldtime + (block.timestamp - _flagLastTransferTime); _factionData[fof].currentHoldtime = currentHoldtime; if (_factionData[fof].highscore < currentHoldtime) { _factionData[fof].highscore = currentHoldtime; if (currentHoldtime > _currentLongestHoldtime) { _currentLongestHoldtime = currentHoldtime; emit NewLeader(_currentLeader, fof); _currentLeader = fof; } } } } function _changeFlagOwner( AddressData memory newOwnerData, address newOwner, bytes1 stolen ) private returns (AddressData memory no) { //Read owner Data no = newOwnerData; //Write owner Data (_addressData[newOwner], _addressData[_flag.owner]) = _changeFlagOwner( no, newOwner, _addressData[_flag.owner], _flag.owner, stolen ); } function _changeFlagOwner( address newOwner, address prevOwner, bytes1 stolen ) private { //Read owner Data AddressData memory no = _addressData[newOwner]; AddressData memory po = _addressData[prevOwner]; //Write owner Data (_addressData[newOwner], _addressData[prevOwner]) = _changeFlagOwner( no, newOwner, po, prevOwner, stolen ); } function _changeFlagOwner( AddressData memory noData, address newOwner, AddressData memory poData, address prevOwner, bytes1 stolen ) private returns (AddressData memory no, AddressData memory po) { //Initialize return Variables no = noData; po = poData; //Read Flag Flag memory f = _flag; uint16 noIDFactionId = _addressIDs[newOwner].factionId; uint16 poIDFactionId = _addressIDs[prevOwner].factionId; //remove flag from previous owner if existent if (prevOwner != newOwner) { if (prevOwner != address(0)) { po = _addressData[f.owner]; po.hasFlag = 0x00; } emit Transfer(_flag.owner, newOwner, 0); } //change Flag and Owner Data f.factionId = noIDFactionId; f.owner = newOwner; no.hasFlag = 0x01; f.vulnerable == 0x00; //if stolen, increase count, emit event if (stolen == 0x01) { no.stolen++; _factionData[poIDFactionId].stolen++; emit GotStolen(prevOwner, newOwner); } else { emit GotFlag(prevOwner, newOwner); } //if new faction reset timer if (noIDFactionId != poIDFactionId) { _factionData[poIDFactionId].currentHoldtime = 0; _factionData[noIDFactionId].currentHoldtime = 0; emit NewFactionHolding(noIDFactionId); } f.withoutFaction = no.withoutFaction; //set current faction holding _currentFactionHolding = noIDFactionId; //Write Flag _flag = f; } // FLAG TRANSFER /////////////////////////////////////////////////// /////////////////////////////////////////////////// // BURN //Burn Faction Token except Flag function burn(uint16 tokenId) public { require(tokenId > 0, "The Stolen: Shouldn't burn flag"); FactionToken memory ft = _ownershipOf(tokenId); require( _existed(tokenId) && ft.isBurned != 0x01, "The Stolen: nonexistent or burned token" ); (address owner, bool isApprovedOrOwner) = _isApprovedOrOwner( _msgSender(), tokenId ); require(isApprovedOrOwner, "The Stolen: caller is not owner nor approved"); _burn(owner, tokenId, ft); } //Remove Faction from owner and burn it function _burn( address owner, uint16 tokenId, FactionToken memory ft ) internal { _removeFrom(owner, tokenId, ft); emit Transfer(owner, address(0), tokenId); _burnedCount++; ft.owner = address(0); ft.isBurned = 0x01; _factionOwnerships[tokenId] = ft; } //Remove Faction from owner and burn it function _burn( address owner, uint16 tokenId ) internal { FactionToken memory ft = _factionOwnerships[tokenId]; _removeFrom(owner, tokenId, ft); emit Transfer(owner, address(0), tokenId); _burnedCount++; ft.owner = address(0); ft.isBurned = 0x01; _factionOwnerships[tokenId] = ft; } // BURN /////////////////////////////////////////////////// /////////////////////////////////////////////////// // TOKENURI function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (tokenId == 0) { uint16 factionId = _flag.factionId; string memory factionName = _flag.withoutFaction != 0x01 ? _factionIDs[factionId].name : ""; return stolenImage.flagTokenURI(factionName, getCurrentHoldtime()); } else { uint16 tId = uint16(tokenId); require(_existed(tId) && !_burned(tId), "The Stolen: nonexistent token"); uint16 factionId = _ownershipOf(tId).factionId; AddressData memory data = _addressData[_ownershipOf(tId).owner]; FactionData memory fdata = _factionData[factionId]; ITheStolenGenerator.FactionImage memory factionImageData; factionImageData.fillFaction = factionId == _currentFactionHolding && _flag.withoutFaction != 0x01; factionImageData.fillOwner = _ownershipOf(tId).owner == _flag.owner && _flag.withoutFaction != 0x01; factionImageData.owner = _ownershipOf(tId).owner; factionImageData.fillHighscore = _currentLeader == factionId; factionImageData.factionName = _factionIDs[factionId].name; factionImageData.highscore = fdata.highscore; factionImageData.member = _factionIDs[factionId].memberCount; factionImageData.factionSteals = fdata.stolen; factionImageData.steals = data.stolen; factionImageData.current = factionId == _currentFactionHolding && _flag.withoutFaction != 0x01 ? getCurrentHoldtime() : 0; return stolenImage.factionTokenURI(factionImageData); } } function _baseURI() internal view virtual returns (string memory) { return ""; } // TOKENURI /////////////////////////////////////////////////// /////////////////////////////////////////////////// // OWNER FUNCTIONS function collectFees() external onlyOwner nonReentrant { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "The Stolen: Transfer failed."); } function lockFactionMint() external onlyOwner { _locked = 0x01; } function startFactionMint(address imageContract) external onlyOwner { setImageContract(imageContract); _mintStarttime = block.timestamp; _open = 0x01; } // OWNER FUNCTIONS /////////////////////////////////////////////////// /** * @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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "The Stolen: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } }
Remove Faction from owner and burn it
function _burn( address owner, uint16 tokenId, FactionToken memory ft ) internal { _removeFrom(owner, tokenId, ft); emit Transfer(owner, address(0), tokenId); _burnedCount++; ft.owner = address(0); ft.isBurned = 0x01; _factionOwnerships[tokenId] = ft; }
1,413,214
./partial_match/4/0xB6B529D997c0E0e7f6AB1f6CC64A71f18D7d65F3/sources/pxv3.sol
make sure the array lengths are all the same
function CloseModApprobationVote() public { require(moderation_gov_vote_in_progress); require(c_mod_vote_count >= MODERATION_APPROB_MIN_VOTE_COUNT); for (uint i = 0; i < active_moderators_.length; i++) { address a = active_moderators_[i]; uint256 slashed_token_amount = balances[a].staked_token_balance*50/100; total_stake_count -= balances[a].staked_token_balance*50/100; staking_rewards_pool += slashed_token_amount; moderators[a].status = ModeratorStatus.SLASHED; delete moderators[a].takedown_block_ids; } else{ balances[a].available_token_balance = balances[a].available_token_balance + moderators[a].locked_rewards; } moderators[a].on = false; moderators[a].votes_ok = 0; moderators[a].votes_slash = 0; moderators[a].locked_rewards = 0; }
8,699,974
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Lockable.sol"; /** * @title A contract to track a whitelist of addresses. */ contract AddressWhitelist is Ownable, Lockable { enum Status { None, In, Out } mapping(address => Status) public whitelist; address[] public whitelistIndices; event AddedToWhitelist(address indexed addedAddress); event RemovedFromWhitelist(address indexed removedAddress); /** * @notice Adds an address to the whitelist. * @param newElement the new address to add. */ function addToWhitelist(address newElement) external nonReentrant() onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddedToWhitelist(newElement); } /** * @notice Removes an address from the whitelist. * @param elementToRemove the existing address to remove. */ function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemovedFromWhitelist(elementToRemove); } } /** * @notice Checks whether an address is on the whitelist. * @param elementToCheck the address to check. * @return True if `elementToCheck` is on the whitelist, or False. */ function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) { return whitelist[elementToCheck] == Status.In; } /** * @notice Gets all addresses that are currently included in the whitelist. * @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out * of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we * can modify the implementation so that when addresses are removed, the last addresses in the array is moved to * the empty index. * @return activeWhitelist the list of addresses on the whitelist. */ function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint256 activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } } 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; } } 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. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } 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: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() internal { // Storing an initial 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 percetange 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. _notEntered = true; } /** * @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() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./MultiRole.sol"; import "../interfaces/ExpandedIERC20.sol"; /** * @title An ERC20 with permissioned burning and minting. The contract deployer will initially * be the owner who is capable of adding new roles. */ contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) public ERC20(_tokenName, _tokenSymbol) { _setupDecimals(_tokenDecimals); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external virtual override { addMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external virtual override { addMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external virtual override { resetMember(uint256(Roles.Owner), account); } } 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 {ERC20MinterPauser}. * * 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 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 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 { } } 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); } 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) { // 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; } } 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"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } /** * @title Base class to manage permissions for the derived class. */ abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes burn and mint methods. */ abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); function addMinter(address account) external virtual; function addBurner(address account) external virtual; function resetOwner(address account) external virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./Timer.sol"; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) internal { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return now; // solhint-disable-line not-rely-on-time } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() public { currentTime = now; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI) * @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note: * this token should never be used to store real value since it allows permissionless minting. */ contract TestnetERC20 is ERC20 { /** * @notice Constructs the TestnetERC20. * @param _name The name which describes the new token. * @param _symbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _decimals The number of decimals to define token precision. */ constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); } // Sample token information. /** * @notice Mints value tokens to the owner address. * @param ownerAddress the address to mint to. * @param value the amount of tokens to mint. */ function allocateTo(address ownerAddress, uint256 value) external { _mint(ownerAddress, value); } } /** * Withdrawable contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./MultiRole.sol"; /** * @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds. */ abstract contract Withdrawable is MultiRole { using SafeERC20 for IERC20; uint256 private roleId; /** * @notice Withdraws ETH from the contract. */ function withdraw(uint256 amount) external onlyRoleHolder(roleId) { Address.sendValue(msg.sender, amount); } /** * @notice Withdraws ERC20 tokens from the contract. * @param erc20Address ERC20 token to withdraw. * @param amount amount of tokens to withdraw. */ function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) { IERC20 erc20 = IERC20(erc20Address); erc20.safeTransfer(msg.sender, amount); } /** * @notice Internal method that allows derived contracts to create a role for withdrawal. * @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function * properly. * @param newRoleId ID corresponding to role whose members can withdraw. * @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership. * @param withdrawerAddress new manager of withdrawable role. */ function _createWithdrawRole( uint256 newRoleId, uint256 managingRoleId, address withdrawerAddress ) internal { roleId = newRoleId; _createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress); } /** * @notice Internal method that allows derived contracts to choose the role for withdrawal. * @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be * called by the derived class for this contract to function properly. * @param setRoleId ID corresponding to role whose members can withdraw. */ function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) { roleId = setRoleId; } } 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 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"); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Interface for Balancer. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract Balancer { function getSpotPriceSansFee(address tokenIn, address tokenOut) external view virtual returns (uint256 spotPrice); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes the decimals read only method. */ interface IERC20Standard is IERC20 { /** * @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() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; abstract contract OneSplit { function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public view virtual returns (uint256 returnAmount, uint256[] memory distribution); function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) public payable virtual returns (uint256 returnAmount); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; // This is an interface to interact with a deployed implementation by https://github.com/kleros/action-callback-bots for // batching on-chain transactions. // See deployed implementation here: https://etherscan.io/address/0x82458d1c812d7c930bb3229c9e159cbabd9aa8cb. abstract contract TransactionBatcher { function batchSend( address[] memory targets, uint256[] memory values, bytes[] memory datas ) public payable virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Interface for Uniswap v2. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract Uniswap { // Called after every swap showing the new uniswap "price" for this token pair. event Sync(uint112 reserve0, uint112 reserve1); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/Balancer.sol"; /** * @title Balancer Mock */ contract BalancerMock is Balancer { uint256 price = 0; // these params arent used in the mock, but this is to maintain compatibility with balancer API function getSpotPriceSansFee(address tokenIn, address tokenOut) external view virtual override returns (uint256 spotPrice) { return price; } // this is not a balancer call, but for testing for changing price. function setPrice(uint256 newPrice) external { price = newPrice; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Implements only the required ERC20 methods. This contract is used * test how contracts handle ERC20 contracts that have not implemented `decimals()` * @dev Mostly copied from Consensys EIP-20 implementation: * https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol */ contract BasicERC20 is IERC20 { uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; uint256 private _totalSupply; constructor(uint256 _initialAmount) public { balances[msg.sender] = _initialAmount; _totalSupply = _initialAmount; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public override returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public override returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view override returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public override returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view override returns (uint256 remaining) { return allowed[_owner][_spender]; } } /* MultiRoleTest contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/MultiRole.sol"; // The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes. contract MultiRoleTest is MultiRole { function createSharedRole( uint256 roleId, uint256 managingRoleId, address[] calldata initialMembers ) external { _createSharedRole(roleId, managingRoleId, initialMembers); } function createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) external { _createExclusiveRole(roleId, managingRoleId, initialMember); } // solhint-disable-next-line no-empty-blocks function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {} } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/OneSplit.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title OneSplit Mock that allows manual price injection. */ contract OneSplitMock is OneSplit { address constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; mapping(bytes32 => uint256) prices; receive() external payable {} // Sets price of 1 FROM = <PRICE> TO function setPrice( address from, address to, uint256 price ) external { prices[keccak256(abi.encodePacked(from, to))] = price; } function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public view override returns (uint256 returnAmount, uint256[] memory distribution) { returnAmount = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount; return (returnAmount, distribution); } function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) public payable override returns (uint256 returnAmount) { uint256 amountReturn = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount; require(amountReturn >= minReturn, "Min Amount not reached"); if (destToken == ETH_ADDRESS) { msg.sender.transfer(amountReturn); } else { require(IERC20(destToken).transfer(msg.sender, amountReturn), "erc20-send-failed"); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; // Tests reentrancy guards defined in Lockable.sol. // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol. contract ReentrancyAttack { function callSender(bytes4 data) public { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call(abi.encodeWithSelector(data)); require(success, "ReentrancyAttack: failed call"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; // The Reentrancy Checker causes failures if it is successfully able to re-enter a contract. // How to use: // 1. Call setTransactionData with the transaction data you want the Reentrancy Checker to reenter the calling // contract with. // 2. Get the calling contract to call into the reentrancy checker with any call. The fallback function will receive // this call and reenter the contract with the transaction data provided in 1. If that reentrancy call does not // revert, then the reentrancy checker reverts the initial call, likely causeing the entire transaction to revert. // // Note: the reentrancy checker has a guard to prevent an infinite cycle of reentrancy. Inifinite cycles will run out // of gas in all cases, potentially causing a revert when the contract is adequately protected from reentrancy. contract ReentrancyChecker { bytes public txnData; bool hasBeenCalled; // Used to prevent infinite cycles where the reentrancy is cycled forever. modifier skipIfReentered { if (hasBeenCalled) { return; } hasBeenCalled = true; _; hasBeenCalled = false; } function setTransactionData(bytes memory _txnData) public { txnData = _txnData; } function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool success) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } } fallback() external skipIfReentered { // Attampt to re-enter with the set txnData. bool success = _executeCall(msg.sender, 0, txnData); // Fail if the call succeeds because that means the re-entrancy was successful. require(!success, "Re-entrancy was successful"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Lockable.sol"; import "./ReentrancyAttack.sol"; // Tests reentrancy guards defined in Lockable.sol. // Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol. contract ReentrancyMock is Lockable { uint256 public counter; constructor() public { counter = 0; } function callback() external nonReentrant { _count(); } function countAndSend(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function countAndCall(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("getCount()")); attacker.callSender(func); } function countLocalRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); require(success, "ReentrancyMock: failed call"); } } function countLocalCall() public nonReentrant { getCount(); } function countThisCall() public nonReentrant { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("getCount()")); require(success, "ReentrancyMock: failed call"); } function getCount() public view nonReentrantView returns (uint256) { return counter; } function _count() private { counter += 1; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract SignedFixedPointTest { using FixedPoint for FixedPoint.Signed; using FixedPoint for int256; using SafeMath for int256; function wrapFromSigned(int256 a) external pure returns (uint256) { return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue; } function wrapFromUnsigned(uint256 a) external pure returns (int256) { return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue; } function wrapFromUnscaledInt(int256 a) external pure returns (int256) { return FixedPoint.fromUnscaledInt(a).rawValue; } function wrapIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b)); } function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(b); } function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b)); } function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b)); } function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Signed(b)); } function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMin(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue; } function wrapMax(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue; } function wrapAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(b).rawValue; } function wrapSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) { return a.sub(FixedPoint.Signed(b)).rawValue; } function wrapMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue; } function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(b).rawValue; } function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue; } function wrapDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue; } function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(b).rawValue; } function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) { return a.div(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(int256 a, uint256 b) external pure returns (int256) { return FixedPoint.Signed(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Testable.sol"; // TestableTest is derived from the abstract contract Testable for testing purposes. contract TestableTest is Testable { // solhint-disable-next-line no-empty-blocks constructor(address _timerAddress) public Testable(_timerAddress) {} function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) { // solhint-disable-next-line not-rely-on-time return (getCurrentTime(), now); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/Uniswap.sol"; /** * @title Uniswap v2 Mock that allows manual price injection. */ contract UniswapMock is Uniswap { function setPrice(uint112 reserve0, uint112 reserve1) external { emit Sync(reserve0, reserve1); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract UnsignedFixedPointTest { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeMath for uint256; function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) { return FixedPoint.fromUnscaledUint(a).rawValue; } function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(b); } function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b)); } function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b)); } function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMin(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue; } function wrapMax(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue; } function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; } function wrapSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.sub(FixedPoint.Unsigned(b)).rawValue; } function wrapMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue; } function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(b).rawValue; } function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(b).rawValue; } function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue; } function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(b).rawValue; } function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.div(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Withdrawable.sol"; // WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes. contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } // solhint-disable-next-line no-empty-blocks constructor() public { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title EmergencyShutdownable contract. * @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable. * This contract provides modifiers that can be used by children contracts to determine if the contract is * in the shutdown state. The child contract is expected to implement the logic that happens * once a shutdown occurs. */ abstract contract EmergencyShutdownable { using SafeMath for uint256; /**************************************** * EMERGENCY SHUTDOWN DATA STRUCTURES * ****************************************/ // Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered. uint256 public emergencyShutdownTimestamp; /**************************************** * MODIFIERS * ****************************************/ modifier notEmergencyShutdown() { _notEmergencyShutdown(); _; } modifier isEmergencyShutdown() { _isEmergencyShutdown(); _; } /**************************************** * EXTERNAL FUNCTIONS * ****************************************/ constructor() public { emergencyShutdownTimestamp = 0; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _notEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp == 0); } function _isEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp != 0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/interfaces/StoreInterface.sol"; import "../../oracle/interfaces/FinderInterface.sol"; import "../../oracle/interfaces/AdministrateeInterface.sol"; import "../../oracle/implementation/Constants.sol"; /** * @title FeePayer contract. * @notice Provides fee payment functionality for the ExpiringMultiParty contract. * contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`. */ abstract contract FeePayer is AdministrateeInterface, Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees virtual { // Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the // regular fee applied linearly since the last update. This implies that the compounding rate depends on the // frequency of update transactions that have this modifier, and it never reaches the ideal of continuous // compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the // complexity of compounding data on-chain. payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { StoreInterface store = _getStore(); uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral from which to pay fees. if (collateralPool.isEqual(0)) { // Note: set the lastPaymentTime in this case so the contract is credited for paying during periods when it // has no locked collateral. lastPaymentTime = time; return totalPaid; } // Exit early if fees were already paid during this block. if (lastPaymentTime == time) { return totalPaid; } (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool); lastPaymentTime = time; totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return totalPaid; } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /** * @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors. * @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively * pays all sponsors a pro-rata portion of the excess collateral. * @dev This will revert if PfC is 0 and this contract's collateral balance > 0. */ function gulp() external nonReentrant() { _gulp(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. // Note: revert reason removed to save bytecode. require(collateralPool.isGreaterThan(amount)); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _gulp() internal { FixedPoint.Unsigned memory currentPfc = _pfc(); FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); if (currentPfc.isLessThan(currentBalance)) { cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc)); } } function _pfc() internal view virtual returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that allows financial contracts to pay oracle fees for their use of the system. */ interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that all financial contracts expose to the admin. */ interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../common/implementation/FixedPoint.sol"; interface ExpiringContractInterface { function expirationTimestamp() external view returns (uint256); } /** * @title Financial product library contract * @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom * Financial product library implementations. */ abstract contract FinancialProductLibrary { using FixedPoint for FixedPoint.Unsigned; /** * @notice Transforms a given oracle price using the financial product libraries transformation logic. * @param oraclePrice input price returned by the DVM to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedOraclePrice input oraclePrice with the transformation function applied. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view virtual returns (FixedPoint.Unsigned memory) { return oraclePrice; } /** * @notice Transforms a given collateral requirement using the financial product libraries transformation logic. * @param oraclePrice input price returned by DVM used to transform the collateral requirement. * @param collateralRequirement input collateral requirement to be transformed. * @return transformedCollateralRequirement input collateral requirement with the transformation function applied. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view virtual returns (FixedPoint.Unsigned memory) { return collateralRequirement; } /** * @notice Transforms a given price identifier using the financial product libraries transformation logic. * @param priceIdentifier input price identifier defined for the financial contract. * @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier. * @return transformedPriceIdentifier input price identifier with the transformation function applied. */ function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view virtual returns (bytes32) { return priceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Pre-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made before expiration then a transformation is made to the identifier * & if it is at or after expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration. * @dev Note: a) Only the owner (deployer) of this library can set identifier transformations b) The identifier can't * be set to blank. c) A transformed price can only be set once to prevent the deployer from changing it after the fact. * d) financialProduct must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public onlyOwner nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is before contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return financialProductTransformedIdentifiers[msg.sender]; } else { return identifier; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Structured Note Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If * ETHUSD is above that strike, the contract pays out a given dollar amount of ETH. * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH * If ETHUSD < $400 at expiry, token is redeemed for 1 ETH. * If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM. */ contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable { mapping(address => FixedPoint.Unsigned) financialProductStrikes; /** * @notice Enables the deployer of the library to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the structured note to be applied to the financial product. * @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) financialProduct must exposes an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public onlyOwner nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the structured note payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThan(strike)) { return FixedPoint.fromUnscaledUint(1); } else { // Token expires to be worth strike $ worth of collateral. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH. return strike.div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price * of the structured note is greater than the strike then the collateral requirement scales down accordingly. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If the price is less than the strike than the original collateral requirement is used. if (oraclePrice.isLessThan(strike)) { return collateralRequirement; } else { // If the price is more than the strike then the collateral requirement is scaled by the strike. For example // a strike of $400 and a CR of 1.2 would yield: // ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292 // ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96 return collateralRequirement.mul(strike.div(oraclePrice)); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/implementation/Constants.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../perpetual-multiparty/ConfigStoreInterface.sol"; import "./EmergencyShutdownable.sol"; import "./FeePayer.sol"; /** * @title FundingRateApplier contract. * @notice Provides funding rate payment functionality for the Perpetual contract. */ abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; using SafeERC20 for IERC20; using SafeMath for uint256; /**************************************** * FUNDING RATE APPLIER DATA STRUCTURES * ****************************************/ struct FundingRate { // Current funding rate value. FixedPoint.Signed rate; // Identifier to retrieve the funding rate. bytes32 identifier; // Tracks the cumulative funding payments that have been paid to the sponsors. // The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment). // Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ... // For example: // The cumulativeFundingRateMultiplier should start at 1. // If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01. // If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201). FixedPoint.Unsigned cumulativeMultiplier; // Most recent time that the funding rate was updated. uint256 updateTime; // Most recent time that the funding rate was applied and changed the cumulative multiplier. uint256 applicationTime; // The time for the active (if it exists) funding rate proposal. 0 otherwise. uint256 proposalTime; } FundingRate public fundingRate; // Remote config store managed an owner. ConfigStoreInterface public configStore; /**************************************** * EVENTS * ****************************************/ event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward); /**************************************** * MODIFIERS * ****************************************/ // This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate. modifier fees override { // Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the // rate applied linearly since the last update. This implies that the compounding rate depends on the frequency // of update transactions that have this modifier, and it never reaches the ideal of continuous compounding. // This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of // compounding data on-chain. applyFundingRate(); _; } // Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees. modifier regularFees { payRegularFees(); _; } /** * @notice Constructs the FundingRateApplier contract. Called by child contracts. * @param _fundingRateIdentifier identifier that tracks the funding rate of this contract. * @param _collateralAddress address of the collateral token. * @param _finderAddress Finder used to discover financial-product-related contracts. * @param _configStoreAddress address of the remote configuration store managed by an external owner. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress address of the timer contract in test envs, otherwise 0x0. */ constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() { uint256 currentTime = getCurrentTime(); fundingRate.updateTime = currentTime; fundingRate.applicationTime = currentTime; // Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are // applied over time. fundingRate.cumulativeMultiplier = _tokenScaling; fundingRate.identifier = _fundingRateIdentifier; configStore = ConfigStoreInterface(_configStoreAddress); } /** * @notice This method takes 3 distinct actions: * 1. Pays out regular fees. * 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards. * 3. Applies the prevailing funding rate over the most recent period. */ function applyFundingRate() public regularFees() nonReentrant() { _applyEffectiveFundingRate(); } /** * @notice Proposes a new funding rate. Proposer receives a reward if correct. * @param rate funding rate being proposed. * @param timestamp time at which the funding rate was computed. */ function proposeNewRate(FixedPoint.Signed memory rate, uint256 timestamp) external fees() nonReentrant() returns (FixedPoint.Unsigned memory totalBond) { require(fundingRate.proposalTime == 0, "Proposal in progress"); _validateFundingRate(rate); // Timestamp must be after the last funding rate update time, within the last 30 minutes. uint256 currentTime = getCurrentTime(); uint256 updateTime = fundingRate.updateTime; require( timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit), "Invalid proposal time" ); // Set the proposal time in order to allow this contract to track this request. fundingRate.proposalTime = timestamp; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Set up optimistic oracle. bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Note: requestPrice will revert if `timestamp` is less than the current block timestamp. optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0); totalBond = FixedPoint.Unsigned( optimisticOracle.setBond( identifier, timestamp, ancillaryData, _pfc().mul(_getConfig().proposerBondPct).rawValue ) ); // Pull bond from caller and send to optimistic oracle. if (totalBond.isGreaterThan(0)) { collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue); } optimisticOracle.proposePriceFor( msg.sender, address(this), identifier, timestamp, ancillaryData, rate.rawValue ); } // Returns a token amount scaled by the current funding rate multiplier. // Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value. function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) internal view returns (FixedPoint.Unsigned memory tokenDebt) { return rawTokenDebt.mul(fundingRate.cumulativeMultiplier); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) { return configStore.updateAndGetCurrentConfig(); } function _getLatestFundingRate() internal returns (FixedPoint.Signed memory) { uint256 proposalTime = fundingRate.proposalTime; // If there is no pending proposal then return the current funding rate, otherwise // check to see if we can update the funding rate. if (proposalTime != 0) { // Attempt to update the funding rate. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Try to get the price from the optimistic oracle. This call will revert if the request has not resolved // yet. If the request has not resolved yet, then we need to do additional checks to see if we should // "forget" the pending proposal and allow new proposals to update the funding rate. try optimisticOracle.getPrice(identifier, proposalTime, ancillaryData) returns (int256 price) { // If successful, determine if the funding rate state needs to be updated. // If the request is more recent than the last update then we should update it. uint256 lastUpdateTime = fundingRate.updateTime; if (proposalTime >= lastUpdateTime) { // Update funding rates fundingRate.rate = FixedPoint.Signed(price); fundingRate.updateTime = proposalTime; // If there was no dispute, send a reward. FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0); OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer == address(0)) { reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime)); if (reward.isGreaterThan(0)) { _adjustCumulativeFeeMultiplier(reward, _pfc()); collateralCurrency.safeTransfer(request.proposer, reward.rawValue); } } // This event will only be emitted after the fundingRate struct's "updateTime" has been set // to the latest proposal's proposalTime, indicating that the proposal has been published. // So, it suffices to just emit fundingRate.updateTime here. emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue); } // Set proposal time to 0 since this proposal has now been resolved. fundingRate.proposalTime = 0; } catch { // Stop tracking and allow other proposals to come in if: // - The requester address is empty, indicating that the Oracle does not know about this funding rate // request. This is possible if the Oracle is replaced while the price request is still pending. // - The request has been disputed. OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer != address(0) || request.proposer == address(0)) { fundingRate.proposalTime = 0; } } } return fundingRate.rate; } // Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the // perpetual's security. For example, let's examine the case where the max and min funding rates // are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a // proposer who can deter honest proposers for 74 hours: // 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%. // How would attack work? Imagine that the market is very volatile currently and that the "true" funding // rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500% // (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding // rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value. function _validateFundingRate(FixedPoint.Signed memory rate) internal { require( rate.isLessThanOrEqual(_getConfig().maxFundingRate) && rate.isGreaterThanOrEqual(_getConfig().minFundingRate) ); } // Fetches a funding rate from the Store, determines the period over which to compute an effective fee, // and multiplies the current multiplier by the effective fee. // A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier. // Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat // values < 1 as "negative". function _applyEffectiveFundingRate() internal { // If contract is emergency shutdown, then the funding rate multiplier should no longer change. if (emergencyShutdownTimestamp != 0) { return; } uint256 currentTime = getCurrentTime(); uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime); fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate( paymentPeriod, _getLatestFundingRate(), fundingRate.cumulativeMultiplier ); fundingRate.applicationTime = currentTime; } function _calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) { // Note: this method uses named return variables to save a little bytecode. // The overall formula that this function is performing: // newCumulativeFundingRateMultiplier = // (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier. FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1); // Multiply the per-second rate over the number of seconds that have elapsed to get the period rate. FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds)); // Add one to create the multiplier to scale the existing fee multiplier. FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate); // Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned. FixedPoint.Unsigned memory unsignedPeriodMultiplier = FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0))); // Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new // cumulative funding rate multiplier. newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier); } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(_getTokenAddress()); } function _getTokenAddress() internal view virtual returns (address); } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 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} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @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 < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(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 < 2**64, "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 < 2**32, "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 < 2**16, "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 < 2**8, "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 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) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length of a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function getPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; interface ConfigStoreInterface { // All of the configuration settings available for querying by a perpetual. struct ConfigSettings { // Liveness period (in seconds) for an update to currentConfig to become official. uint256 timelockLiveness; // Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%. FixedPoint.Unsigned rewardRatePerSecond; // Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%. FixedPoint.Unsigned proposerBondPct; // Maximum funding rate % per second that can be proposed. FixedPoint.Signed maxFundingRate; // Minimum funding rate % per second that can be proposed. FixedPoint.Signed minFundingRate; // Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest // update time. uint256 proposalTimePastLimit; } function updateAndGetCurrentConfig() external returns (ConfigSettings memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Burnable and mintable ERC20. * @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles. */ contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external override nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external override nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external override nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./SyntheticToken.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Factory for creating new mintable and burnable tokens. */ contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } /** *Submitted for verification at Etherscan.io on 2017-12-12 */ // Copyright (C) 2015, 2016, 2017 Dapphub // 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/>. // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; // Copied from the verified code from Etherscan: // https://etherscan.io/address/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2#code // And then updated for Solidity version 0.6. Specific changes: // * Change `function() public` into `receive() external` and `fallback() external` // * Change `this.balance` to `address(this).balance` // * Ran prettier contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; receive() external payable { deposit(); } fallback() external payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); } function withdraw(uint256 wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); emit Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint256) { return address(this).balance; } function approve(address guy, uint256 wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint256 wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint256 wad ) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } /* GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> 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/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../common/FeePayer.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/implementation/ContractCreator.sol"; /** * @title Token Deposit Box * @notice This is a minimal example of a financial template that depends on price requests from the DVM. * This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral. * The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount. * When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM. * For simplicty, the user is constrained to have one outstanding withdrawal request at any given time. * Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box, * and final fees are charged on each price request. * * This example is intended to accompany a technical tutorial for how to integrate the DVM into a project. * The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price * requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework. * * The typical user flow would be: * - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit * box is therefore wETH. * The user can subsequently make withdrawal requests for USD-denominated amounts of wETH. * - User deposits 10 wETH into their deposit box. * - User later requests to withdraw $100 USD of wETH. * - DepositBox asks DVM for latest wETH/USD exchange rate. * - DVM resolves the exchange rate at: 1 wETH is worth 200 USD. * - DepositBox transfers 0.5 wETH to user. */ contract DepositBox is FeePayer, ContractCreator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; // Represents a single caller's deposit box. All collateral is held by this contract. struct DepositBoxData { // Requested amount of collateral, denominated in quote asset of the price identifier. // Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then // this represents a withdrawal request for 100 USD worth of wETH. FixedPoint.Unsigned withdrawalRequestAmount; // Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`. uint256 requestPassTimestamp; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps addresses to their deposit boxes. Each address can have only one position. mapping(address => DepositBoxData) private depositBoxes; // Unique identifier for DVM price feed ticker. bytes32 private priceIdentifier; // Similar to the rawCollateral in DepositBoxData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned private rawTotalDepositBoxCollateral; // This blocks every public state-modifying method until it flips to true, via the `initialize()` method. bool private initialized; /**************************************** * EVENTS * ****************************************/ event NewDepositBox(address indexed user); event EndedDepositBox(address indexed user); event Deposit(address indexed user, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp); event RequestWithdrawalExecuted( address indexed user, uint256 indexed collateralAmount, uint256 exchangeRate, uint256 requestPassTimestamp ); event RequestWithdrawalCanceled( address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp ); /**************************************** * MODIFIERS * ****************************************/ modifier noPendingWithdrawal(address user) { _depositBoxHasNoPendingWithdrawal(user); _; } modifier isInitialized() { _isInitialized(); _; } /**************************************** * PUBLIC FUNCTIONS * ****************************************/ /** * @notice Construct the DepositBox. * @param _collateralAddress ERC20 token to be deposited. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited. * The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20 * currency deposited into this account, and it is denominated in the "quote" asset on withdrawals. * An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, address _timerAddress ) public ContractCreator(_finderAddress) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); priceIdentifier = _priceIdentifier; } /** * @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required * to make price requests in production environments. * @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM. * Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role * in order to register with the `Registry`. But, its address is not known until after deployment. */ function initialize() public nonReentrant() { initialized = true; _registerContract(new address[](0), address(this)); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box. * @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) { emit NewDepositBox(msg.sender); } // Increase the individual deposit box and global collateral balance by collateral amount. _incrementCollateralBalances(depositBoxData, collateralAmount); emit Deposit(msg.sender, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount` * from their position denominated in the quote asset of the price identifier, following a DVM price resolution. * @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time. * Only one withdrawal request can exist for the user. * @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw. */ function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount) public isInitialized() noPendingWithdrawal(msg.sender) nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Update the position object for the user. depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount; depositBoxData.requestPassTimestamp = getCurrentTime(); emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp); // Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee. FixedPoint.Unsigned memory finalFee = _computeFinalFees(); require( _getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee), "Cannot pay final fee" ); _payFinalFees(address(this), finalFee); // A price request is sent for the current timestamp. _requestOraclePrice(depositBoxData.requestPassTimestamp); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), * withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function executeWithdrawal() external isInitialized() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require( depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // Get the resolved price or revert. FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp); // Calculate denomated amount of collateral based on resolved exchange rate. // Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. // Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div(exchangeRate); // If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) { denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral); // Reset the position state as all the value has been removed after settlement. emit EndedDepositBox(msg.sender); } // Decrease the individual deposit box and global collateral balance. amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw); emit RequestWithdrawalExecuted( msg.sender, amountWithdrawn.rawValue, exchangeRate.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external isInitialized() nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled( msg.sender, depositBoxData.withdrawalRequestAmount.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); } /** * @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but * because this is a minimal demo they will simply exit silently. */ function emergencyShutdown() external override isInitialized() nonReentrant() { return; } /** * @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently. */ function remargin() external override isInitialized() nonReentrant() { return; } /** * @notice Accessor method for a user's collateral. * @dev This is necessary because the struct returned by the depositBoxes() method shows * rawCollateral, which isn't a user-readable value. * @param user address whose collateral amount is retrieved. * @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). */ function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the entire contract. * @return the total fee-adjusted collateral amount in the contract (i.e. across all users). */ function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(depositBoxData.rawCollateral, collateralAmount); return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(depositBoxData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount); } function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal { depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); depositBoxData.requestPassTimestamp = 0; } function _depositBoxHasNoPendingWithdrawal(address user) internal view { require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal"); } function _isInitialized() internal view { require(initialized, "Uninitialized contract"); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For simplicity we don't want to deal with negative prices. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from // which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the // contract. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/FinderInterface.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "./Registry.sol"; import "./Constants.sol"; /** * @title Base contract for all financial contract creators */ abstract contract ContractCreator { address internal finderAddress; constructor(address _finderAddress) public { finderAddress = _finderAddress; } function _requireWhitelistedCollateral(address collateralAddress) internal view { FinderInterface finder = FinderInterface(finderAddress); AddressWhitelist collateralWhitelist = AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted"); } function _registerContract(address[] memory parties, address contractToRegister) internal { FinderInterface finder = FinderInterface(finderAddress); Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); registry.registerContract(parties, contractToRegister); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../interfaces/RegistryInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title Registry for financial contracts and approved financial contract creators. * @dev Maintains a whitelist of financial contract creators that are allowed * to register new financial contracts and stores party members of a financial contract. */ contract Registry is RegistryInterface, MultiRole { using SafeMath for uint256; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // The owner manages the set of ContractCreators. ContractCreator // Can register financial contracts. } // This enum is required because a `WasValid` state is required // to ensure that financial contracts cannot be re-registered. enum Validity { Invalid, Valid } // Local information about a contract. struct FinancialContract { Validity valid; uint128 index; } struct Party { address[] contracts; // Each financial contract address is stored in this array. // The address of each financial contract is mapped to its index for constant time look up and deletion. mapping(address => uint256) contractIndex; } // Array of all contracts that are approved to use the UMA Oracle. address[] public registeredContracts; // Map of financial contract contracts to the associated FinancialContract struct. mapping(address => FinancialContract) public contractMap; // Map each party member to their their associated Party struct. mapping(address => Party) private partyMap; /**************************************** * EVENTS * ****************************************/ event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties); event PartyAdded(address indexed contractAddress, address indexed party); event PartyRemoved(address indexed contractAddress, address indexed party); /** * @notice Construct the Registry contract. */ constructor() public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); // Start with no contract creators registered. _createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0)); } /**************************************** * REGISTRATION FUNCTIONS * ****************************************/ /** * @notice Registers a new financial contract. * @dev Only authorized contract creators can call this method. * @param parties array of addresses who become parties in the contract. * @param contractAddress address of the contract against which the parties are registered. */ function registerContract(address[] calldata parties, address contractAddress) external override onlyRoleHolder(uint256(Roles.ContractCreator)) { FinancialContract storage financialContract = contractMap[contractAddress]; require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once"); // Store contract address as a registered contract. registeredContracts.push(contractAddress); // No length check necessary because we should never hit (2^127 - 1) contracts. financialContract.index = uint128(registeredContracts.length.sub(1)); // For all parties in the array add them to the contract's parties. financialContract.valid = Validity.Valid; for (uint256 i = 0; i < parties.length; i = i.add(1)) { _addPartyToContract(parties[i], contractAddress); } emit NewContractRegistered(contractAddress, msg.sender, parties); } /** * @notice Adds a party member to the calling contract. * @dev msg.sender will be used to determine the contract that this party is added to. * @param party new party for the calling contract. */ function addPartyToContract(address party) external override { address contractAddress = msg.sender; require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract"); _addPartyToContract(party, contractAddress); } /** * @notice Removes a party member from the calling contract. * @dev msg.sender will be used to determine the contract that this party is removed from. * @param partyAddress address to be removed from the calling contract. */ function removePartyFromContract(address partyAddress) external override { address contractAddress = msg.sender; Party storage party = partyMap[partyAddress]; uint256 numberOfContracts = party.contracts.length; require(numberOfContracts != 0, "Party has no contracts"); require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract"); require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party"); // Index of the current location of the contract to remove. uint256 deleteIndex = party.contractIndex[contractAddress]; // Store the last contract's address to update the lookup map. address lastContractAddress = party.contracts[numberOfContracts - 1]; // Swap the contract to be removed with the last contract. party.contracts[deleteIndex] = lastContractAddress; // Update the lookup index with the new location. party.contractIndex[lastContractAddress] = deleteIndex; // Pop the last contract from the array and update the lookup map. party.contracts.pop(); delete party.contractIndex[contractAddress]; emit PartyRemoved(contractAddress, partyAddress); } /**************************************** * REGISTRY STATE GETTERS * ****************************************/ /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the financial contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view override returns (bool) { return contractMap[contractAddress].valid == Validity.Valid; } /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view override returns (address[] memory) { return partyMap[party].contracts; } /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view override returns (address[] memory) { return registeredContracts; } /** * @notice checks if an address is a party of a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) { uint256 index = partyMap[party].contractIndex[contractAddress]; return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _addPartyToContract(address party, address contractAddress) internal { require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once"); uint256 contractIndex = partyMap[party].contracts.length; partyMap[party].contracts.push(contractAddress); partyMap[party].contractIndex[contractAddress] = contractIndex; emit PartyAdded(contractAddress, party); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for a registry of contracts and contract creators. */ interface RegistryInterface { /** * @notice Registers a new contract. * @dev Only authorized contract creators can call this method. * @param parties an array of addresses who become parties in the contract. * @param contractAddress defines the address of the deployed contract. */ function registerContract(address[] calldata parties, address contractAddress) external; /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view returns (bool); /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view returns (address[] memory); /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view returns (address[] memory); /** * @notice Adds a party to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be added to the contract. */ function addPartyToContract(address party) external; /** * @notice Removes a party member to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be removed from the contract. */ function removePartyFromContract(address party) external; /** * @notice checks if an address is a party in a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Liquidatable.sol"; /** * @title Expiring Multi Party. * @notice Convenient wrapper for Liquidatable. */ contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./PricelessPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Liquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. */ contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; address financialProductLibraryAddress; bytes32 priceFeedIdentifier; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPct; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPct; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPct; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.minSponsorTokens, params.timerAddress, params.financialProductLibraryAddress ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1), "CR must be more than 100%"); require( params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1), "Rewards are more than 100%" ); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPct = params.disputeBondPct; sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; disputerDisputeRewardPct = params.disputerDisputeRewardPct; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.PreDispute, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPct` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.PendingDispute; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePriceLiquidation(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.PreDispute) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /** * @notice Accessor method to calculate a transformed collateral requirement using the finanical product library specified during contract deployment. If no library was provided then no modification to the collateral requirement is done. * @param price input price used as an input to transform the collateral requirement. * @return transformedCollateralRequirement collateral requirement with transformation applied to it. * @dev This method should never revert. */ function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformCollateralRequirement(price); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return. // If the liquidation is in the PendingDispute state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == PendingDispute and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.PendingDispute) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform // Collateral requirement method applies a from the financial Product library to change the scaled the collateral // requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice)); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.PreDispute) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)), "Liquidation not withdrawable" ); } function _transformCollateralRequirement(FixedPoint.Unsigned memory price) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FeePayer.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PricelessPositionManager is FeePayer { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; using Address for address; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend // the functionality of the EMP to support a wider range of financial products. FinancialProductLibrary public financialProductLibrary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. * @param _financialProductLibraryAddress Contract providing contract state transformations. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _financialProductLibraryAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime()); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; // Initialize the financialProductLibrary at the provided address. financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ) ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime() ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp, "Request expires post-expiry"); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePriceExpiration(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // Final fees do not need to be paid when sending a request to the optimistic oracle. _requestOraclePriceExpiration(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress()); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePriceExpiration(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev TODO: This method does not account for any pending regular fees that have not yet been withdrawn * from this contract, for example if the `lastPaymentTime != currentTime`. Future work should be to add * logic to this method to account for any such pending fees. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getFeeAdjustedCollateral(positions[sponsor].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } /** * @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract * deployment. If no library was provided then no modification to the price is done. * @param price input price to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformPrice(price, requestTime); } /** * @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified * at contract deployment. If no library was provided then no modification to the identifier is done. * @param requestTime timestamp the identifier is to be used at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) { return _transformPriceIdentifier(requestTime); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceExpiration(uint256 requestedTime) internal { OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Increase token allowance to enable the optimistic oracle reward transfer. FixedPoint.Unsigned memory reward = _computeFinalFees(); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue); optimisticOracle.requestPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData(), collateralCurrency, reward.rawValue // Reward is equal to the final fee ); // Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee. _adjustCumulativeFeeMultiplier(reward, _pfc()); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.hasPrice( address(this), _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ), "Unresolved oracle price" ); int256 optimisticOraclePrice = optimisticOracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData()); // For now we don't want to deal with negative prices in positions. if (optimisticOraclePrice < 0) { optimisticOraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceLiquidation(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) { if (!address(financialProductLibrary).isContract()) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(address(tokenCurrency)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./ExpiringMultiPartyLib.sol"; /** * @title Expiring Multi Party Contract creator. * @notice Factory contract to create and register new instances of expiring multiparty contracts. * Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints * that are applied to newly created expiring multi party contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * EMP CREATOR DATA STRUCTURES * ****************************************/ struct Params { uint256 expirationTimestamp; address collateralAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; FixedPoint.Unsigned minSponsorTokens; uint256 withdrawalLiveness; uint256 liquidationLiveness; address financialProductLibraryAddress; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress); /** * @notice Constructs the ExpiringMultiPartyCreator contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of expiring multi party and registers it within the registry. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract. */ function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { // Create a new synthetic token using the params. require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, then a default precision of 18 will be // applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency)); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedExpiringMultiParty(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency) private view returns (ExpiringMultiParty.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); require(params.expirationTimestamp > now, "Invalid expiration time"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want EMP deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the EMP unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // Input from function call. constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.expirationTimestamp = params.expirationTimestamp; constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPct = params.disputeBondPct; constructorParams.sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; constructorParams.disputerDisputeRewardPct = params.disputerDisputeRewardPct; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ExpiringMultiParty.sol"; /** * @title Provides convenient Expiring Multi Party contract utilities. * @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode. */ library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ConfigStoreInterface.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it * to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded * by a privileged account and the upgraded changes are timelocked. */ contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /**************************************** * STORE DATA STRUCTURES * ****************************************/ // Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig // if its liveness has expired. ConfigStoreInterface.ConfigSettings private currentConfig; // Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config. ConfigStoreInterface.ConfigSettings public pendingConfig; uint256 public pendingPassedTimestamp; /**************************************** * EVENTS * ****************************************/ event ProposedNewConfigSettings( address indexed proposer, uint256 rewardRate, uint256 proposerBond, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit, uint256 proposalPassedTimestamp ); event ChangedConfigSettings( uint256 rewardRate, uint256 proposerBond, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit ); /**************************************** * MODIFIERS * ****************************************/ // Update config settings if possible. modifier updateConfig() { _updateConfig(); _; } /** * @notice Construct the Config Store. An initial configuration is provided and set on construction. * @param _initialConfig Configuration settings to initialize `currentConfig` with. * @param _timerAddress Address of testable Timer contract. */ constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) { _validateConfig(_initialConfig); currentConfig = _initialConfig; } /** * @notice Returns current config or pending config if pending liveness has expired. * @return ConfigSettings config settings that calling financial contract should view as "live". */ function updateAndGetCurrentConfig() external override updateConfig() nonReentrant() returns (ConfigStoreInterface.ConfigSettings memory) { return currentConfig; } /** * @notice Propose new configuration settings. New settings go into effect after a liveness period passes. * @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now. * @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal. */ function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() { _validateConfig(newConfig); // Warning: This overwrites a pending proposal! pendingConfig = newConfig; // Use current config's liveness period to timelock this proposal. pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness); emit ProposedNewConfigSettings( msg.sender, newConfig.rewardRatePerSecond.rawValue, newConfig.proposerBondPct.rawValue, newConfig.timelockLiveness, newConfig.maxFundingRate.rawValue, newConfig.minFundingRate.rawValue, newConfig.proposalTimePastLimit, pendingPassedTimestamp ); } /** * @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness. */ function publishPendingConfig() external nonReentrant() updateConfig() {} /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Check if pending proposal can overwrite the current config. function _updateConfig() internal { // If liveness has passed, publish proposed configuration settings. if (_pendingProposalPassed()) { currentConfig = pendingConfig; _deletePendingConfig(); emit ChangedConfigSettings( currentConfig.rewardRatePerSecond.rawValue, currentConfig.proposerBondPct.rawValue, currentConfig.timelockLiveness, currentConfig.maxFundingRate.rawValue, currentConfig.minFundingRate.rawValue, currentConfig.proposalTimePastLimit ); } } function _deletePendingConfig() internal { delete pendingConfig; pendingPassedTimestamp = 0; } function _pendingProposalPassed() internal view returns (bool) { return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime()); } // Use this method to constrain values with which you can set ConfigSettings. function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure { // We don't set limits on proposal timestamps because there are already natural limits: // - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints. // - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30 // mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time. // Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself // before a vulnerability drains its collateral. require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness"); // The reward rate should be modified as needed to incentivize honest proposers appropriately. // Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs // = 0.0000033 FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7); require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond"); // We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer // were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer // could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest // proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their // PfC for each proposal liveness window. The downside of not limiting this is that the config store owner // can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the // proposal bond based on the configuration's funding rate range like in this discussion: // https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383 // We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude // funding rates in extraordinarily volatile market situations. Note, that even though we do not bound // the max/min, we still recommend that the deployer of this contract set the funding rate max/min values // to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year]. } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./PerpetualLiquidatable.sol"; /** * @title Perpetual Multiparty Contract. * @notice Convenient wrapper for Liquidatable. */ contract Perpetual is PerpetualLiquidatable { /** * @notice Constructs the Perpetual contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualLiquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./PerpetualPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title PerpetualLiquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. */ contract PerpetualLiquidatable is PerpetualPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPct; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPct; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPct; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPct = params.disputeBondPct; sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; disputerDisputeRewardPct = params.disputerDisputeRewardPct; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external notEmergencyShutdown() fees() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.PreDispute, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated), lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPct` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.PendingDispute; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // TODO: Do we also need to apply some sort of funding rate adjustment to account for multiplier changes // since liquidation time? FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.PreDispute) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return. // If the liquidation is in the PendingDispute state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == PendingDispute and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.PendingDispute) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.PreDispute) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)), "Liquidation not withdrawable" ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FundingRateApplier.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PerpetualPositionManager is FundingRateApplier { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // Expiry price pulled from the DVM in the case of an emergency shutdown. FixedPoint.Unsigned public emergencyShutdownPrice; /**************************************** * EVENTS * ****************************************/ event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp); event SettleEmergencyShutdown( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); /**************************************** * MODIFIERS * ****************************************/ modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PerpetualPositionManager. * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract. * @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production. */ constructor( uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, bytes32 _fundingRateIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external notEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); // No pending withdrawal require message removed to save bytecode. require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount * ` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens)); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); // Note: revert reason removed to save bytecode. require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or * remaining collateral for underlying at the prevailing price defined by a DVM vote. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this * function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleEmergencyShutdown() external isEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert. if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) { emergencyShutdownPrice = _getOracleEmergencyShutdownPrice(); } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = _getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with // the funding rate applied to the outstanding token debt. FixedPoint.Unsigned memory tokenDebtValueInCollateral = _getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the `settleEmergencyShutdown` function. */ function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() { // Note: revert reason removed to save bytecode. require(msg.sender == _getFinancialContractsAdminAddress()); emergencyShutdownTimestamp = getCurrentTime(); _requestOraclePrice(emergencyShutdownTimestamp); emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev TODO: This method does not account for any pending regular fees that have not yet been withdrawn * from this contract, for example if the `lastPaymentTime != currentTime`. Future work should be to add * logic to this method to account for any such pending fees. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getFeeAdjustedCollateral(positions[sponsor].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the PerpetualPositionManager. * @return totalCollateral amount of all collateral within the position manager. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFundingRateAppliedTokenDebt(rawTokenDebt); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove); require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens)); // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { _getOracle().requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) { // Create an instance of the oracle and get the price. If the price is not resolved revert. int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) { return _getOraclePrice(emergencyShutdownTimestamp); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyCollateralizedPosition(address sponsor) internal view { require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0)); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens); } function _getTokenAddress() internal view override returns (address) { return address(tokenCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./PerpetualLib.sol"; import "./ConfigStore.sol"; /** * @title Perpetual Contract creator. * @notice Factory contract to create and register new instances of perpetual contracts. * Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints * that are applied to newly created contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract PerpetualCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * PERP CREATOR DATA STRUCTURES * ****************************************/ // Immutable params for perpetual contract. struct Params { address collateralAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; uint256 withdrawalLiveness; uint256 liquidationLiveness; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress); event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress); /** * @notice Constructs the Perpetual contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of perpetual and registers it within the registry. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed contract. */ function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings) public nonReentrant() returns (address) { require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); // Create new config settings store for this contract and reset ownership to the deployer. ConfigStore configStore = new ConfigStore(configSettings, timerAddress); configStore.transferOwnership(msg.sender); emit CreatedConfigStore(address(configStore), configStore.owner()); // Create a new synthetic token using the params. TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, // then a default precision of 18 will be applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore))); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedPerpetual(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createPerpetual params to Perpetual constructor params. function _convertParams( Params memory params, ExpandedIERC20 newTokenCurrency, address configStore ) private view returns (Perpetual.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want perpetual deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the perpetual unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // To avoid precision loss or overflows, prevent the token scaling from being too large or too small. FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10 FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10 require( params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling), "Invalid tokenScaling" ); // Input from function call. constructorParams.configStoreAddress = configStore; constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.fundingRateIdentifier = params.fundingRateIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPct = params.disputeBondPct; constructorParams.sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; constructorParams.disputerDisputeRewardPct = params.disputerDisputeRewardPct; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.tokenScaling = params.tokenScaling; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Perpetual.sol"; /** * @title Provides convenient Perpetual Multi Party contract utilities. * @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode. */ library PerpetualLib { /** * @notice Returns address of new Perpetual deployed with given `params` configuration. * @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed Perpetual contract */ function deploy(Perpetual.ConstructorParams memory params) public returns (address) { Perpetual derivative = new Perpetual(params); return address(derivative); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; contract ExpiringMultiPartyMock is Testable { using FixedPoint for FixedPoint.Unsigned; FinancialProductLibrary public financialProductLibrary; uint256 public expirationTimestamp; FixedPoint.Unsigned public collateralRequirement; bytes32 public priceIdentifier; constructor( address _financialProductLibraryAddress, uint256 _expirationTimestamp, FixedPoint.Unsigned memory _collateralRequirement, bytes32 _priceIdentifier, address _timerAddress ) public Testable(_timerAddress) { expirationTimestamp = _expirationTimestamp; collateralRequirement = _collateralRequirement; financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); priceIdentifier = _priceIdentifier; } function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) { if (address(financialProductLibrary) == address(0)) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; // Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations. contract FinancialProductLibraryTest is FinancialProductLibrary { FixedPoint.Unsigned public priceTransformationScalar; FixedPoint.Unsigned public collateralRequirementTransformationScalar; bytes32 public transformedPriceIdentifier; bool public shouldRevert; constructor( FixedPoint.Unsigned memory _priceTransformationScalar, FixedPoint.Unsigned memory _collateralRequirementTransformationScalar, bytes32 _transformedPriceIdentifier ) public { priceTransformationScalar = _priceTransformationScalar; collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar; transformedPriceIdentifier = _transformedPriceIdentifier; } // Set the mocked methods to revert to test failed library computation. function setShouldRevert(bool _shouldRevert) public { shouldRevert = _shouldRevert; } // Create a simple price transformation function that scales the input price by the scalar for testing. function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return oraclePrice.mul(priceTransformationScalar); } // Create a simple collateral requirement transformation that doubles the input collateralRequirement. function transformCollateralRequirement( FixedPoint.Unsigned memory price, FixedPoint.Unsigned memory collateralRequirement ) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return collateralRequirement.mul(collateralRequirementTransformationScalar); } // Create a simple transformPriceIdentifier function that returns the transformed price identifier. function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view override returns (bytes32) { require(!shouldRevert, "set to always reverts"); return transformedPriceIdentifier; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/FundingRateApplier.sol"; import "../../common/implementation/FixedPoint.sol"; // Implements FundingRateApplier internal methods to enable unit testing. contract FundingRateApplierTest is FundingRateApplier { constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) {} function calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) public pure returns (FixedPoint.Unsigned memory) { return _calculateEffectiveFundingRate( paymentPeriodSeconds, fundingRatePerSecond, currentCumulativeFundingRateMultiplier ); } // Required overrides. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) { return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); } function emergencyShutdown() external override {} function remargin() external override {} function _getTokenAddress() internal view override returns (address) { return address(collateralCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Used internally by Truffle migrations. * @dev See https://www.trufflesuite.com/docs/truffle/getting-started/running-migrations#initial-migration for details. */ contract Migrations { address public owner; uint256 public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint256 completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../interfaces/VotingInterface.sol"; import "../interfaces/FinderInterface.sol"; import "./Constants.sol"; /** * @title Proxy to allow voting from another address. * @dev Allows a UMA token holder to designate another address to vote on their behalf. * Each voter must deploy their own instance of this contract. */ contract DesignatedVoting is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the Voter role. Is also permanently permissioned as the minter role. Voter // Can vote through this contract. } // Reference to the UMA Finder contract, allowing Voting upgrades to be performed // without requiring any calls to this contract. FinderInterface private finder; /** * @notice Construct the DesignatedVoting contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. * @param ownerAddress address of the owner of the DesignatedVoting contract. * @param voterAddress address to which the owner has delegated their voting power. */ constructor( address finderAddress, address ownerAddress, address voterAddress ) public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress); _createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress); _setWithdrawRole(uint256(Roles.Owner)); finder = FinderInterface(finderAddress); } /**************************************** * VOTING AND REWARD FUNCTIONALITY * ****************************************/ /** * @notice Forwards a commit to Voting. * @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param hash the keccak256 hash of the price you want to vote for and a random integer salt value. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingInterface.Commitment[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchCommit(commits); } /** * @notice Forwards a reveal to Voting. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price used along with the `salt` to produce the `hash` during the commit phase. * @param salt used along with the `price` to produce the `hash` during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, salt); } /** * @notice Forwards a batch reveal to Voting. * @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(VotingInterface.Reveal[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchReveal(reveals); } /** * @notice Forwards a reward retrieval to Voting. * @dev Rewards are added to the tokens already held by this contract. * @param roundId defines the round from which voting rewards will be retrieved from. * @param toRetrieve an array of PendingRequests which rewards are retrieved from. * @return amount of rewards that the user should receive. */ function retrieveRewards(uint256 roundId, VotingInterface.PendingRequest[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingInterface) { return VotingInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "./VotingAncillaryInterface.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingInterface { struct PendingRequest { bytes32 identifier; uint256 time; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint256 time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint256 time; int256 price; int256 salt; } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (VotingAncillaryInterface.PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingAncillaryInterface { struct PendingRequestAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct CommitmentAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct RevealAncillary { bytes32 identifier; uint256 time; int256 price; bytes ancillaryData; int256 salt; } // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. // `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last. enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Withdrawable.sol"; import "./DesignatedVoting.sol"; /** * @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances. * @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract. */ contract DesignatedVotingFactory is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract. } address private finder; mapping(address => DesignatedVoting) public designatedVotingContracts; /** * @notice Construct the DesignatedVotingFactory contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. */ constructor(address finderAddress) public { finder = finderAddress; _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender); } /** * @notice Deploys a new `DesignatedVoting` contract. * @param ownerAddress defines who will own the deployed instance of the designatedVoting contract. * @return designatedVoting a new DesignatedVoting contract. */ function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) { require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted"); DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender); designatedVotingContracts[msg.sender] = designatedVoting; return designatedVoting; } /** * @notice Associates a `DesignatedVoting` instance with `msg.sender`. * @param designatedVotingAddress address to designate voting to. * @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter` * address and wants that reflected here. */ function setDesignatedVoting(address designatedVotingAddress) external { require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted"); designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/AdministrateeInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Admin for financial contracts in the UMA system. * @dev Allows appropriately permissioned admin roles to interact with financial contracts. */ contract FinancialContractsAdmin is Ownable { /** * @notice Calls emergency shutdown on the provided financial contract. * @param financialContract address of the FinancialContract to be shut down. */ function callEmergencyShutdown(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.emergencyShutdown(); } /** * @notice Calls remargin on the provided financial contract. * @param financialContract address of the FinancialContract to be remargined. */ function callRemargin(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.remargin(); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/FinderInterface.sol"; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces. */ contract Finder is FinderInterface, Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external override onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external view override returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "Implementation not found"); return implementationAddress; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OracleInterface.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Takes proposals for certain governance actions and allows UMA token holders to vote on them. */ contract Governor is MultiRole, Testable { using SafeMath for uint256; using Address for address; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. } struct Transaction { address to; uint256 value; bytes data; } struct Proposal { Transaction[] transactions; uint256 requestTime; } FinderInterface private finder; Proposal[] public proposals; /**************************************** * EVENTS * ****************************************/ // Emitted when a new proposal is created. event NewProposal(uint256 indexed id, Transaction[] transactions); // Emitted when an existing proposal is executed. event ProposalExecuted(uint256 indexed id, uint256 transactionIndex); /** * @notice Construct the Governor contract. * @param _finderAddress keeps track of all contracts within the system based on their interfaceName. * @param _startingId the initial proposal id that the contract will begin incrementing from. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _finderAddress, uint256 _startingId, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender); // Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite // other storage slots in the contract. uint256 maxStartingId = 10**18; require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18"); // This just sets the initial length of the array to the startingId since modifying length directly has been // disallowed in solidity 0.6. assembly { sstore(proposals_slot, _startingId) } } /**************************************** * PROPOSAL ACTIONS * ****************************************/ /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that * disallows structs arrays to be passed to external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) { uint256 id = proposals.length; uint256 time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add a zero-initialized element to the proposals array. proposals.push(); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. for (uint256 i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The `to` address cannot be 0x0"); // If the transaction has any data with it the recipient must be a contract, not an EOA. if (transactions[i].data.length > 0) { require(transactions[i].to.isContract(), "EOA can't accept tx with data"); } proposal.transactions.push(transactions[i]); } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. OracleInterface oracle = _getOracle(); IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist(); supportedIdentifiers.addSupportedIdentifier(identifier); oracle.requestPrice(identifier, time); supportedIdentifiers.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } /** * @notice Executes a proposed governance action that has been approved by voters. * @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions. * @param id unique id for the executed proposal. * @param transactionIndex unique transaction index for the executed proposal. */ function executeProposal(uint256 id, uint256 transactionIndex) external payable { Proposal storage proposal = proposals[id]; int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction memory transaction = proposal.transactions[transactionIndex]; require( transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous tx not yet executed" ); require(transaction.to != address(0), "Tx already executed"); require(price != 0, "Proposal was rejected"); require(msg.value == transaction.value, "Must send exact amount of ETH"); // Delete the transaction before execution to avoid any potential re-entrancy issues. delete proposal.transactions[transactionIndex]; require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed"); emit ProposalExecuted(id, transactionIndex); } /**************************************** * GOVERNOR STATE GETTERS * ****************************************/ /** * @notice Gets the total number of proposals (includes executed and non-executed). * @return uint256 representing the current number of proposals. */ function numProposals() external view returns (uint256) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * @dev after a proposal is executed, its data will be zeroed out, except for the request time. * @param id uniquely identify the identity of the proposal. * @return proposal struct containing transactions[] and requestTime. */ function getProposal(uint256 id) external view returns (Proposal memory) { return proposals[id]; } /**************************************** * PRIVATE GETTERS AND FUNCTIONS * ****************************************/ function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly bool success; assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } return success; } function _getOracle() private view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Returns a UTF-8 identifier representing a particular admin proposal. // The identifier is of the form "Admin n", where n is the proposal id provided. function _constructIdentifier(uint256 id) internal pure returns (bytes32) { bytes32 bytesId = _uintToUtf8(id); return _addPrefix(bytesId, "Admin ", 6); } // This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type. // If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits. // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToUtf8(uint256 v) internal pure returns (bytes32) { bytes32 ret; if (v == 0) { // Handle 0 case explicitly. ret = "0"; } else { // Constants. uint256 bitsPerByte = 8; uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10. uint256 utf8NumberOffset = 48; while (v > 0) { // Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which // translates to the beginning of the UTF-8 representation. ret = ret >> bitsPerByte; // Separate the last digit that remains in v by modding by the base of desired output representation. uint256 leastSignificantDigit = v % base; // Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character. bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset); // The top byte of ret has already been cleared to make room for the new digit. // Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched. ret |= utf8Digit << (31 * bitsPerByte); // Divide v by the base to remove the digit that was just added. v /= base; } } return ret; } // This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. // `input` is the UTF-8 that should have the prefix prepended. // `prefix` is the UTF-8 that should be prepended onto input. // `prefixLength` is number of UTF-8 characters represented by `prefix`. // Notes: // 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented // by the bytes32 output. // 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result. function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) internal pure returns (bytes32) { // Downshift `input` to open space at the "front" of the bytes32 bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/IdentifierWhitelistInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Stores a whitelist of supported identifiers that the oracle can provide prices for. */ contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ mapping(bytes32 => bool) private supportedIdentifiers; /**************************************** * EVENTS * ****************************************/ event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } /**************************************** * WHITELIST GETTERS FUNCTIONS * ****************************************/ /** * @notice Checks whether an identifier is on the whitelist. * @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view override returns (bool) { return supportedIdentifiers[identifier]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/StoreInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OptimisticOracleInterface.sol"; import "./Constants.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/AddressWhitelist.sol"; /** * @title Optimistic Requester. * @notice Optional interface that requesters can implement to receive callbacks. */ interface OptimisticRequester { /** * @notice Callback for proposals. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. */ function priceProposed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external; /** * @notice Callback for disputes. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param refund refund received in the case that refundOnDispute was enabled. */ function priceDisputed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 refund ) external; /** * @notice Callback for settlement. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param price price that was resolved by the escalation process. */ function priceSettled( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 price ) external; } /** * @title Optimistic Oracle. * @notice Pre-DVM escalation contract that allows faster settlement. */ contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; event RequestPrice( address indexed requester, bytes32 identifier, uint256 timestamp, bytes ancillaryData, address currency, uint256 reward, uint256 finalFee ); event ProposePrice( address indexed requester, address indexed proposer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice ); event DisputePrice( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData ); event Settle( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 price, uint256 payout ); mapping(bytes32 => Request) public requests; // Finder to provide addresses for DVM contracts. FinderInterface public finder; // Default liveness value for all price requests. uint256 public defaultLiveness; /** * @notice Constructor. * @param _liveness default liveness applied to each price request. * @param _finderAddress finder to use to get addresses of DVM contracts. * @param _timerAddress address of the timer contract. Should be 0x0 in prod. */ constructor( uint256 _liveness, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _validateLiveness(_liveness); defaultLiveness = _liveness; } /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier"); require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency"); require(timestamp <= getCurrentTime(), "Timestamp in future"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue; requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({ proposer: address(0), disputer: address(0), currency: currency, settled: false, refundOnDispute: false, proposedPrice: 0, resolvedPrice: 0, expirationTime: 0, reward: reward, finalFee: finalFee, bond: finalFee, customLiveness: 0 }); if (reward > 0) { currency.safeTransferFrom(msg.sender, address(this), reward); } emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee); // This function returns the initial proposal bond for this request, which can be customized by calling // setBond() with the same identifier and timestamp. return finalFee.mul(2); } /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested"); Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData); request.bond = bond; // Total bond is the final fee + the newly set bond. return bond.add(request.finalFee); } /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setRefundOnDispute: Requested" ); _getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true; } /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setCustomLiveness: Requested" ); _validateLiveness(customLiveness); _getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness; } /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public override nonReentrant() returns (uint256 totalBond) { require(proposer != address(0), "proposer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Requested, "proposePriceFor: Requested" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.proposer = proposer; request.proposedPrice = proposedPrice; // If a custom liveness has been set, use it instead of the default. request.expirationTime = getCurrentTime().add( request.customLiveness != 0 ? request.customLiveness : defaultLiveness ); totalBond = request.bond.add(request.finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } // Event. emit ProposePrice(requester, proposer, identifier, timestamp, ancillaryData, proposedPrice); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {} } /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice); } /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public override nonReentrant() returns (uint256 totalBond) { require(disputer != address(0), "disputer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Proposed, "disputePriceFor: Proposed" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.disputer = disputer; uint256 finalFee = request.finalFee; totalBond = request.bond.add(finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } StoreInterface store = _getStore(); if (finalFee > 0) { request.currency.safeIncreaseAllowance(address(store), finalFee); _getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(finalFee)); } _getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)); // Compute refund. uint256 refund = 0; if (request.reward > 0 && request.refundOnDispute) { refund = request.reward; request.reward = 0; request.currency.safeTransfer(requester, refund); } // Event. emit DisputePrice(requester, request.proposer, disputer, identifier, timestamp, ancillaryData); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {} } /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData); } /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function getPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (int256) { if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) { _settle(msg.sender, identifier, timestamp, ancillaryData); } return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice; } /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (uint256 payout) { return _settle(requester, identifier, timestamp, ancillaryData); } /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (Request memory) { return _getRequest(requester, identifier, timestamp, ancillaryData); } /** * @notice Computes the current state of a price request. See the State enum for more details. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (State) { Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); if (address(request.currency) == address(0)) { return State.Invalid; } if (request.proposer == address(0)) { return State.Requested; } if (request.settled) { return State.Settled; } if (request.disputer == address(0)) { return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed; } return _getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)) ? State.Resolved : State.Disputed; } /** * @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return boolean indicating true if price exists and false if not. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (bool) { State state = getState(requester, identifier, timestamp, ancillaryData); return state == State.Settled || state == State.Resolved || state == State.Expired; } /** * @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute. * @param ancillaryData ancillary data of the price being requested. * @param requester sender of the initial price request. * @return the stampped ancillary bytes. */ function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) { return _stampAncillaryData(ancillaryData, requester); } function _getId( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData)); } function _settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private returns (uint256 payout) { State state = getState(requester, identifier, timestamp, ancillaryData); // Set it to settled so this function can never be entered again. Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.settled = true; if (state == State.Expired) { // In the expiry case, just pay back the proposer's bond and final fee along with the reward. request.resolvedPrice = request.proposedPrice; payout = request.bond.add(request.finalFee).add(request.reward); request.currency.safeTransfer(request.proposer, payout); } else if (state == State.Resolved) { // In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward). request.resolvedPrice = _getOracle().getPrice( identifier, timestamp, _stampAncillaryData(ancillaryData, requester) ); bool disputeSuccess = request.resolvedPrice != request.proposedPrice; payout = request.bond.mul(2).add(request.finalFee).add(request.reward); request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout); } else { revert("_settle: not settleable"); } // Event. emit Settle( requester, request.proposer, request.disputer, identifier, timestamp, ancillaryData, request.resolvedPrice, payout ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice) {} catch {} } function _getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private view returns (Request storage) { return requests[_getId(requester, identifier, timestamp, ancillaryData)]; } function _validateLiveness(uint256 _liveness) private pure { require(_liveness < 5200 weeks, "Liveness too large"); require(_liveness > 0, "Liveness cannot be 0"); } function _getOracle() internal view returns (OracleAncillaryInterface) { return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getCollateralWhitelist() internal view returns (AddressWhitelist) { return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); } function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it. function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) { return abi.encodePacked(ancillaryData, "OptimisticOracle", requester); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleAncillaryInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param time unix timestamp for the price request. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/FixedPoint.sol"; /** * @title Computes vote results. * @dev The result is the mode of the added votes. Otherwise, the vote is unresolved. */ library ResultComputation { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL LIBRARY DATA STRUCTURE * ****************************************/ struct Data { // Maps price to number of tokens that voted for that price. mapping(int256 => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int256 currentMode; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Adds a new vote to be used when computing the result. * @param data contains information to which the vote is applied. * @param votePrice value specified in the vote for the given `numberTokens`. * @param numberTokens number of tokens that voted on the `votePrice`. */ function addVote( Data storage data, int256 votePrice, FixedPoint.Unsigned memory numberTokens ) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if ( votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode]) ) { data.currentMode = votePrice; } } /**************************************** * VOTING STATE GETTERS * ****************************************/ /** * @notice Returns whether the result is resolved, and if so, what value it resolved to. * @dev `price` should be ignored if `isResolved` is false. * @param data contains information against which the `minVoteThreshold` is applied. * @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. * @return isResolved indicates if the price has been resolved correctly. * @return price the price that the dvm resolved to. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int256 price) { FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if ( data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold) ) { // `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @notice Checks whether a `voteHash` is considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains information against which the `voteHash` is checked. * @param voteHash committed hash submitted by the voter. * @return bool true if the vote was correct. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @notice Gets the total number of tokens whose votes are considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains all votes against which the correctly voted tokens are counted. * @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/StoreInterface.sol"; /** * @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token. */ contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) public Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable override { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK)); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Governor.sol"; // GovernorTest exposes internal methods in the Governor for testing. contract GovernorTest is Governor { constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {} function addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) external pure returns (bytes32) { return _addPrefix(input, prefix, prefixLength); } function uintToUtf8(uint256 v) external pure returns (bytes32 ret) { return _uintToUtf8(v); } function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) { return _constructIdentifier(id); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/AdministrateeInterface.sol"; // A mock implementation of AdministrateeInterface, taking the place of a financial contract. contract MockAdministratee is AdministrateeInterface { uint256 public timesRemargined; uint256 public timesEmergencyShutdown; function remargin() external override { timesRemargined++; } function emergencyShutdown() external override { timesEmergencyShutdown++; } function pfc() external view override returns (FixedPoint.Unsigned memory) { return FixedPoint.fromUnscaledUint(0); } } // SPDX-License-Identifier: AGPL-3.0-only import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../OptimisticOracle.sol"; // This is just a test contract to make requests to the optimistic oracle. contract OptimisticRequesterTest is OptimisticRequester { OptimisticOracle optimisticOracle; bool public shouldRevert = false; // State variables to track incoming calls. bytes32 public identifier; uint256 public timestamp; bytes public ancillaryData; uint256 public refund; int256 public price; constructor(OptimisticOracle _optimisticOracle) public { optimisticOracle = _optimisticOracle; } function requestPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, IERC20 currency, uint256 reward ) external { currency.approve(address(optimisticOracle), reward); optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward); } function getPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external returns (int256) { return optimisticOracle.getPrice(_identifier, _timestamp, _ancillaryData); } function setBond( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 bond ) external { optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond); } function setRefundOnDispute( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external { optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData); } function setCustomLiveness( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 customLiveness ) external { optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness); } function setRevert(bool _shouldRevert) external { shouldRevert = _shouldRevert; } function clearState() external { delete identifier; delete timestamp; delete refund; delete price; } function priceProposed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; } function priceDisputed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 _refund ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; refund = _refund; } function priceSettled( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, int256 _price ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; price = _price; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ResultComputation.sol"; import "../../../common/implementation/FixedPoint.sol"; // Wraps the library ResultComputation for testing purposes. contract ResultComputationTest { using ResultComputation for ResultComputation.Data; ResultComputation.Data public data; function wrapAddVote(int256 votePrice, uint256 numberTokens) external { data.addVote(votePrice, FixedPoint.Unsigned(numberTokens)); } function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) { return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold)); } function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) { return data.wasVoteCorrect(revealHash); } function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) { return data.getTotalCorrectlyVotedTokens().rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../interfaces/VotingInterface.sol"; import "../VoteTiming.sol"; // Wraps the library VoteTiming for testing purposes. contract VoteTimingTest { using VoteTiming for VoteTiming.Data; VoteTiming.Data public voteTiming; constructor(uint256 phaseLength) public { wrapInit(phaseLength); } function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) { return voteTiming.computeCurrentRoundId(currentTime); } function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) { return voteTiming.computeCurrentPhase(currentTime); } function wrapInit(uint256 phaseLength) public { voteTiming.init(phaseLength); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/VotingInterface.sol"; /** * @title Library to compute rounds and phases for an equal length commit-reveal voting cycle. */ library VoteTiming { using SafeMath for uint256; struct Data { uint256 phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input. */ function init(Data storage data, uint256 phaseLength) internal { // This should have a require message but this results in an internal Solidity error. require(phaseLength > 0); data.phaseLength = phaseLength; } /** * @notice Computes the roundID based off the current time as floor(timestamp/roundLength). * @dev The round ID depends on the global timestamp but not on the lifetime of the system. * The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return roundId defined as a function of the currentTime and `phaseLength` from `data`. */ function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return currentTime.div(roundLength); } /** * @notice compute the round end time as a function of the round Id. * @param data input data object. * @param roundId uniquely identifies the current round. * @return timestamp unix time of when the current round will end. */ function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); } /** * @notice Computes the current phase based only on the current time. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return current voting phase based on current time and vote phases configuration. */ function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingAncillaryInterface.Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return VotingAncillaryInterface.Phase( currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Voting.sol"; import "../../../common/implementation/FixedPoint.sol"; // Test contract used to access internal variables in the Voting contract. contract VotingTest is Voting { constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Voting( _phaseLength, _gatPercentage, _inflationRate, _rewardsExpirationTimeout, _votingToken, _finder, _timerAddress ) {} function getPendingPriceRequestsArray() external view returns (bytes32[] memory) { return pendingPriceRequests; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "./Registry.sol"; import "./ResultComputation.sol"; import "./VoteTiming.sol"; import "./VotingToken.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; /** * @title Voting system for Oracle. * @dev Handles receiving and resolving price requests via a commit-reveal voting scheme. */ contract Voting is Testable, Ownable, OracleInterface, OracleAncillaryInterface, // Interface to support ancillary data with price requests. VotingInterface, VotingAncillaryInterface // Interface to support ancillary data with voting rounds. { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; /**************************************** * VOTING DATA STRUCTURES * ****************************************/ // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; bytes ancillaryData; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } /**************************************** * INTERNAL TRACKING * ****************************************/ // Maps round numbers to the rounds. mapping(uint256 => Round) public rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. // These requests may be for future rounds. bytes32[] internal pendingPriceRequests; VoteTiming.Data public voteTiming; // Percentage of the total token supply that must be used in a vote to // create a valid price resolution. 1 == 100%. FixedPoint.Unsigned public gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. // Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%. FixedPoint.Unsigned public inflationRate; // Time in seconds from the end of the round in which a price request is // resolved that voters can still claim their rewards. uint256 public rewardsExpirationTimeout; // Reference to the voting token. VotingToken public votingToken; // Reference to the Finder. FinderInterface private finder; // If non-zero, this contract has been migrated to this address. All voters and // financial contracts should query the new address only. address public migratedAddress; // Max value of an unsigned integer. uint256 private constant UINT_MAX = ~uint256(0); // Max length in bytes of ancillary data that can be appended to a price request. // As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily // comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to // storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function // well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here: // - https://etherscan.io/chart/gaslimit // - https://github.com/djrtwo/evm-opcode-gas-costs uint256 public constant ancillaryBytesLimit = 8192; bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot"))); /*************************************** * EVENTS * ****************************************/ event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); /** * @notice Construct the Voting contract. * @param _phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution. * @param _inflationRate percentage inflation per round used to increase token supply of correct voters. * @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed. * @param _votingToken address of the UMA token contract used to commit votes. * @param _finder keeps track of all contracts within the system based on their interfaceName. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Testable(_timerAddress) { voteTiming.init(_phaseLength); require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%"); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = FinderInterface(_finder); rewardsExpirationTimeout = _rewardsExpirationTimeout; } /*************************************** MODIFIERS ****************************************/ modifier onlyRegisteredContract() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Caller must be migrated address"); } else { Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Called must be registered"); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0), "Only call this if not migrated"); _; } /**************************************** * PRICE REQUEST AND ACCESS FUNCTIONS * ****************************************/ /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. The length of the ancillary data * is limited such that this method abides by the EVM transaction gas limit. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override onlyRegisteredContract() { uint256 blockTime = getCurrentTime(); require(time <= blockTime, "Can only request in past"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.NotRequested) { // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint256 nextRoundId = currentRoundId.add(1); priceRequests[priceRequestId] = PriceRequest({ identifier: identifier, time: time, lastVotingRound: nextRoundId, index: pendingPriceRequests.length, ancillaryData: ancillaryData }); pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function requestPrice(bytes32 identifier, uint256 time) public override { requestPrice(identifier, time, ""); } /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (bool) { (bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData); return _hasPrice; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { return hasPrice(identifier, time, ""); } /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (int256) { (bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData); // If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { return getPrice(identifier, time, ""); } /** * @notice Gets the status of a list of price requests, identified by their identifier and time. * @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0. * @param requests array of type PendingRequest which includes an identifier and timestamp for each request. * @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests. */ function getPriceRequestStatuses(PendingRequestAncillary[] memory requests) public view returns (RequestState[] memory) { RequestState[] memory requestStates = new RequestState[](requests.length); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); for (uint256 i = 0; i < requests.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData); RequestStatus status = _getRequestStatus(priceRequest, currentRoundId); // If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated. if (status == RequestStatus.Active) { requestStates[i].lastVotingRound = currentRoundId; } else { requestStates[i].lastVotingRound = priceRequest.lastVotingRound; } requestStates[i].status = status; } return requestStates; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) { PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length); for (uint256 i = 0; i < requests.length; i++) { requestsAncillary[i].identifier = requests[i].identifier; requestsAncillary[i].time = requests[i].time; requestsAncillary[i].ancillaryData = ""; } return getPriceRequestStatuses(requestsAncillary); } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public override onlyIfNotMigrated() { require(hash != bytes32(0), "Invalid provided hash"); // Current time is required for all vote timing queries. uint256 blockTime = getCurrentTime(); require( voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit, "Cannot commit in reveal phase" ); // At this point, the computed and last updated round ID should be equal. uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) public override onlyIfNotMigrated() { commitVote(identifier, time, "", hash); } /** * @notice Snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times, but only the first call per round into this function or `revealVote` * will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external override(VotingInterface, VotingAncillaryInterface) onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase"); // Require public snapshot require signature to ensure caller is an EOA. require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender"); uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); _freezeRoundVariables(roundId); } /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price voted on during the commit phase. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public override onlyIfNotMigrated() { require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase"); // Note: computing the current round is required to disallow people from revealing an old commit after the round is over. uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // Scoping to get rid of a stack too deep error. { // 0 hashes are disallowed in the commit phase, so they indicate a different error. // Cannot reveal an uncommitted or previously revealed hash require(voteSubmission.commit != bytes32(0), "Invalid hash reveal"); require( keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) == voteSubmission.commit, "Revealed data != commit hash" ); // To protect against flash loans, we require snapshot be validated as EOA. require(rounds[roundId].snapshotId != 0, "Round has no snapshot"); } // Get the frozen snapshotId uint256 snapshotId = rounds[roundId].snapshotId; delete voteSubmission.commit; // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public override { revealVote(identifier, time, price, "", salt); } /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, ancillaryData, hash); uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, "", hash); commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote); } /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash, commits[i].encryptedVote ); } } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchCommit(Commitment[] memory commits) public override { CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length); for (uint256 i = 0; i < commits.length; i++) { commitsAncillary[i].identifier = commits[i].identifier; commitsAncillary[i].time = commits[i].time; commitsAncillary[i].ancillaryData = ""; commitsAncillary[i].hash = commits[i].hash; commitsAncillary[i].encryptedVote = commits[i].encryptedVote; } batchCommit(commitsAncillary); } /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more info on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public override { for (uint256 i = 0; i < reveals.length; i++) { revealVote( reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].ancillaryData, reveals[i].salt ); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchReveal(Reveal[] memory reveals) public override { RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length); for (uint256 i = 0; i < reveals.length; i++) { revealsAncillary[i].identifier = reveals[i].identifier; revealsAncillary[i].time = reveals[i].time; revealsAncillary[i].price = reveals[i].price; revealsAncillary[i].ancillaryData = ""; revealsAncillary[i].salt = reveals[i].salt; } batchReveal(revealsAncillary); } /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold * (not expired). Note that a named return value is used here to avoid a stack to deep error. * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return totalRewardToIssue total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Can only call from migrated"); } require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId"); Round storage round = rounds[roundId]; bool isExpired = getCurrentTime() > round.rewardsExpirationTime; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId)); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId)); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint256 i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; // Only retrieve rewards for votes resolved in same round require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) { continue; } else if (isExpired) { // Emit a 0 token retrieval on expired rewards. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } else if ( voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash) ) { // The price was successfully resolved during the voter's last voting round, the voter revealed // and was correct, so they are eligible for a reward. // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div( voteInstance.resultComputation.getTotalCorrectlyVotedTokens() ); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, reward.rawValue ); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed"); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory) { PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length); for (uint256 i = 0; i < toRetrieve.length; i++) { toRetrieveAncillary[i].identifier = toRetrieve[i].identifier; toRetrieveAncillary[i].time = toRetrieve[i].time; toRetrieveAncillary[i].ancillaryData = ""; } return retrieveRewards(voterAddress, roundId, toRetrieveAncillary); } /**************************************** * VOTING GETTER FUNCTIONS * ****************************************/ /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests array containing identifiers of type `PendingRequest`. * and timestamps for all pending requests. */ function getPendingRequests() external view override(VotingInterface, VotingAncillaryInterface) returns (PendingRequestAncillary[] memory) { uint256 blockTime = getCurrentTime(); uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that have an Active RequestStatus. PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length); uint256 numUnresolved = 0; for (uint256 i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequestAncillary({ identifier: priceRequest.identifier, time: priceRequest.time, ancillaryData: priceRequest.ancillaryData }); numUnresolved++; } } PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved); for (uint256 i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } return pendingRequests; } /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } /**************************************** * OWNER ADMIN FUNCTIONS * ****************************************/ /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external override(VotingInterface, VotingAncillaryInterface) onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { inflationRate = newInflationRate; } /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%"); gatPercentage = newGatPercentage; } /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { rewardsExpirationTimeout = NewRewardsExpirationTimeout; } /**************************************** * PRIVATE AND INTERNAL FUNCTIONS * ****************************************/ // Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent // the resolved price and a string which is filled with an error message, if there was an error or "". function _getPriceOrError( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns ( bool, int256, string memory ) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "Current voting round not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price is still to be voted on"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)]; } function _encodePriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time, ancillaryData)); } function _freezeRoundVariables(uint256 roundId) private { Round storage round = rounds[roundId]; // Only on the first reveal should the snapshot be captured for that round. if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); // Set the round inflation rate to the current global inflation rate. rounds[roundId].inflationRate = inflationRate; // Set the round gat percentage to the current global gat rate. rounds[roundId].gatPercentage = gatPercentage; // Set the rewards expiration time based on end of time of this round and the current global timeout. rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add( rewardsExpirationTimeout ); } } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); require(isResolved, "Can't resolve unresolved request"); // Delete the resolved price request from pendingPriceRequests. uint256 lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; pendingPriceRequests.pop(); priceRequest.index = UINT_MAX; emit PriceResolved( priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice, priceRequest.ancillaryData ); } function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) { uint256 snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(rounds[roundId].gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol"; /** * @title Ownership of this token allows a voter to respond to price requests. * @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards. */ contract VotingToken is ExpandedERC20, ERC20Snapshot { /** * @notice Constructs the VotingToken. * stonkbase.org * tw StonkBase */ constructor() public ExpandedERC20("StonkBase", "SBF", 18) {} /** * @notice Creates a new snapshot ID. * @return uint256 Thew new snapshot ID. */ function snapshot() external returns (uint256) { return _snapshot(); } // _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot, // therefore the compiler will complain that VotingToken must override these methods // because the two base classes (ERC20 and ERC20Snapshot) both define the same functions function _transfer( address from, address to, uint256 value ) internal override(ERC20, ERC20Snapshot) { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._mint(account, value); } function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._burn(account, value); } } 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(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal virtual override { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } 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]; } } } 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; } } } 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); } } 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); } } pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ 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)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "./VotingToken.sol"; /** * @title Migration contract for VotingTokens. * @dev Handles migrating token holders from one token to the next. */ contract TokenMigrator { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ VotingToken public oldToken; ExpandedIERC20 public newToken; uint256 public snapshotId; FixedPoint.Unsigned public rate; mapping(address => bool) public hasMigrated; /** * @notice Construct the TokenMigrator contract. * @dev This function triggers the snapshot upon which all migrations will be based. * @param _rate the number of old tokens it takes to generate one new token. * @param _oldToken address of the token being migrated from. * @param _newToken address of the token being migrated to. */ constructor( FixedPoint.Unsigned memory _rate, address _oldToken, address _newToken ) public { // Prevents division by 0 in migrateTokens(). // Also it doesn’t make sense to have “0 old tokens equate to 1 new token”. require(_rate.isGreaterThan(0), "Rate can't be 0"); rate = _rate; newToken = ExpandedIERC20(_newToken); oldToken = VotingToken(_oldToken); snapshotId = oldToken.snapshot(); } /** * @notice Migrates the tokenHolder's old tokens to new tokens. * @dev This function can only be called once per `tokenHolder`. Anyone can call this method * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier. * @param tokenHolder address of the token holder to migrate. */ function migrateTokens(address tokenHolder) external { require(!hasMigrated[tokenHolder], "Already migrated tokens"); hasMigrated[tokenHolder] = true; FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId)); if (!oldBalance.isGreaterThan(0)) { return; } FixedPoint.Unsigned memory newBalance = oldBalance.div(rate); require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracle is OracleInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint256 time) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, int256 price ) external { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracleAncillary is OracleAncillaryInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; bytes ancillaryData; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) { // New query, enqueue it for review. queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time, ancillaryData)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) external { verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time][ancillaryData]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data. abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/VotingInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data. abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract to track a whitelist of addresses. */ contract Umip15Upgrader { // Existing governor is the only one who can initiate the upgrade. address public governor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public newVoting; constructor( address _governor, address _existingVoting, address _newVoting, address _finder ) public { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); } function upgrade() external { require(msg.sender == governor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting); // Set current Voting contract to migrated. existingVoting.setMigrated(newVoting); // Transfer back ownership of old voting contract and the finder to the governor. existingVoting.transferOwnership(governor); finder.transferOwnership(governor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract to track a whitelist of addresses. */ contract Umip3Upgrader { // Existing governor is the only one who can initiate the upgrade. address public existingGovernor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. address public newGovernor; // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public voting; address public identifierWhitelist; address public store; address public financialContractsAdmin; address public registry; constructor( address _existingGovernor, address _existingVoting, address _finder, address _voting, address _identifierWhitelist, address _store, address _financialContractsAdmin, address _registry, address _newGovernor ) public { existingGovernor = _existingGovernor; existingVoting = Voting(_existingVoting); finder = Finder(_finder); voting = _voting; identifierWhitelist = _identifierWhitelist; store = _store; financialContractsAdmin = _financialContractsAdmin; registry = _registry; newGovernor = _newGovernor; } function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, voting); finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist); finder.changeImplementationAddress(OracleInterfaces.Store, store); finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin); finder.changeImplementationAddress(OracleInterfaces.Registry, registry); // Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. finder.transferOwnership(newGovernor); // Inform the existing Voting contract of the address of the new Voting contract and transfer its // ownership to the new governor to allow for any future changes to the migrated contract. existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); } }
Must be disputed or the liquidation has passed expiry.
function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; require( (state > Status.PreDispute) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)), "Liquidation not withdrawable" ); }
591,222
pragma solidity >=0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ struct Airline { string name; bool isRegistered; uint256 funds; } struct Insuree { bool isCredited; uint256 balance; } address private contractOwner; address private appContractOwner; bool private operational = true; uint constant airlinesThreshold = 4; uint256 private airlinesCount = 0; mapping(address => Airline) private registeredAirlines; mapping(address => uint256) private multiParty; mapping(address => address) private votedAirlines; mapping(bytes32 => address[]) private flightInsurees; mapping(address => Insuree) private insureesBalance; mapping(address => bool) private authorizedContracts; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor(address firstAirline, string memory name) public { contractOwner = msg.sender; _registerAirline(firstAirline, name); } /********************************************************************************************/ /* 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"); _; } modifier requireAppContractOwner() { require(msg.sender == appContractOwner, "Caller is not App contract owner"); _; } modifier requireIsAuthorized() { require(authorizedContracts[msg.sender], "(data contract) Caller is not authorized"); _; } /** * @dev Modifier that requires the Airline be registered */ modifier requireRegistredAirline(address airline) { require(registeredAirlines[airline].isRegistered == true, "Airline is not registered"); _; } /** * @dev Modifier that requires the Airline has funds */ modifier requireFundedAirline(address airline) { require(registeredAirlines[airline].funds >= (10 ether), "Airline has not enough fund"); _; } /********************************************************************************************/ /* 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; } /** * Authorize application contract owner calls this contract. Only this address can call * data contract business methods. */ function authorizeCaller(address _appContractOwner) external requireIsOperational requireContractOwner { appContractOwner = _appContractOwner; } /** * @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 requireAppContractOwner { require(mode != operational, "New mode must be different from existing one"); operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(address airline, string calldata name, address applicantAirline) external requireIsOperational requireAppContractOwner requireRegistredAirline(airline) requireFundedAirline(airline) { if(airlinesCount < airlinesThreshold) { _registerAirline(applicantAirline, name); } else { require(!(votedAirlines[airline] == applicantAirline), "The airline is already voted to applicantAirline"); multiParty[applicantAirline] += 1; votedAirlines[airline] = applicantAirline; if(airlinesCount.mod(multiParty[applicantAirline]) == 0 && multiParty[applicantAirline] != 1) { _registerAirline(applicantAirline, name); delete multiParty[applicantAirline]; delete votedAirlines[airline]; } } } function _registerAirline(address airlineAddr, string memory name) private { Airline memory airline = Airline(name, true, 0); airlinesCount = airlinesCount + 1; registeredAirlines[airlineAddr] = airline; } /** * @dev Buy insurance for a flight * */ function buy(address airline, string calldata flight, uint256 timestamp, address insuree) external payable requireIsOperational requireAppContractOwner { require(msg.value <= (1 ether), "Value should be less than or equals to one ether"); bytes32 flightKey = getFlightKey(airline, flight, timestamp); flightInsurees[flightKey].push(insuree); Insuree memory insureeStuct = Insuree(false, msg.value); insureesBalance[insuree] = insureeStuct; } /** * @dev Credits payouts to insurees */ function creditInsurees(address airline, string calldata flight, uint256 timestamp, uint256 numerator, uint256 denominator) external requireIsOperational requireAppContractOwner { bytes32 flightKey = getFlightKey(airline, flight, timestamp); Insuree memory insuree; for (uint256 i = 0; i < flightInsurees[flightKey].length; i++) { insuree = insureesBalance[flightInsurees[flightKey][i]]; uint256 currentBalance = insuree.balance; uint256 newBalance = currentBalance.mul(numerator).div(denominator); insuree.isCredited = true; insuree.balance = newBalance; insureesBalance[flightInsurees[flightKey][i]] = insuree; } delete flightInsurees[flightKey]; } /** * @dev Transfers eligible payout funds to insuree * */ function withdraw(address payable insuree) external requireIsOperational requireAppContractOwner { require(insureesBalance[insuree].balance > 0, "Insuree has no balance."); uint256 value = insureesBalance[insuree].balance; insureesBalance[insuree].balance = 0; insuree.transfer(value); } /** * @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, uint256 value) external payable requireIsOperational requireAppContractOwner requireRegistredAirline(airline) { registeredAirlines[airline].funds = registeredAirlines[airline].funds.add(value); } function getFlightKey(address airline, string memory flight, uint256 timestamp) internal pure returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } function getAirline(address airlineAddress) external view requireIsOperational requireAppContractOwner returns(string memory, bool, uint) { Airline memory airline = registeredAirlines[airlineAddress]; return (airline.name, airline.isRegistered, airline.funds); } function getInsureeBalance(address insuree) external view requireIsOperational returns(uint256) { if(insureesBalance[insuree].isCredited) return insureesBalance[insuree].balance; else return uint256(0); } /** * @dev Fallback function for funding smart contract. * */ fallback() external payable { //this.fund{value:msg.value}(msg.sender, msg.value); } }
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 requireAppContractOwner { require(mode != operational, "New mode must be different from existing one"); operational = mode; }
6,353,464
// File: @openzeppelin/contracts/proxy/Initializable.sol // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <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 {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // 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; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // File: @openzeppelin/contracts/math/SafeMath.sol // 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, 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: contracts/uniswapv2/interfaces/IUniswapV2Factory.sol pragma solidity ^0.6.0; interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File: contracts/uniswapv2/interfaces/IUniswapV2Pair.sol pragma solidity ^0.6.0; interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 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 (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts/libraries/Priviledgeable.sol // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.2; abstract contract Priviledgeable { using SafeMath for uint256; using SafeMath for uint256; event PriviledgeGranted(address indexed admin); event PriviledgeRevoked(address indexed admin); modifier onlyAdmin() { require( _priviledgeTable[msg.sender], "Priviledgeable: caller is not the owner" ); _; } mapping(address => bool) private _priviledgeTable; constructor() internal { _priviledgeTable[msg.sender] = true; } function addAdmin(address _admin) external onlyAdmin returns (bool) { require(_admin != address(0), "Admin address cannot be 0"); return _addAdmin(_admin); } function removeAdmin(address _admin) external onlyAdmin returns (bool) { require(_admin != address(0), "Admin address cannot be 0"); _priviledgeTable[_admin] = false; emit PriviledgeRevoked(_admin); return true; } function isAdmin(address _who) external view returns (bool) { return _priviledgeTable[_who]; } //----------- // internals //----------- function _addAdmin(address _admin) internal returns (bool) { _priviledgeTable[_admin] = true; emit PriviledgeGranted(_admin); } } // File: contracts/EmiPrice.sol // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.2; contract EmiPrice is Initializable, Priviledgeable { using SafeMath for uint256; using SafeMath for uint256; address[3] public market; address private _DAI; string public codeVersion = "EmiPrice v1.0-113-g96f8394"; /** * @dev Upgradeable proxy constructor replacement */ function initialize( address _market1, address _market2, address _market3, address _daitoken ) public initializer { require(_market2 != address(0), "Market address cannot be 0"); require(_market3 != address(0), "Market address cannot be 0"); require(_daitoken != address(0), "DAI token address cannot be 0"); market[0] = _market1; market[1] = _market2; market[2] = _market3; _DAI = _daitoken; _addAdmin(msg.sender); } /** * @dev Return coin prices * 10e5 (to solve rounding problems, this yields 5 meaning digits after decimal point) */ function getCoinPrices(address[] calldata _coins, uint8 _market) external view returns (uint256[] memory prices) { require(_market < market.length, "Wrong market index"); IUniswapV2Factory _factory = IUniswapV2Factory(market[_market]); IUniswapV2Pair _p; uint256[] memory _prices; _prices = new uint256[](_coins.length); if (address(_factory) == address(0)) { return _prices; } for (uint256 i = 0; i < _coins.length; i++) { _p = IUniswapV2Pair(_factory.getPair(_coins[i], _DAI)); if (address(_p) == address(0)) { _prices[i] = 0; } else { (uint256 reserv0, uint256 reserv1, ) = _p.getReserves(); if (reserv1 == 0) { _prices[i] = 0; // special case } else { _prices[i] = address(_coins[i]) < address(_DAI) ? reserv1.mul(100000).div(reserv0) : reserv0.mul(100000).div(reserv1); } } } return _prices; } function changeDAI(address _daiToken) external onlyAdmin { require(_daiToken != address(0), "Token address cannot be 0"); _DAI = _daiToken; } function changeMarket(uint8 idx, address _market) external onlyAdmin { require(_market != address(0), "Token address cannot be 0"); require(idx < 3, "Wrong market index"); market[idx] = _market; } }
Return coin prices 10e5 (to solve rounding problems, this yields 5 meaning digits after decimal point)/
function getCoinPrices(address[] calldata _coins, uint8 _market) external view returns (uint256[] memory prices) { require(_market < market.length, "Wrong market index"); IUniswapV2Factory _factory = IUniswapV2Factory(market[_market]); IUniswapV2Pair _p; uint256[] memory _prices; _prices = new uint256[](_coins.length); if (address(_factory) == address(0)) { return _prices; } for (uint256 i = 0; i < _coins.length; i++) { _p = IUniswapV2Pair(_factory.getPair(_coins[i], _DAI)); if (address(_p) == address(0)) { _prices[i] = 0; (uint256 reserv0, uint256 reserv1, ) = _p.getReserves(); if (reserv1 == 0) { _prices[i] = address(_coins[i]) < address(_DAI) ? reserv1.mul(100000).div(reserv0) : reserv0.mul(100000).div(reserv1); } } } return _prices; }
12,594,759
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 c) { c = a + b; assert(c >= a); 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) { assert(b <= a); 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 c) { if(a == 0) return 0; c = a * b; assert(c/a == b); 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. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); return a / b; } }
Returns the integer division of two unsigned integers, reverting on division by zero. The result is rounded towards zero. Counterpart to Solidity's `/` operator. Requirements: - The divisor cannot be zero./
function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); return a / b; }
2,556,312
./full_match/1/0xe5BB8654F698c5f021dA21146219f6a998F2aA99/sources/contracts/v3/tokens/ERC721LA.sol
See {IERC721-transferFrom}.
function transferFrom( address from, address to, uint256 tokenId ) external override { if (!_isApprovedOrOwner(msg.sender, tokenId)) { revert CustomErrors.TransferError(); } _transfer(from, to, tokenId); }
3,137,212
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).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 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 override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } 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, _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]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.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 { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, 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: MIT pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @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 pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @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: 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 "../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 String operations. */ library StringsUpgradeable { 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); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT 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 IERC165Upgradeable { /** * @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.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]; } /** * @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 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, _msgSender()); _; } /** * @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 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]{40}) is missing role (0x[0-9a-f]{64})$/ */ 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 { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, 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()); } } } // SPDX-License-Identifier: MIT 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: MIT 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() { _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); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../Proxy.sol"; import "./ERC1967Upgrade.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. */ contract ERC1967Proxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _upgradeToAndCall(_logic, _data, false); } /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { return ERC1967Upgrade._getImplementation(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @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 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IBeacon.sol"; import "../Proxy.sol"; import "../ERC1967/ERC1967Upgrade.sol"; /** * @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}. * * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't * conflict with the storage layout of the implementation behind the proxy. * * _Available since v3.4._ */ contract BeaconProxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the proxy with `beacon`. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This * will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity * constructor. * * Requirements: * * - `beacon` must be a contract with the interface {IBeacon}. */ constructor(address beacon, bytes memory data) payable { assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1)); _upgradeBeaconToAndCall(beacon, data, false); } /** * @dev Returns the current beacon address. */ function _beacon() internal view virtual returns (address) { return _getBeacon(); } /** * @dev Returns the current implementation address of the associated beacon. */ function _implementation() internal view virtual override returns (address) { return IBeacon(_getBeacon()).implementation(); } /** * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. * * Requirements: * * - `beacon` must be a contract. * - The implementation returned by `beacon` must be a contract. */ function _setBeacon(address beacon, bytes memory data) internal virtual { _upgradeBeaconToAndCall(beacon, data, false); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IBeacon.sol"; import "../../access/Ownable.sol"; import "../../utils/Address.sol"; /** * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their * implementation contract, which is where they will delegate all function calls. * * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon. */ contract UpgradeableBeacon is IBeacon, Ownable { address private _implementation; /** * @dev Emitted when the implementation returned by the beacon is changed. */ event Upgraded(address indexed implementation); /** * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the * beacon. */ constructor(address implementation_) { _setImplementation(implementation_); } /** * @dev Returns the current implementation address. */ function implementation() public view virtual override returns (address) { return _implementation; } /** * @dev Upgrades the beacon to a new implementation. * * Emits an {Upgraded} event. * * Requirements: * * - msg.sender must be the owner of the contract. * - `newImplementation` must be a contract. */ function upgradeTo(address newImplementation) public virtual onlyOwner { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation contract address for this beacon * * Requirements: * * - `newImplementation` must be a contract. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract"); _implementation = newImplementation; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967Proxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is ERC1967Proxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}. */ constructor( address _logic, address admin_, bytes memory _data ) payable ERC1967Proxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _changeAdmin(admin_); } /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _getAdmin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _getAdmin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { _changeAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeToAndCall(newImplementation, bytes(""), false); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeToAndCall(newImplementation, data, true); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address) { return _getAdmin(); } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // 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; /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT 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); } } // SPDX-License-Identifier: MIT 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.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: GPL-3.0 // solhint-disable-next-line pragma solidity ^0.8.0; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import {AccessControlEnumerableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {StringsUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {TransparentUpgradeableProxy} from "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; import {IMintGateway} from "../Gateways/interfaces/IMintGateway.sol"; import {ILockGateway} from "../Gateways/interfaces/ILockGateway.sol"; import {String} from "../libraries/String.sol"; import {RenAssetFactory} from "./RenAssetFactory.sol"; import {StringSet} from "../libraries/StringSet.sol"; contract GatewayRegistryStateV2 { struct GatewayDetails { address gateway; address token; } StringSet.Set internal mintGatewaySymbols; StringSet.Set internal lockGatewaySymbols; mapping(address => string) internal mintSymbolByToken; mapping(string => GatewayDetails) internal mintGatewayDetailsBySymbol; mapping(address => string) internal lockSymbolByToken; mapping(string => GatewayDetails) internal lockGatewayDetailsBySymbol; address internal _signatureVerifier; uint256 internal _chainId; address internal _transferContract; // Leave a gap so that storage values added in future upgrages don't corrupt // the storage of contracts that inherit from this contract. // Note that StringSet.Set occupies two slots. uint256[39] private __gap; } contract GatewayRegistryGettersV2 is GatewayRegistryStateV2 { using StringSet for StringSet.Set; function getChainId() public view returns (uint256) { return _chainId; } function getSignatureVerifier() public view returns (address) { require(_signatureVerifier != address(0x0), "GatewayRegistry: not initialized"); return _signatureVerifier; } function getTransferContract() external view returns (address) { require(_transferContract != address(0x0), "GatewayRegistry: not initialized"); return _transferContract; } /// @dev To get all the registered Gateway contracts set count to `0`. function getMintGatewaySymbols(uint256 from, uint256 count) external view returns (string[] memory) { return enumerateSet(mintGatewaySymbols, from, count); } /// @dev To get all the registered tokens set count to `0`. function getLockGatewaySymbols(uint256 from, uint256 count) external view returns (string[] memory) { return enumerateSet(lockGatewaySymbols, from, count); } function enumerateSet( StringSet.Set storage set, uint256 from, uint256 count ) internal view returns (string[] memory) { uint256 length = set.length(); if (count == 0 || from + count > length) { count = length - from; } string[] memory gateways = new string[](count); for (uint256 i = 0; i < count; i++) { gateways[i] = set.at(i + from); } return gateways; } /// @notice Returns the Gateway contract for the given RenERC20 token /// address. /// /// @param token The address of the RenERC20 token contract. function getMintGatewayByToken(address token) public view returns (IMintGateway) { return IMintGateway(mintGatewayDetailsBySymbol[mintSymbolByToken[token]].gateway); } /// @notice Deprecated in favour of getMintGatewayByToken. function getGatewayByToken(address token) external view returns (IMintGateway) { return getMintGatewayByToken(token); } /// @notice Returns the Gateway contract for the given RenERC20 token /// symbol. /// /// @param tokenSymbol The symbol of the RenERC20 token contract. function getMintGatewayBySymbol(string calldata tokenSymbol) public view returns (IMintGateway) { return IMintGateway(mintGatewayDetailsBySymbol[tokenSymbol].gateway); } /// @notice Deprecated in favour of getMintGatewayBySymbol. function getGatewayBySymbol(string calldata tokenSymbol) external view returns (IMintGateway) { return getMintGatewayBySymbol(tokenSymbol); } /// @notice Returns the RenERC20 address for the given token symbol. /// /// @param tokenSymbol The symbol of the RenERC20 token contract to /// lookup. function getRenAssetBySymbol(string calldata tokenSymbol) public view returns (IERC20) { return IERC20(mintGatewayDetailsBySymbol[tokenSymbol].token); } /// @notice Deprecated in favour of getRenAssetBySymbol. function getTokenBySymbol(string calldata tokenSymbol) external view returns (IERC20) { return getRenAssetBySymbol(tokenSymbol); } function getLockGatewayByToken(address token_) external view returns (ILockGateway) { return ILockGateway(lockGatewayDetailsBySymbol[lockSymbolByToken[token_]].gateway); } function getLockGatewayBySymbol(string calldata tokenSymbol) external view returns (ILockGateway) { return ILockGateway(lockGatewayDetailsBySymbol[tokenSymbol].gateway); } function getLockAssetBySymbol(string calldata tokenSymbol) external view returns (IERC20) { return IERC20(lockGatewayDetailsBySymbol[tokenSymbol].token); } } /// GatewayRegistry is a mapping from assets to their associated /// RenERC20 and Gateway contracts. contract GatewayRegistryV2 is Initializable, AccessControlEnumerableUpgradeable, RenAssetFactory, GatewayRegistryStateV2, GatewayRegistryGettersV2 { using StringSet for StringSet.Set; string public constant NAME = "GatewayRegistry"; bytes32 public constant CAN_UPDATE_GATEWAYS = keccak256("CAN_UPDATE_GATEWAYS"); bytes32 public constant CAN_ADD_GATEWAYS = keccak256("CAN_ADD_GATEWAYS"); function __GatewayRegistry_init( uint256 chainId_, address signatureVerifier_, address transferContract, address renAssetProxyBeacon_, address mintGatewayProxyBeacon_, address lockGatewayProxyBeacon_, address adminAddress, address[] calldata gatewayDeployers ) external initializer { __AccessControlEnumerable_init(); __RenAssetFactory_init(renAssetProxyBeacon_, mintGatewayProxyBeacon_, lockGatewayProxyBeacon_); _chainId = chainId_; _signatureVerifier = signatureVerifier_; _transferContract = transferContract; AccessControlEnumerableUpgradeable._setupRole(AccessControlUpgradeable.DEFAULT_ADMIN_ROLE, adminAddress); AccessControlEnumerableUpgradeable._setupRole(CAN_UPDATE_GATEWAYS, adminAddress); AccessControlEnumerableUpgradeable._setupRole(CAN_ADD_GATEWAYS, adminAddress); for (uint256 i = 0; i < gatewayDeployers.length; ++i) { _setupRole(CAN_ADD_GATEWAYS, gatewayDeployers[i]); } } /// @dev The symbol is included twice because strings have to be hashed /// first in order to be used as a log index/topic. event LogMintGatewayAdded( string symbol, address indexed token, address indexed gatewayContract, // Indexed versions of previous parameters. string indexed indexedSymbol ); event LogMintGatewayRemoved( string symbol, // Indexed versions of previous parameters. string indexed indexedSymbol ); event LogLockGatewayAdded( string symbol, address indexed token, address indexed gatewayContract, // Indexed versions of previous parameters. string indexed indexedSymbol ); event LogLockGatewayRemoved( string symbol, // Indexed versions of previous parameters. string indexed indexedSymbol ); event LogSignatureVerifierUpdated(address indexed oldSignatureVerifier, address indexed newSignatureVerifier); event LogTransferContractUpdated(address indexed oldTransferContract, address indexed newTransferContract); // MODIFIERS /////////////////////////////////////////////////////////////// modifier onlyValidString(string calldata str_) { require(String.isValidString(str_), "GatewayRegistry: empty or invalid string input"); _; } function checkRoleVerbose( bytes32 role, string memory roleName, address account ) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "GatewayRegistry: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", roleName ) ) ); } } modifier onlyRoleVerbose(bytes32 role, string memory roleName) { checkRoleVerbose(role, roleName, _msgSender()); _; } // GOVERNANCE ////////////////////////////////////////////////////////////// /// @notice Allow the owner to update the signature verifier contract. /// /// @param newSignatureVerifier The new verifier contract address. function updateSignatureVerifier(address newSignatureVerifier) external onlyRoleVerbose(CAN_UPDATE_GATEWAYS, "CAN_UPDATE_GATEWAYS") { require(newSignatureVerifier != address(0x0), "GatewayRegistry: invalid signature verifier"); address oldSignatureVerifier = _signatureVerifier; _signatureVerifier = newSignatureVerifier; emit LogSignatureVerifierUpdated(oldSignatureVerifier, newSignatureVerifier); } /// @notice Allow the owner to update the TransferContract contract. /// /// @param newTransferContract The new TransferContract contract address. function updateTransferContract(address newTransferContract) external onlyRoleVerbose(CAN_UPDATE_GATEWAYS, "CAN_UPDATE_GATEWAYS") { require(newTransferContract != address(0x0), "GatewayRegistry: invalid transfer with log"); address oldTransferContract = _transferContract; _transferContract = newTransferContract; emit LogTransferContractUpdated(oldTransferContract, newTransferContract); } // MINT GATEWAYS /////////////////////////////////////////////////////////// /// @notice Allow the owner to set the Gateway contract for a given /// RenERC20 token contract. /// /// @param symbol A string that identifies the token and gateway pair. /// @param renAsset The address of the RenERC20 token contract. /// @param mintGateway The address of the Gateway contract. function addMintGateway( string calldata symbol, address renAsset, address mintGateway ) public onlyValidString(symbol) onlyRoleVerbose(CAN_ADD_GATEWAYS, "CAN_ADD_GATEWAYS") { if (mintGatewaySymbols.contains(symbol)) { // If there is an existing gateway for the symbol, delete it. The // caller must also have the CAN_UPDATE_GATEWAYS role. removeMintGateway(symbol); } // Check that token, Gateway and symbol haven't already been registered. if (String.isNotEmpty(mintSymbolByToken[renAsset])) { revert( string( abi.encodePacked( "GatewayRegistry: ", symbol, " token already registered as ", mintSymbolByToken[renAsset] ) ) ); } // Add to list of gateways. mintGatewaySymbols.add(symbol); mintGatewayDetailsBySymbol[symbol] = GatewayDetails({token: renAsset, gateway: mintGateway}); mintSymbolByToken[renAsset] = symbol; emit LogMintGatewayAdded(symbol, renAsset, mintGateway, symbol); } function deployMintGateway( string calldata symbol, address renAsset, string calldata version ) external onlyRoleVerbose(CAN_ADD_GATEWAYS, "CAN_ADD_GATEWAYS") { if (mintGatewaySymbols.contains(symbol)) { // Check role before expensive contract deployment. checkRoleVerbose(CAN_UPDATE_GATEWAYS, "CAN_UPDATE_GATEWAYS", _msgSender()); } address mintGateway = address(_deployMintGateway(symbol, getSignatureVerifier(), renAsset, version)); addMintGateway(symbol, renAsset, mintGateway); } function deployMintGatewayAndRenAsset( string calldata symbol, string calldata erc20Name, string calldata erc20Symbol, uint8 erc20Decimals, string calldata version ) external onlyRoleVerbose(CAN_ADD_GATEWAYS, "CAN_ADD_GATEWAYS") { if (mintGatewaySymbols.contains(symbol)) { // Check role before expensive contract deployment. checkRoleVerbose(CAN_UPDATE_GATEWAYS, "CAN_UPDATE_GATEWAYS", _msgSender()); } address renAsset = address( _deployRenAsset(getChainId(), symbol, erc20Name, erc20Symbol, erc20Decimals, version) ); address mintGateway = address(_deployMintGateway(symbol, getSignatureVerifier(), renAsset, version)); OwnableUpgradeable(renAsset).transferOwnership(mintGateway); addMintGateway(symbol, renAsset, mintGateway); } /// @notice Allows the owner to remove the Gateway contract for a given /// RenERC20 contract. /// /// @param symbol The symbol of the token to deregister. function removeMintGateway(string calldata symbol) public onlyRoleVerbose(CAN_UPDATE_GATEWAYS, "CAN_UPDATE_GATEWAYS") { address renAsset = mintGatewayDetailsBySymbol[symbol].token; require(renAsset != address(0x0), "GatewayRegistry: gateway not registered"); // Remove token and Gateway contract delete mintSymbolByToken[renAsset]; delete mintGatewayDetailsBySymbol[symbol]; mintGatewaySymbols.remove(symbol); emit LogMintGatewayRemoved(symbol, symbol); } // LOCK GATEWAYS /////////////////////////////////////////////////////////// /// @notice Allow the owner to set the Gateway contract for a given /// RenERC20 token contract. /// /// @param symbol A string that identifies the token and gateway pair. /// @param lockAsset The address of the RenERC20 token contract. /// @param lockGateway The address of the Gateway contract. function addLockGateway( string calldata symbol, address lockAsset, address lockGateway ) public onlyValidString(symbol) onlyRoleVerbose(CAN_ADD_GATEWAYS, "CAN_ADD_GATEWAYS") { if (lockGatewaySymbols.contains(symbol)) { // If there is an existing gateway for the symbol, delete it. The // caller must also have the CAN_UPDATE_GATEWAYS role. removeLockGateway(symbol); } // Check that token hasn't already been registered. if (String.isNotEmpty(lockSymbolByToken[lockAsset])) { revert( string( abi.encodePacked( "GatewayRegistry: ", symbol, " token already registered as ", lockSymbolByToken[lockAsset] ) ) ); } // Add to list of gateways. lockGatewaySymbols.add(symbol); lockGatewayDetailsBySymbol[symbol] = GatewayDetails({token: lockAsset, gateway: lockGateway}); lockSymbolByToken[lockAsset] = symbol; emit LogLockGatewayAdded(symbol, lockAsset, lockGateway, symbol); } function deployLockGateway( string calldata symbol, address lockToken, string calldata version ) external onlyRoleVerbose(CAN_ADD_GATEWAYS, "CAN_ADD_GATEWAYS") { if (lockGatewaySymbols.contains(symbol)) { // Check role before expensive contract deployment. checkRoleVerbose(CAN_UPDATE_GATEWAYS, "CAN_UPDATE_GATEWAYS", _msgSender()); } address lockGateway = address(_deployLockGateway(symbol, getSignatureVerifier(), lockToken, version)); addLockGateway(symbol, lockToken, lockGateway); } /// @notice Allows the owner to remove the Gateway contract for a given /// asset contract. /// /// @param symbol The symbol of the token to deregister. function removeLockGateway(string calldata symbol) public onlyRoleVerbose(CAN_UPDATE_GATEWAYS, "CAN_UPDATE_GATEWAYS") { require(lockGatewaySymbols.contains(symbol), "GatewayRegistry: gateway not registered"); address lockAsset = lockGatewayDetailsBySymbol[symbol].token; // Remove token and Gateway contract delete lockSymbolByToken[lockAsset]; delete lockGatewayDetailsBySymbol[symbol]; lockGatewaySymbols.remove(symbol); emit LogLockGatewayRemoved(symbol, symbol); } } contract GatewayRegistryProxy is TransparentUpgradeableProxy { constructor( address logic, address admin, bytes memory data ) payable TransparentUpgradeableProxy(logic, admin, data) {} } // SPDX-License-Identifier: GPL-3.0 // solhint-disable-next-line pragma solidity ^0.8.0; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; import {UpgradeableBeacon} from "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol"; import {Context} from "@openzeppelin/contracts/utils/Context.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {BeaconProxy} from "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol"; contract ProxyBeacon is Context, UpgradeableBeacon { event LogProxyDeployerUpdated(address indexed oldProxyDeployer, address indexed newProxyDeployer); // Only allow one address to call `deployProxy`. address private _proxyDeployer; modifier onlyProxyDeployer() { address proxyDeployer_ = getProxyDeployer(); require( proxyDeployer_ != address(0x0) && _msgSender() == proxyDeployer_, "ProxyBeacon: caller is not the proxy deployer" ); _; } constructor(address implementation_, address contractOwner) UpgradeableBeacon(implementation_) { transferOwnership(contractOwner); } // GETTERS ///////////////////////////////////////////////////////////////// function getProxyDeployer() public view returns (address) { return _proxyDeployer; } // GOVERNANCE ////////////////////////////////////////////////////////////// function updateProxyDeployer(address newProxyDeployer) public onlyOwner { require(newProxyDeployer != address(0x0), "ProxyBeacon: invalid proxy deployer"); address oldProxyDeployer = _proxyDeployer; _proxyDeployer = newProxyDeployer; emit LogProxyDeployerUpdated(oldProxyDeployer, newProxyDeployer); } // RESTRICTED ////////////////////////////////////////////////////////////// /// @notice Deploy a proxy that fetches its implementation from this /// ProxyBeacon. function deployProxy(bytes32 create2Salt, bytes calldata encodedParameters) external onlyProxyDeployer returns (address) { // Deploy without initialization code so that the create2 address isn't // based on the initialization parameters. address proxy = address(new BeaconProxy{salt: create2Salt}(address(this), "")); Address.functionCall(address(proxy), encodedParameters); return proxy; } } contract RenAssetProxyBeacon is ProxyBeacon { string public constant NAME = "RenAssetProxyBeacon"; constructor(address implementation, address adminAddress) ProxyBeacon(implementation, adminAddress) {} } contract MintGatewayProxyBeacon is ProxyBeacon { string public constant NAME = "MintGatewayProxyBeacon"; constructor(address implementation, address adminAddress) ProxyBeacon(implementation, adminAddress) {} } contract LockGatewayProxyBeacon is ProxyBeacon { string public constant NAME = "LockGatewayProxyBeacon"; constructor(address implementation, address adminAddress) ProxyBeacon(implementation, adminAddress) {} } // SPDX-License-Identifier: GPL-3.0 // solhint-disable-next-line pragma solidity ^0.8.0; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import {ContextUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import {BeaconProxy} from "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IMintGateway} from "../Gateways/interfaces/IMintGateway.sol"; import {ILockGateway} from "../Gateways/interfaces/ILockGateway.sol"; import {RenAssetProxyBeacon, MintGatewayProxyBeacon, LockGatewayProxyBeacon} from "./ProxyBeacon.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; contract RenAssetFactoryState { RenAssetProxyBeacon internal _renAssetProxyBeacon; MintGatewayProxyBeacon internal _mintGatewayProxyBeacon; LockGatewayProxyBeacon internal _lockGatewayProxyBeacon; } abstract contract RenAssetFactory is Initializable, ContextUpgradeable, RenAssetFactoryState { event RenAssetProxyDeployed( uint256 chainId, string asset, string name, string symbol, uint8 decimals, string version ); event MintGatewayProxyDeployed(string asset, address signatureVerifier, address token, string version); event LockGatewayProxyDeployed(string asset, address signatureVerifier, address token, string version); function getRenAssetProxyBeacon() public view returns (RenAssetProxyBeacon) { return _renAssetProxyBeacon; } function getMintGatewayProxyBeacon() public view returns (MintGatewayProxyBeacon) { return _mintGatewayProxyBeacon; } function getLockGatewayProxyBeacon() public view returns (LockGatewayProxyBeacon) { return _lockGatewayProxyBeacon; } function __RenAssetFactory_init( address renAssetProxyBeacon_, address mintGatewayProxyBeacon_, address lockGatewayProxyBeacon_ ) public initializer { __Context_init(); _renAssetProxyBeacon = RenAssetProxyBeacon(renAssetProxyBeacon_); _mintGatewayProxyBeacon = MintGatewayProxyBeacon(mintGatewayProxyBeacon_); _lockGatewayProxyBeacon = LockGatewayProxyBeacon(lockGatewayProxyBeacon_); } function _deployRenAsset( uint256 chainId, string calldata asset, string calldata name, string calldata symbol, uint8 decimals, string calldata version ) internal returns (IERC20) { bytes memory encodedParameters = abi.encodeWithSignature( "__RenAsset_init(uint256,string,string,string,uint8,address)", chainId, version, name, symbol, decimals, // Owner will be transferred to gateway address(this) ); bytes32 create2Salt = keccak256(abi.encodePacked(asset, version)); address renAsset = getRenAssetProxyBeacon().deployProxy(create2Salt, encodedParameters); emit RenAssetProxyDeployed(chainId, asset, name, symbol, decimals, version); return IERC20(renAsset); } function _deployMintGateway( string calldata asset, address signatureVerifier, address token, string calldata version ) internal returns (IMintGateway) { bytes memory encodedParameters = abi.encodeWithSignature( "__MintGateway_init(string,address,address)", asset, signatureVerifier, token ); bytes32 create2Salt = keccak256(abi.encodePacked(asset, version)); address mintGateway = getMintGatewayProxyBeacon().deployProxy(create2Salt, encodedParameters); emit MintGatewayProxyDeployed(asset, signatureVerifier, token, version); return IMintGateway(mintGateway); } function _deployLockGateway( string calldata asset, address signatureVerifier, address token, string calldata version ) internal returns (ILockGateway) { bytes memory encodedParameters = abi.encodeWithSignature( "__LockGateway_init(string,address,address)", asset, signatureVerifier, token ); bytes32 create2Salt = keccak256(abi.encodePacked(asset, version)); address lockGateway = getLockGatewayProxyBeacon().deployProxy(create2Salt, encodedParameters); emit LockGatewayProxyDeployed(asset, signatureVerifier, token, version); return ILockGateway(lockGateway); } } // SPDX-License-Identifier: GPL-3.0 // solhint-disable-next-line pragma solidity ^0.8.0; abstract contract ILockGateway { event LogRelease(address indexed recipient, uint256 amount, bytes32 indexed sigHash, bytes32 indexed nHash); event LogLockToChain( string recipientAddress, string recipientChain, bytes recipientPayload, uint256 amount, uint256 indexed lockNonce, // Indexed versions of previous parameters. string indexed recipientAddressIndexed, string indexed recipientChainIndexed ); function lock( string calldata recipientAddress, string calldata recipientChain, bytes calldata recipientPayload, uint256 amount ) external virtual returns (uint256); function release( bytes32 pHash, uint256 amount, bytes32 nHash, bytes calldata sig ) external virtual returns (uint256); } // SPDX-License-Identifier: GPL-3.0 // solhint-disable-next-line pragma solidity ^0.8.0; abstract contract IMintGateway { /// @dev For backwards compatiblity reasons, the sigHash is cast to a /// uint256. event LogMint(address indexed to, uint256 amount, uint256 indexed sigHash, bytes32 indexed nHash); /// @dev Once `LogBurnToChain` is enabled on mainnet, LogBurn may be /// replaced by LogBurnToChain with empty payload and chain fields. /// @dev For backwards compatibility, `to` is bytes instead of a string. event LogBurn( bytes to, uint256 amount, uint256 indexed burnNonce, // Indexed versions of previous parameters. bytes indexed indexedTo ); event LogBurnToChain( string recipientAddress, string recipientChain, bytes recipientPayload, uint256 amount, uint256 indexed burnNonce, // Indexed versions of previous parameters. string indexed recipientAddressIndexed, string indexed recipientChainIndexed ); function mint( bytes32 pHash, uint256 amount, bytes32 nHash, bytes calldata sig ) external virtual returns (uint256); function burnWithPayload( string calldata recipientAddress, string calldata recipientChain, bytes calldata recipientPayload, uint256 amount ) external virtual returns (uint256); function burn(string calldata recipient, uint256 amount) external virtual returns (uint256); function burn(bytes calldata recipient, uint256 amount) external virtual returns (uint256); } // SPDX-License-Identifier: GPL-3.0 // solhint-disable-next-line pragma solidity ^0.8.0; /// Library with common String checks. library String { /// Check that the string only contains alphanumeric characters, to avoid /// UTF-8 characters that are indistinguishable from alphanumeric /// characters. function isAlphanumeric(string memory str) internal pure returns (bool) { for (uint256 i = 0; i < bytes(str).length; i++) { uint8 char = uint8(bytes(str)[i]); if (!((char >= 65 && char <= 90) || (char >= 97 && char <= 122) || (char >= 48 && char <= 57))) { return false; } } return true; } /// Check that the string has at least one character. function isNotEmpty(string memory str) internal pure returns (bool) { return bytes(str).length > 0; } /// Check that the string is not empty and only has alphanumeric characters. function isValidString(string memory str) internal pure returns (bool) { return isNotEmpty(str) && isAlphanumeric(str); } } // SPDX-License-Identifier: MIT // Modified from @openzeppelin/contracts's EnumerableSet to store strings. /* The MIT License (MIT) Copyright (c) 2016-2020 zOS Global Limited 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. */ // solhint-disable-next-line pragma solidity ^0.8.0; library StringSet { struct Set { string[] _values; mapping(string => uint256) _indexes; // 1-indexed } function add(Set storage set, string memory value) internal returns (bool) { if (!contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; } else { return false; } } function remove(Set storage set, string memory value) internal returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // Swap the item with the last element so that it can be popped. if (lastIndex != toDeleteIndex) { string memory lastvalue = set._values[lastIndex]; set._values[toDeleteIndex] = lastvalue; set._indexes[lastvalue] = valueIndex; } set._values.pop(); delete set._indexes[value]; return true; } else { return false; } } function contains(Set storage set, string memory value) internal view returns (bool) { return set._indexes[value] != 0; } function length(Set storage set) internal view returns (uint256) { return set._values.length; } function at(Set storage set, uint256 index) internal view returns (string memory) { return set._values[index]; } }
Swap the item with the last element so that it can be popped.
function remove(Set storage set, string memory value) internal returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { string memory lastvalue = set._values[lastIndex]; set._values[toDeleteIndex] = lastvalue; set._indexes[lastvalue] = valueIndex; } set._values.pop(); delete set._indexes[value]; return true; return false; } }
1,274,776
pragma solidity >=0.5.0; //Inheritance import '../interfaces/IIndicator.sol'; //Libraries import '../libraries/SafeMath.sol'; contract SMA is IIndicator { using SafeMath for uint; struct State { uint8 SMAperiod; uint248 currentValue; } uint public _price; address public _developer; mapping (address => State[]) private _tradingBotStates; mapping (address => mapping (uint => uint[])) private _tradingBotHistory; mapping (address => mapping (uint => uint[])) private _priceHistory; constructor(uint price) public { require(price >= 0, "Price must be greater than 0"); _price = price; _developer = msg.sender; } /** * @dev Returns the name of the indicator * @return string Name of the indicator */ function getName() public pure override returns (string memory) { return "SMA"; } /** * @dev Returns the sale price and the developer of the indicator * @return (uint, address) Sale price of the indicator and the indicator's developer */ function getPriceAndDeveloper() public view override returns (uint, address) { return (_price, _developer); } /** * @dev Updates the sale price of the indicator; meant to be called by the indicator's developer * @param newPrice The new sale price of the indicator */ function editPrice(uint newPrice) external override { require(msg.sender == _developer, "Only the developer can edit the price"); require(newPrice >= 0, "Price must be a positive number"); _price = newPrice; emit UpdatedPrice(address(this), newPrice, block.timestamp); } /** * @dev Initializes the state of the trading bot; meant to be called by a trading bot * @param param Value of the indicator's parameter * @return uint Index of trading bot instance in State array */ function addTradingBot(uint param) public override returns (uint) { require(param > 1 && param <= 200, "Param must be between 2 and 200"); _tradingBotStates[msg.sender].push(State(uint8(param), 0)); return _tradingBotStates[msg.sender].length - 1; } /** * @dev Updates the indicator's state based on the latest price feed update * @param index Index in trading bot's entry/exit rule array * @param latestPrice The latest price from oracle price feed */ function update(uint index, uint latestPrice) public override { require(index >= 0 && index < _tradingBotStates[msg.sender].length, "Invalid index"); _priceHistory[msg.sender][index].push(latestPrice); uint[] memory priceHistory = _priceHistory[msg.sender][index]; if (priceHistory.length > uint256(_tradingBotStates[msg.sender][index].SMAperiod)) { uint temp = uint256(_tradingBotStates[msg.sender][index].currentValue).mul(uint256(_tradingBotStates[msg.sender][index].SMAperiod)); uint index2 = priceHistory.length.sub(uint256(_tradingBotStates[msg.sender][index].SMAperiod)).sub(1); temp = temp.sub(priceHistory[index2]); temp = temp.add(latestPrice); temp = temp.div(uint256(_tradingBotStates[msg.sender][index].SMAperiod)); _tradingBotStates[msg.sender][index].currentValue = uint128(temp); _tradingBotHistory[msg.sender][index].push(temp); } else { uint temp = uint256(_tradingBotStates[msg.sender][index].currentValue).mul(priceHistory.length - 1); temp = temp.add(latestPrice); temp = temp.div(priceHistory.length); uint value = (priceHistory.length == uint256(_tradingBotStates[msg.sender][index].SMAperiod)) ? temp : 1; _tradingBotStates[msg.sender][index].currentValue = uint128(temp); _tradingBotHistory[msg.sender][index].push(value); } } /** * @dev Given a trading bot address, returns the indicator value for that bot * @param tradingBotAddress Address of trading bot * @param index Index in trading bot's entry/exit rule array * @return uint[] Indicator value for the given trading bot */ function getValue(address tradingBotAddress, uint index) public view override returns (uint[] memory) { require(tradingBotAddress != address(0), "Invalid trading bot address"); require(index >= 0 && index < _tradingBotStates[tradingBotAddress].length, "Invalid index"); uint[] memory temp = new uint[](1); temp[0] = (_priceHistory[tradingBotAddress][index].length >= uint256(_tradingBotStates[tradingBotAddress][index].SMAperiod)) ? uint256(_tradingBotStates[tradingBotAddress][index].currentValue) : 0; return temp; } /** * @dev Given a trading bot address, returns the indicator value history for that bot * @param tradingBotAddress Address of trading bot * @param index Index in trading bot's entry/exit rule array * @return uint[] Indicator value history for the given trading bot */ function getHistory(address tradingBotAddress, uint index) public view override returns (uint[] memory) { require(tradingBotAddress != address(0), "Invalid trading bot address"); require(index >= 0 && index < _tradingBotStates[tradingBotAddress].length, "Invalid index"); return _tradingBotHistory[tradingBotAddress][index]; } }
Given a trading bot address, returns the indicator value for that bot tradingBotAddress Address of trading bot index Index in trading bot's entry/exit rule array return uint[] Indicator value for the given trading bot/
function getValue(address tradingBotAddress, uint index) public view override returns (uint[] memory) { require(tradingBotAddress != address(0), "Invalid trading bot address"); require(index >= 0 && index < _tradingBotStates[tradingBotAddress].length, "Invalid index"); uint[] memory temp = new uint[](1); temp[0] = (_priceHistory[tradingBotAddress][index].length >= uint256(_tradingBotStates[tradingBotAddress][index].SMAperiod)) ? uint256(_tradingBotStates[tradingBotAddress][index].currentValue) : 0; return temp; }
5,355,565
./full_match/5/0x40E8961f2C055c4a92Fa4Ee68A30B8Fd4e7e4Bd4/sources/contracts/AuctionListing.sol
autoBid function, written but not implementedtakes 2 more blocks than usual
function autoBid(uint256 maxPrice, uint256 priceIncrease) public { while (isOpen) { if (currentPrice+priceIncrease <= maxPrice) { bid(currentPrice+priceIncrease); } } }
1,849,930
/** *Submitted for verification at Etherscan.io on 2021-10-15 */ // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; pragma experimental ABIEncoderV2; // File: contracts\interfaces\IWitnetRequestBoardEvents.sol /// @title Witnet Request Board emitting events interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardEvents { /// Emitted when a Witnet Data Request is posted to the WRB. event PostedRequest(uint256 queryId, address from); /// Emitted when a Witnet-solved result is reported to the WRB. event PostedResult(uint256 queryId, address from); /// Emitted when all data related to given query is deleted from the WRB. event DeletedQuery(uint256 queryId, address from); } // File: contracts\interfaces\IWitnetRequestBoardReporter.sol /// @title The Witnet Request Board Reporter interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardReporter { /// Reports the Witnet-provided result to a previously posted request. /// @dev Will assume `block.timestamp` as the timestamp at which the request was solved. /// @dev Fails if: /// @dev - the `_queryId` is not in 'Posted' status. /// @dev - provided `_drTxHash` is zero; /// @dev - length of provided `_result` is zero. /// @param _queryId The unique identifier of the data request. /// @param _drTxHash The hash of the solving tally transaction in Witnet. /// @param _result The result itself as bytes. function reportResult(uint256 _queryId, bytes32 _drTxHash, bytes calldata _result) external; /// Reports the Witnet-provided result to a previously posted request. /// @dev Fails if: /// @dev - called from unauthorized address; /// @dev - the `_queryId` is not in 'Posted' status. /// @dev - provided `_drTxHash` is zero; /// @dev - length of provided `_result` is zero. /// @param _queryId The unique query identifier /// @param _timestamp The timestamp of the solving tally transaction in Witnet. /// @param _drTxHash The hash of the solving tally transaction in Witnet. /// @param _result The result itself as bytes. function reportResult(uint256 _queryId, uint256 _timestamp, bytes32 _drTxHash, bytes calldata _result) external; } // File: contracts\interfaces\IWitnetRequest.sol /// @title The Witnet Data Request basic interface. /// @author The Witnet Foundation. interface IWitnetRequest { /// A `IWitnetRequest` is constructed around a `bytes` value containing /// a well-formed Witnet Data Request using Protocol Buffers. function bytecode() external view returns (bytes memory); /// Returns SHA256 hash of Witnet Data Request as CBOR-encoded bytes. function hash() external view returns (bytes32); } // File: contracts\libs\Witnet.sol library Witnet { /// @notice Witnet function that computes the hash of a CBOR-encoded Data Request. /// @param _bytecode CBOR-encoded RADON. function hash(bytes memory _bytecode) internal pure returns (bytes32) { return sha256(_bytecode); } /// Struct containing both request and response data related to every query posted to the Witnet Request Board struct Query { Request request; Response response; } /// Possible status of a Witnet query. enum QueryStatus { Unknown, Posted, Reported, Deleted } /// Data kept in EVM-storage for every Request posted to the Witnet Request Board. struct Request { IWitnetRequest addr; // The contract containing the Data Request which execution has been requested. address requester; // Address from which the request was posted. bytes32 hash; // Hash of the Data Request whose execution has been requested. uint256 gasprice; // Minimum gas price the DR resolver should pay on the solving tx. uint256 reward; // Escrowed reward to be paid to the DR resolver. } /// Data kept in EVM-storage containing Witnet-provided response metadata and result. struct Response { address reporter; // Address from which the result was reported. uint256 timestamp; // Timestamp of the Witnet-provided result. bytes32 drTxHash; // Hash of the Witnet transaction that solved the queried Data Request. bytes cborBytes; // Witnet-provided result CBOR-bytes to the queried Data Request. } /// Data struct containing the Witnet-provided result to a Data Request. struct Result { bool success; // Flag stating whether the request could get solved successfully, or not. CBOR value; // Resulting value, in CBOR-serialized bytes. } /// Data struct following the RFC-7049 standard: Concise Binary Object Representation. struct CBOR { Buffer buffer; uint8 initialByte; uint8 majorType; uint8 additionalInformation; uint64 len; uint64 tag; } /// Iterable bytes buffer. struct Buffer { bytes data; uint32 cursor; } /// Witnet error codes table. enum ErrorCodes { // 0x00: Unknown error. Something went really bad! Unknown, // Script format errors /// 0x01: At least one of the source scripts is not a valid CBOR-encoded value. SourceScriptNotCBOR, /// 0x02: The CBOR value decoded from a source script is not an Array. SourceScriptNotArray, /// 0x03: The Array value decoded form a source script is not a valid Data Request. SourceScriptNotRADON, /// Unallocated ScriptFormat0x04, ScriptFormat0x05, ScriptFormat0x06, ScriptFormat0x07, ScriptFormat0x08, ScriptFormat0x09, ScriptFormat0x0A, ScriptFormat0x0B, ScriptFormat0x0C, ScriptFormat0x0D, ScriptFormat0x0E, ScriptFormat0x0F, // Complexity errors /// 0x10: The request contains too many sources. RequestTooManySources, /// 0x11: The script contains too many calls. ScriptTooManyCalls, /// Unallocated Complexity0x12, Complexity0x13, Complexity0x14, Complexity0x15, Complexity0x16, Complexity0x17, Complexity0x18, Complexity0x19, Complexity0x1A, Complexity0x1B, Complexity0x1C, Complexity0x1D, Complexity0x1E, Complexity0x1F, // Operator errors /// 0x20: The operator does not exist. UnsupportedOperator, /// Unallocated Operator0x21, Operator0x22, Operator0x23, Operator0x24, Operator0x25, Operator0x26, Operator0x27, Operator0x28, Operator0x29, Operator0x2A, Operator0x2B, Operator0x2C, Operator0x2D, Operator0x2E, Operator0x2F, // Retrieval-specific errors /// 0x30: At least one of the sources could not be retrieved, but returned HTTP error. HTTP, /// 0x31: Retrieval of at least one of the sources timed out. RetrievalTimeout, /// Unallocated Retrieval0x32, Retrieval0x33, Retrieval0x34, Retrieval0x35, Retrieval0x36, Retrieval0x37, Retrieval0x38, Retrieval0x39, Retrieval0x3A, Retrieval0x3B, Retrieval0x3C, Retrieval0x3D, Retrieval0x3E, Retrieval0x3F, // Math errors /// 0x40: Math operator caused an underflow. Underflow, /// 0x41: Math operator caused an overflow. Overflow, /// 0x42: Tried to divide by zero. DivisionByZero, /// Unallocated Math0x43, Math0x44, Math0x45, Math0x46, Math0x47, Math0x48, Math0x49, Math0x4A, Math0x4B, Math0x4C, Math0x4D, Math0x4E, Math0x4F, // Other errors /// 0x50: Received zero reveals NoReveals, /// 0x51: Insufficient consensus in tally precondition clause InsufficientConsensus, /// 0x52: Received zero commits InsufficientCommits, /// 0x53: Generic error during tally execution TallyExecution, /// Unallocated OtherError0x54, OtherError0x55, OtherError0x56, OtherError0x57, OtherError0x58, OtherError0x59, OtherError0x5A, OtherError0x5B, OtherError0x5C, OtherError0x5D, OtherError0x5E, OtherError0x5F, /// 0x60: Invalid reveal serialization (malformed reveals are converted to this value) MalformedReveal, /// Unallocated OtherError0x61, OtherError0x62, OtherError0x63, OtherError0x64, OtherError0x65, OtherError0x66, OtherError0x67, OtherError0x68, OtherError0x69, OtherError0x6A, OtherError0x6B, OtherError0x6C, OtherError0x6D, OtherError0x6E, OtherError0x6F, // Access errors /// 0x70: Tried to access a value from an index using an index that is out of bounds ArrayIndexOutOfBounds, /// 0x71: Tried to access a value from a map using a key that does not exist MapKeyNotFound, /// Unallocated OtherError0x72, OtherError0x73, OtherError0x74, OtherError0x75, OtherError0x76, OtherError0x77, OtherError0x78, OtherError0x79, OtherError0x7A, OtherError0x7B, OtherError0x7C, OtherError0x7D, OtherError0x7E, OtherError0x7F, OtherError0x80, OtherError0x81, OtherError0x82, OtherError0x83, OtherError0x84, OtherError0x85, OtherError0x86, OtherError0x87, OtherError0x88, OtherError0x89, OtherError0x8A, OtherError0x8B, OtherError0x8C, OtherError0x8D, OtherError0x8E, OtherError0x8F, OtherError0x90, OtherError0x91, OtherError0x92, OtherError0x93, OtherError0x94, OtherError0x95, OtherError0x96, OtherError0x97, OtherError0x98, OtherError0x99, OtherError0x9A, OtherError0x9B, OtherError0x9C, OtherError0x9D, OtherError0x9E, OtherError0x9F, OtherError0xA0, OtherError0xA1, OtherError0xA2, OtherError0xA3, OtherError0xA4, OtherError0xA5, OtherError0xA6, OtherError0xA7, OtherError0xA8, OtherError0xA9, OtherError0xAA, OtherError0xAB, OtherError0xAC, OtherError0xAD, OtherError0xAE, OtherError0xAF, OtherError0xB0, OtherError0xB1, OtherError0xB2, OtherError0xB3, OtherError0xB4, OtherError0xB5, OtherError0xB6, OtherError0xB7, OtherError0xB8, OtherError0xB9, OtherError0xBA, OtherError0xBB, OtherError0xBC, OtherError0xBD, OtherError0xBE, OtherError0xBF, OtherError0xC0, OtherError0xC1, OtherError0xC2, OtherError0xC3, OtherError0xC4, OtherError0xC5, OtherError0xC6, OtherError0xC7, OtherError0xC8, OtherError0xC9, OtherError0xCA, OtherError0xCB, OtherError0xCC, OtherError0xCD, OtherError0xCE, OtherError0xCF, OtherError0xD0, OtherError0xD1, OtherError0xD2, OtherError0xD3, OtherError0xD4, OtherError0xD5, OtherError0xD6, OtherError0xD7, OtherError0xD8, OtherError0xD9, OtherError0xDA, OtherError0xDB, OtherError0xDC, OtherError0xDD, OtherError0xDE, OtherError0xDF, // Bridge errors: errors that only belong in inter-client communication /// 0xE0: Requests that cannot be parsed must always get this error as their result. /// However, this is not a valid result in a Tally transaction, because invalid requests /// are never included into blocks and therefore never get a Tally in response. BridgeMalformedRequest, /// 0xE1: Witnesses exceeds 100 BridgePoorIncentives, /// 0xE2: The request is rejected on the grounds that it may cause the submitter to spend or stake an /// amount of value that is unjustifiably high when compared with the reward they will be getting BridgeOversizedResult, /// Unallocated OtherError0xE3, OtherError0xE4, OtherError0xE5, OtherError0xE6, OtherError0xE7, OtherError0xE8, OtherError0xE9, OtherError0xEA, OtherError0xEB, OtherError0xEC, OtherError0xED, OtherError0xEE, OtherError0xEF, OtherError0xF0, OtherError0xF1, OtherError0xF2, OtherError0xF3, OtherError0xF4, OtherError0xF5, OtherError0xF6, OtherError0xF7, OtherError0xF8, OtherError0xF9, OtherError0xFA, OtherError0xFB, OtherError0xFC, OtherError0xFD, OtherError0xFE, // This should not exist: /// 0xFF: Some tally error is not intercepted but should UnhandledIntercept } } // File: contracts\interfaces\IWitnetRequestBoardRequestor.sol /// @title Witnet Requestor Interface /// @notice It defines how to interact with the Witnet Request Board in order to: /// - request the execution of Witnet Radon scripts (data request); /// - upgrade the resolution reward of any previously posted request, in case gas price raises in mainnet; /// - read the result of any previously posted request, eventually reported by the Witnet DON. /// - remove from storage all data related to past and solved data requests, and results. /// @author The Witnet Foundation. interface IWitnetRequestBoardRequestor { /// Retrieves a copy of all Witnet-provided data related to a previously posted request, removing the whole query from the WRB storage. /// @dev Fails if the `_queryId` is not in 'Reported' status, or called from an address different to /// @dev the one that actually posted the given request. /// @param _queryId The unique query identifier. function deleteQuery(uint256 _queryId) external returns (Witnet.Response memory); /// Requests the execution of the given Witnet Data Request in expectation that it will be relayed and solved by the Witnet DON. /// A reward amount is escrowed by the Witnet Request Board that will be transferred to the reporter who relays back the Witnet-provided /// result to this request. /// @dev Fails if: /// @dev - provided reward is too low. /// @dev - provided script is zero address. /// @dev - provided script bytecode is empty. /// @param _addr The address of the IWitnetRequest contract that can provide the actual Data Request bytecode. /// @return _queryId An unique query identifier. function postRequest(IWitnetRequest _addr) external payable returns (uint256 _queryId); /// Increments the reward of a previously posted request by adding the transaction value to it. /// @dev Updates request `gasPrice` in case this method is called with a higher /// @dev gas price value than the one used in previous calls to `postRequest` or /// @dev `upgradeReward`. /// @dev Fails if the `_queryId` is not in 'Posted' status. /// @dev Fails also in case the request `gasPrice` is increased, and the new /// @dev reward value gets below new recalculated threshold. /// @param _queryId The unique query identifier. function upgradeReward(uint256 _queryId) external payable; } // File: contracts\interfaces\IWitnetRequestBoardView.sol /// @title Witnet Request Board info interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardView { /// Estimates the amount of reward we need to insert for a given gas price. /// @param _gasPrice The gas price for which we need to calculate the rewards. function estimateReward(uint256 _gasPrice) external view returns (uint256); /// Returns next query id to be generated by the Witnet Request Board. function getNextQueryId() external view returns (uint256); /// Gets the whole Query data contents, if any, no matter its current status. function getQueryData(uint256 _queryId) external view returns (Witnet.Query memory); /// Gets current status of given query. function getQueryStatus(uint256 _queryId) external view returns (Witnet.QueryStatus); /// Retrieves the whole `Witnet.Request` record referred to a previously posted Witnet Data Request. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequest(uint256 _queryId) external view returns (Witnet.Request memory); /// Retrieves the serialized bytecode of a previously posted Witnet Data Request. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequestBytecode(uint256 _queryId) external view returns (bytes memory); /// Retrieves the gas price that any assigned reporter will have to pay when reporting result /// to the referred query. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequestGasPrice(uint256 _queryId) external view returns (uint256); /// Retrieves the reward currently set for the referred query. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequestReward(uint256 _queryId) external view returns (uint256); /// Retrieves the whole `Witnet.Response` record referred to a previously posted Witnet Data Request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponse(uint256 _queryId) external view returns (Witnet.Response memory); /// Retrieves the hash of the Witnet transaction hash that actually solved the referred query. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseDrTxHash(uint256 _queryId) external view returns (bytes32); /// Retrieves the address that reported the result to a previously-posted request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseReporter(uint256 _queryId) external view returns (address); /// Retrieves the Witnet-provided CBOR-bytes result of a previously posted request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseResult(uint256 _queryId) external view returns (Witnet.Result memory); /// Retrieves the timestamp in which the result to the referred query was solved by the Witnet DON. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseTimestamp(uint256 _queryId) external view returns (uint256); } // File: contracts\interfaces\IWitnetRequestParser.sol /// @title The Witnet interface for decoding Witnet-provided request to Data Requests. /// This interface exposes functions to check for the success/failure of /// a Witnet-provided result, as well as to parse and convert result into /// Solidity types suitable to the application level. /// @author The Witnet Foundation. interface IWitnetRequestParser { /// Decode raw CBOR bytes into a Witnet.Result instance. /// @param _cborBytes Raw bytes representing a CBOR-encoded value. /// @return A `Witnet.Result` instance. function resultFromCborBytes(bytes memory _cborBytes) external pure returns (Witnet.Result memory); /// Decode a CBOR value into a Witnet.Result instance. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return A `Witnet.Result` instance. function resultFromCborValue(Witnet.CBOR memory _cborValue) external pure returns (Witnet.Result memory); /// Tell if a Witnet.Result is successful. /// @param _result An instance of Witnet.Result. /// @return `true` if successful, `false` if errored. function isOk(Witnet.Result memory _result) external pure returns (bool); /// Tell if a Witnet.Result is errored. /// @param _result An instance of Witnet.Result. /// @return `true` if errored, `false` if successful. function isError(Witnet.Result memory _result) external pure returns (bool); /// Decode a bytes value from a Witnet.Result as a `bytes` value. /// @param _result An instance of Witnet.Result. /// @return The `bytes` decoded from the Witnet.Result. function asBytes(Witnet.Result memory _result) external pure returns (bytes memory); /// Decode an error code from a Witnet.Result as a member of `Witnet.ErrorCodes`. /// @param _result An instance of `Witnet.Result`. /// @return The `CBORValue.Error memory` decoded from the Witnet.Result. function asErrorCode(Witnet.Result memory _result) external pure returns (Witnet.ErrorCodes); /// Generate a suitable error message for a member of `Witnet.ErrorCodes` and its corresponding arguments. /// @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function /// @param _result An instance of `Witnet.Result`. /// @return A tuple containing the `CBORValue.Error memory` decoded from the `Witnet.Result`, plus a loggable error message. function asErrorMessage(Witnet.Result memory _result) external pure returns (Witnet.ErrorCodes, string memory); /// Decode a raw error from a `Witnet.Result` as a `uint64[]`. /// @param _result An instance of `Witnet.Result`. /// @return The `uint64[]` raw error as decoded from the `Witnet.Result`. function asRawError(Witnet.Result memory _result) external pure returns(uint64[] memory); /// Decode a boolean value from a Witnet.Result as an `bool` value. /// @param _result An instance of Witnet.Result. /// @return The `bool` decoded from the Witnet.Result. function asBool(Witnet.Result memory _result) external pure returns (bool); /// Decode a fixed16 (half-precision) numeric value from a Witnet.Result as an `int32` value. /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values. /// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`. /// use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. /// @param _result An instance of Witnet.Result. /// @return The `int128` decoded from the Witnet.Result. function asFixed16(Witnet.Result memory _result) external pure returns (int32); /// Decode an array of fixed16 values from a Witnet.Result as an `int128[]` value. /// @param _result An instance of Witnet.Result. /// @return The `int128[]` decoded from the Witnet.Result. function asFixed16Array(Witnet.Result memory _result) external pure returns (int32[] memory); /// Decode a integer numeric value from a Witnet.Result as an `int128` value. /// @param _result An instance of Witnet.Result. /// @return The `int128` decoded from the Witnet.Result. function asInt128(Witnet.Result memory _result) external pure returns (int128); /// Decode an array of integer numeric values from a Witnet.Result as an `int128[]` value. /// @param _result An instance of Witnet.Result. /// @return The `int128[]` decoded from the Witnet.Result. function asInt128Array(Witnet.Result memory _result) external pure returns (int128[] memory); /// Decode a string value from a Witnet.Result as a `string` value. /// @param _result An instance of Witnet.Result. /// @return The `string` decoded from the Witnet.Result. function asString(Witnet.Result memory _result) external pure returns (string memory); /// Decode an array of string values from a Witnet.Result as a `string[]` value. /// @param _result An instance of Witnet.Result. /// @return The `string[]` decoded from the Witnet.Result. function asStringArray(Witnet.Result memory _result) external pure returns (string[] memory); /// Decode a natural numeric value from a Witnet.Result as a `uint64` value. /// @param _result An instance of Witnet.Result. /// @return The `uint64` decoded from the Witnet.Result. function asUint64(Witnet.Result memory _result) external pure returns(uint64); /// Decode an array of natural numeric values from a Witnet.Result as a `uint64[]` value. /// @param _result An instance of Witnet.Result. /// @return The `uint64[]` decoded from the Witnet.Result. function asUint64Array(Witnet.Result memory _result) external pure returns (uint64[] memory); } // File: contracts\WitnetRequestBoard.sol /// @title Witnet Request Board functionality base contract. /// @author The Witnet Foundation. abstract contract WitnetRequestBoard is IWitnetRequestBoardEvents, IWitnetRequestBoardReporter, IWitnetRequestBoardRequestor, IWitnetRequestBoardView, IWitnetRequestParser { receive() external payable { revert("WitnetRequestBoard: no transfers accepted"); } } // File: contracts\patterns\Proxiable.sol interface Proxiable { /// @dev Complying with EIP-1822: Universal Upgradable Proxy Standard (UUPS) /// @dev See https://eips.ethereum.org/EIPS/eip-1822. function proxiableUUID() external pure returns (bytes32); } // File: contracts\patterns\Initializable.sol interface Initializable { /// @dev Initialize contract's storage context. function initialize(bytes calldata) external; } // File: contracts\patterns\Upgradable.sol /* solhint-disable var-name-mixedcase */ abstract contract Upgradable is Initializable, Proxiable { address internal immutable _BASE; bytes32 internal immutable _CODEHASH; bool internal immutable _UPGRADABLE; /// Emitted every time the contract gets upgraded. /// @param from The address who ordered the upgrading. Namely, the WRB operator in "trustable" implementations. /// @param baseAddr The address of the new implementation contract. /// @param baseCodehash The EVM-codehash of the new implementation contract. /// @param versionTag Ascii-encoded version literal with which the implementation deployer decided to tag it. event Upgraded( address indexed from, address indexed baseAddr, bytes32 indexed baseCodehash, bytes32 versionTag ); constructor (bool _isUpgradable) { address _base = address(this); bytes32 _codehash; assembly { _codehash := extcodehash(_base) } _BASE = _base; _CODEHASH = _codehash; _UPGRADABLE = _isUpgradable; } /// @dev Tells whether provided address could eventually upgrade the contract. function isUpgradableFrom(address from) virtual external view returns (bool); /// TODO: the following methods should be all declared as pure /// whenever this Solidity's PR gets merged and released: /// https://github.com/ethereum/solidity/pull/10240 /// @dev Retrieves base contract. Differs from address(this) when via delegate-proxy pattern. function base() public view returns (address) { return _BASE; } /// @dev Retrieves the immutable codehash of this contract, even if invoked as delegatecall. /// @return _codehash This contracts immutable codehash. function codehash() public view returns (bytes32 _codehash) { return _CODEHASH; } /// @dev Determines whether current instance allows being upgraded. /// @dev Returned value should be invariant from whoever is calling. function isUpgradable() public view returns (bool) { return _UPGRADABLE; } /// @dev Retrieves human-redable named version of current implementation. function version() virtual public view returns (bytes32); } // File: contracts\impls\WitnetProxy.sol /// @title WitnetProxy: upgradable delegate-proxy contract that routes Witnet data requests coming from a /// `UsingWitnet`-inheriting contract to a currently active `WitnetRequestBoard` implementation. /// @author The Witnet Foundation. contract WitnetProxy { struct WitnetProxySlot { address implementation; } /// Event emitted every time the implementation gets updated. event Upgraded(address indexed implementation); /// Constructor with no params as to ease eventual support of Singleton pattern (i.e. ERC-2470). constructor () {} /// WitnetProxies will never accept direct transfer of ETHs. receive() external payable { revert("WitnetProxy: no transfers accepted"); } /// Payable fallback accepts delegating calls to payable functions. fallback() external payable { /* solhint-disable no-complex-fallback */ address _implementation = implementation(); assembly { /* solhint-disable avoid-low-level-calls */ // Gas optimized delegate call to 'implementation' contract. // Note: `msg.data`, `msg.sender` and `msg.value` will be passed over // to actual implementation of `msg.sig` within `implementation` contract. let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _implementation, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { // pass back revert message: revert(ptr, size) } default { // pass back same data as returned by 'implementation' contract: return(ptr, size) } } } /// Returns proxy's current implementation address. function implementation() public view returns (address) { return _proxySlot().implementation; } /// Upgrades the `implementation` address. /// @param _newImplementation New implementation address. /// @param _initData Raw data with which new implementation will be initialized. /// @return Returns whether new implementation would be further upgradable, or not. function upgradeTo(address _newImplementation, bytes memory _initData) public returns (bool) { // New implementation cannot be null: require(_newImplementation != address(0), "WitnetProxy: null implementation"); address _oldImplementation = implementation(); if (_oldImplementation != address(0)) { // New implementation address must differ from current one: require(_newImplementation != _oldImplementation, "WitnetProxy: nothing to upgrade"); // Assert whether current implementation is intrinsically upgradable: try Upgradable(_oldImplementation).isUpgradable() returns (bool _isUpgradable) { require(_isUpgradable, "WitnetProxy: not upgradable"); } catch { revert("WitnetProxy: unable to check upgradability"); } // Assert whether current implementation allows `msg.sender` to upgrade the proxy: (bool _wasCalled, bytes memory _result) = _oldImplementation.delegatecall( abi.encodeWithSignature( "isUpgradableFrom(address)", msg.sender ) ); require(_wasCalled, "WitnetProxy: not compliant"); require(abi.decode(_result, (bool)), "WitnetProxy: not authorized"); require( Upgradable(_oldImplementation).proxiableUUID() == Upgradable(_newImplementation).proxiableUUID(), "WitnetProxy: proxiableUUIDs mismatch" ); } // Initialize new implementation within proxy-context storage: (bool _wasInitialized,) = _newImplementation.delegatecall( abi.encodeWithSignature( "initialize(bytes)", _initData ) ); require(_wasInitialized, "WitnetProxy: unable to initialize"); // If all checks and initialization pass, update implementation address: _proxySlot().implementation = _newImplementation; emit Upgraded(_newImplementation); // Asserts new implementation complies w/ minimal implementation of Upgradable interface: try Upgradable(_newImplementation).isUpgradable() returns (bool _isUpgradable) { return _isUpgradable; } catch { revert ("WitnetProxy: not compliant"); } } /// @dev Complying with EIP-1967, retrieves storage struct containing proxy's current implementation address. function _proxySlot() private pure returns (WitnetProxySlot storage _slot) { assembly { // bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1) _slot.slot := 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc } } } // File: contracts\impls\WitnetRequestBoardUpgradableBase.sol /* solhint-disable var-name-mixedcase */ // Inherits from: // Eventual deployment dependencies: /// @title Witnet Request Board base contract, with an Upgradable (and Destructible) touch. /// @author The Witnet Foundation. abstract contract WitnetRequestBoardUpgradableBase is Proxiable, Upgradable, WitnetRequestBoard { bytes32 internal immutable _VERSION; constructor( bool _upgradable, bytes32 _versionTag ) Upgradable(_upgradable) { _VERSION = _versionTag; } /// @dev Reverts if proxy delegatecalls to unexistent method. fallback() external payable { revert("WitnetRequestBoardUpgradableBase: not implemented"); } // ================================================================================================================ // --- Overrides 'Proxiable' -------------------------------------------------------------------------------------- /// @dev Gets immutable "heritage blood line" (ie. genotype) as a Proxiable, and eventually Upgradable, contract. /// If implemented as an Upgradable touch, upgrading this contract to another one with a different /// `proxiableUUID()` value should fail. function proxiableUUID() external pure override returns (bytes32) { return ( /* keccak256("io.witnet.proxiable.board") */ 0x9969c6aff411c5e5f0807500693e8f819ce88529615cfa6cab569b24788a1018 ); } // ================================================================================================================ // --- Overrides 'Upgradable' -------------------------------------------------------------------------------------- /// Retrieves human-readable version tag of current implementation. function version() public view override returns (bytes32) { return _VERSION; } } // File: contracts\data\WitnetBoardData.sol /// @title Witnet Request Board base data model. /// @author The Witnet Foundation. abstract contract WitnetBoardData { bytes32 internal constant _WITNET_BOARD_DATA_SLOTHASH = /* keccak256("io.witnet.boards.data") */ 0xf595240b351bc8f951c2f53b26f4e78c32cb62122cf76c19b7fdda7d4968e183; struct WitnetBoardState { address base; address owner; uint256 numQueries; mapping (uint => Witnet.Query) queries; } constructor() { _state().owner = msg.sender; } /// Asserts the given query is currently in the given status. modifier inStatus(uint256 _queryId, Witnet.QueryStatus _status) { require( _getQueryStatus(_queryId) == _status, _getQueryStatusRevertMessage(_status) ); _; } /// Asserts the given query was previously posted and that it was not yet deleted. modifier notDeleted(uint256 _queryId) { require(_queryId > 0 && _queryId <= _state().numQueries, "WitnetBoardData: not yet posted"); require(_getRequestData(_queryId).requester != address(0), "WitnetBoardData: deleted"); _; } /// Asserts caller corresponds to the current owner. modifier onlyOwner { require(msg.sender == _state().owner, "WitnetBoardData: only owner"); _; } /// Asserts the give query was actually posted before calling this method. modifier wasPosted(uint256 _queryId) { require(_queryId > 0 && _queryId <= _state().numQueries, "WitnetBoardData: not yet posted"); _; } // ================================================================================================================ // --- Internal functions ----------------------------------------------------------------------------------------- /// Gets current status of given query. function _getQueryStatus(uint256 _queryId) internal view returns (Witnet.QueryStatus) { if (_queryId == 0 || _queryId > _state().numQueries) return Witnet.QueryStatus.Unknown; else { Witnet.Query storage _query = _state().queries[_queryId]; if (_query.request.requester == address(0)) return Witnet.QueryStatus.Deleted; else if (_query.response.drTxHash != 0) return Witnet.QueryStatus.Reported; else return Witnet.QueryStatus.Posted; } } function _getQueryStatusRevertMessage(Witnet.QueryStatus _status) internal pure returns (string memory) { if (_status == Witnet.QueryStatus.Posted) { return "WitnetBoardData: not in Posted status"; } else if (_status == Witnet.QueryStatus.Reported) { return "WitnetBoardData: not in Reported status"; } else if (_status == Witnet.QueryStatus.Deleted) { return "WitnetBoardData: not in Deleted status"; } else { return "WitnetBoardData: bad mood"; } } /// Gets the Witnet.Request part of a given query. function _getRequestData(uint256 _queryId) internal view returns (Witnet.Request storage) { return _state().queries[_queryId].request; } /// Gets the Witnet.Result part of a given query. function _getResponseData(uint256 _queryId) internal view returns (Witnet.Response storage) { return _state().queries[_queryId].response; } /// Returns storage pointer to contents of 'WitnetBoardState' struct. function _state() internal pure returns (WitnetBoardState storage _ptr) { assembly { _ptr.slot := _WITNET_BOARD_DATA_SLOTHASH } } } // File: contracts\data\WitnetBoardDataACLs.sol /// @title Witnet Access Control Lists storage layout, for Witnet-trusted request boards. /// @author The Witnet Foundation. abstract contract WitnetBoardDataACLs is WitnetBoardData { bytes32 internal constant _WITNET_BOARD_ACLS_SLOTHASH = /* keccak256("io.witnet.boards.data.acls") */ 0xa6db7263983f337bae2c9fb315730227961d1c1153ae1e10a56b5791465dd6fd; struct WitnetBoardACLs { mapping (address => bool) isReporter_; } constructor() { _acls().isReporter_[msg.sender] = true; } modifier onlyReporters { require( _acls().isReporter_[msg.sender], "WitnetBoardDataACLs: unauthorized reporter" ); _; } // ================================================================================================================ // --- Internal functions ----------------------------------------------------------------------------------------- function _acls() internal pure returns (WitnetBoardACLs storage _struct) { assembly { _struct.slot := _WITNET_BOARD_ACLS_SLOTHASH } } } // File: contracts\interfaces\IWitnetRequestBoardAdmin.sol /// @title Witnet Request Board basic administration interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardAdmin { event OwnershipTransferred(address indexed from, address indexed to); /// Gets admin/owner address. function owner() external view returns (address); /// Transfers ownership. function transferOwnership(address) external; } // File: contracts\interfaces\IWitnetRequestBoardAdminACLs.sol /// @title Witnet Request Board ACLs administration interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardAdminACLs { event ReportersSet(address[] reporters); event ReportersUnset(address[] reporters); /// Tells whether given address is included in the active reporters control list. function isReporter(address) external view returns (bool); /// Adds given addresses to the active reporters control list. /// @dev Can only be called from the owner address. /// @dev Emits the `ReportersSet` event. function setReporters(address[] calldata reporters) external; /// Removes given addresses from the active reporters control list. /// @dev Can only be called from the owner address. /// @dev Emits the `ReportersUnset` event. function unsetReporters(address[] calldata reporters) external; } // File: contracts\libs\WitnetBuffer.sol /// @title A convenient wrapper around the `bytes memory` type that exposes a buffer-like interface /// @notice The buffer has an inner cursor that tracks the final offset of every read, i.e. any subsequent read will /// start with the byte that goes right after the last one in the previous read. /// @dev `uint32` is used here for `cursor` because `uint16` would only enable seeking up to 8KB, which could in some /// theoretical use cases be exceeded. Conversely, `uint32` supports up to 512MB, which cannot credibly be exceeded. /// @author The Witnet Foundation. library WitnetBuffer { // Ensures we access an existing index in an array modifier notOutOfBounds(uint32 index, uint256 length) { require(index < length, "Tried to read from a consumed Buffer (must rewind it first)"); _; } /// @notice Read and consume a certain amount of bytes from the buffer. /// @param _buffer An instance of `Witnet.Buffer`. /// @param _length How many bytes to read and consume from the buffer. /// @return A `bytes memory` containing the first `_length` bytes from the buffer, counting from the cursor position. function read(Witnet.Buffer memory _buffer, uint32 _length) internal pure returns (bytes memory) { // Make sure not to read out of the bounds of the original bytes require(_buffer.cursor + _length <= _buffer.data.length, "Not enough bytes in buffer when reading"); // Create a new `bytes memory destination` value bytes memory destination = new bytes(_length); // Early return in case that bytes length is 0 if (_length != 0) { bytes memory source = _buffer.data; uint32 offset = _buffer.cursor; // Get raw pointers for source and destination uint sourcePointer; uint destinationPointer; assembly { sourcePointer := add(add(source, 32), offset) destinationPointer := add(destination, 32) } // Copy `_length` bytes from source to destination memcpy(destinationPointer, sourcePointer, uint(_length)); // Move the cursor forward by `_length` bytes seek(_buffer, _length, true); } return destination; } /// @notice Read and consume the next byte from the buffer. /// @param _buffer An instance of `Witnet.Buffer`. /// @return The next byte in the buffer counting from the cursor position. function next(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (bytes1) { // Return the byte at the position marked by the cursor and advance the cursor all at once return _buffer.data[_buffer.cursor++]; } /// @notice Move the inner cursor of the buffer to a relative or absolute position. /// @param _buffer An instance of `Witnet.Buffer`. /// @param _offset How many bytes to move the cursor forward. /// @param _relative Whether to count `_offset` from the last position of the cursor (`true`) or the beginning of the /// buffer (`true`). /// @return The final position of the cursor (will equal `_offset` if `_relative` is `false`). // solium-disable-next-line security/no-assign-params function seek(Witnet.Buffer memory _buffer, uint32 _offset, bool _relative) internal pure returns (uint32) { // Deal with relative offsets if (_relative) { require(_offset + _buffer.cursor > _offset, "Integer overflow when seeking"); _offset += _buffer.cursor; } // Make sure not to read out of the bounds of the original bytes require(_offset <= _buffer.data.length, "Not enough bytes in buffer when seeking"); _buffer.cursor = _offset; return _buffer.cursor; } /// @notice Move the inner cursor a number of bytes forward. /// @dev This is a simple wrapper around the relative offset case of `seek()`. /// @param _buffer An instance of `Witnet.Buffer`. /// @param _relativeOffset How many bytes to move the cursor forward. /// @return The final position of the cursor. function seek(Witnet.Buffer memory _buffer, uint32 _relativeOffset) internal pure returns (uint32) { return seek(_buffer, _relativeOffset, true); } /// @notice Move the inner cursor back to the first byte in the buffer. /// @param _buffer An instance of `Witnet.Buffer`. function rewind(Witnet.Buffer memory _buffer) internal pure { _buffer.cursor = 0; } /// @notice Read and consume the next byte from the buffer as an `uint8`. /// @param _buffer An instance of `Witnet.Buffer`. /// @return The `uint8` value of the next byte in the buffer counting from the cursor position. function readUint8(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (uint8) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint8 value; assembly { value := mload(add(add(bytesValue, 1), offset)) } _buffer.cursor++; return value; } /// @notice Read and consume the next 2 bytes from the buffer as an `uint16`. /// @param _buffer An instance of `Witnet.Buffer`. /// @return The `uint16` value of the next 2 bytes in the buffer counting from the cursor position. function readUint16(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 1, _buffer.data.length) returns (uint16) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint16 value; assembly { value := mload(add(add(bytesValue, 2), offset)) } _buffer.cursor += 2; return value; } /// @notice Read and consume the next 4 bytes from the buffer as an `uint32`. /// @param _buffer An instance of `Witnet.Buffer`. /// @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position. function readUint32(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 3, _buffer.data.length) returns (uint32) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint32 value; assembly { value := mload(add(add(bytesValue, 4), offset)) } _buffer.cursor += 4; return value; } /// @notice Read and consume the next 8 bytes from the buffer as an `uint64`. /// @param _buffer An instance of `Witnet.Buffer`. /// @return The `uint64` value of the next 8 bytes in the buffer counting from the cursor position. function readUint64(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 7, _buffer.data.length) returns (uint64) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint64 value; assembly { value := mload(add(add(bytesValue, 8), offset)) } _buffer.cursor += 8; return value; } /// @notice Read and consume the next 16 bytes from the buffer as an `uint128`. /// @param _buffer An instance of `Witnet.Buffer`. /// @return The `uint128` value of the next 16 bytes in the buffer counting from the cursor position. function readUint128(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint128 value; assembly { value := mload(add(add(bytesValue, 16), offset)) } _buffer.cursor += 16; return value; } /// @notice Read and consume the next 32 bytes from the buffer as an `uint256`. /// @return The `uint256` value of the next 32 bytes in the buffer counting from the cursor position. /// @param _buffer An instance of `Witnet.Buffer`. function readUint256(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 31, _buffer.data.length) returns (uint256) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint256 value; assembly { value := mload(add(add(bytesValue, 32), offset)) } _buffer.cursor += 32; return value; } /// @notice Read and consume the next 2 bytes from the buffer as an IEEE 754-2008 floating point number enclosed in an /// `int32`. /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values /// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `float16` /// use cases. In other words, the integer output of this method is 10,000 times the actual value. The input bytes are /// expected to follow the 16-bit base-2 format (a.k.a. `binary16`) in the IEEE 754-2008 standard. /// @param _buffer An instance of `Witnet.Buffer`. /// @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position. function readFloat16(Witnet.Buffer memory _buffer) internal pure returns (int32) { uint32 bytesValue = readUint16(_buffer); // Get bit at position 0 uint32 sign = bytesValue & 0x8000; // Get bits 1 to 5, then normalize to the [-14, 15] range so as to counterweight the IEEE 754 exponent bias int32 exponent = (int32(bytesValue & 0x7c00) >> 10) - 15; // Get bits 6 to 15 int32 significand = int32(bytesValue & 0x03ff); // Add 1024 to the fraction if the exponent is 0 if (exponent == 15) { significand |= 0x400; } // Compute `2 ^ exponent · (1 + fraction / 1024)` int32 result = 0; if (exponent >= 0) { result = int32((int256(1 << uint256(int256(exponent))) * 10000 * int256(uint256(int256(significand)) | 0x400)) >> 10); } else { result = int32(((int256(uint256(int256(significand)) | 0x400) * 10000) / int256(1 << uint256(int256(- exponent)))) >> 10); } // Make the result negative if the sign bit is not 0 if (sign != 0) { result *= - 1; } return result; } /// @notice Copy bytes from one memory address into another. /// @dev This function was borrowed from Nick Johnson's `solidity-stringutils` lib, and reproduced here under the terms /// of [Apache License 2.0](https://github.com/Arachnid/solidity-stringutils/blob/master/LICENSE). /// @param _dest Address of the destination memory. /// @param _src Address to the source memory. /// @param _len How many bytes to copy. // solium-disable-next-line security/no-assign-params function memcpy(uint _dest, uint _src, uint _len) private pure { require(_len > 0, "Cannot copy 0 bytes"); // Copy word-length chunks while possible for (; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } if (_len > 0) { // 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: contracts\libs\WitnetDecoderLib.sol /// @title A minimalistic implementation of “RFC 7049 Concise Binary Object Representation” /// @notice This library leverages a buffer-like structure for step-by-step decoding of bytes so as to minimize /// the gas cost of decoding them into a useful native type. /// @dev Most of the logic has been borrowed from Patrick Gansterer’s cbor.js library: https://github.com/paroga/cbor-js /// @author The Witnet Foundation. /// /// TODO: add support for Array (majorType = 4) /// TODO: add support for Map (majorType = 5) /// TODO: add support for Float32 (majorType = 7, additionalInformation = 26) /// TODO: add support for Float64 (majorType = 7, additionalInformation = 27) library WitnetDecoderLib { using WitnetBuffer for Witnet.Buffer; uint32 constant internal _UINT32_MAX = type(uint32).max; uint64 constant internal _UINT64_MAX = type(uint64).max; /// @notice Decode a `Witnet.CBOR` structure into a native `bool` value. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as a `bool` value. function decodeBool(Witnet.CBOR memory _cborValue) public pure returns(bool) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(_cborValue.majorType == 7, "Tried to read a `bool` value from a `Witnet.CBOR` with majorType != 7"); if (_cborValue.len == 20) { return false; } else if (_cborValue.len == 21) { return true; } else { revert("Tried to read `bool` from a `Witnet.CBOR` with len different than 20 or 21"); } } /// @notice Decode a `Witnet.CBOR` structure into a native `bytes` value. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as a `bytes` value. function decodeBytes(Witnet.CBOR memory _cborValue) public pure returns(bytes memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == _UINT32_MAX) { bytes memory bytesData; // These checks look repetitive but the equivalent loop would be more expensive. uint32 itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType)); if (itemLength < _UINT32_MAX) { bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength)); itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType)); if (itemLength < _UINT32_MAX) { bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength)); } } return bytesData; } else { return _cborValue.buffer.read(uint32(_cborValue.len)); } } /// @notice Decode a `Witnet.CBOR` structure into a `fixed16` value. /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values /// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16` /// use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as an `int128` value. function decodeFixed16(Witnet.CBOR memory _cborValue) public pure returns(int32) { require(_cborValue.majorType == 7, "Tried to read a `fixed` value from a `WT.CBOR` with majorType != 7"); require(_cborValue.additionalInformation == 25, "Tried to read `fixed16` from a `WT.CBOR` with additionalInformation != 25"); return _cborValue.buffer.readFloat16(); } /// @notice Decode a `Witnet.CBOR` structure into a native `int128[]` value whose inner values follow the same convention. /// as explained in `decodeFixed16`. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as an `int128[]` value. function decodeFixed16Array(Witnet.CBOR memory _cborValue) external pure returns(int32[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `Witnet.CBOR` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < _UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int32[] memory array = new int32[](length); for (uint64 i = 0; i < length; i++) { Witnet.CBOR memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeFixed16(item); } return array; } /// @notice Decode a `Witnet.CBOR` structure into a native `int128` value. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as an `int128` value. function decodeInt128(Witnet.CBOR memory _cborValue) public pure returns(int128) { if (_cborValue.majorType == 1) { uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); return int128(-1) - int128(uint128(length)); } else if (_cborValue.majorType == 0) { // Any `uint64` can be safely casted to `int128`, so this method supports majorType 1 as well so as to have offer // a uniform API for positive and negative numbers return int128(uint128(decodeUint64(_cborValue))); } revert("Tried to read `int128` from a `Witnet.CBOR` with majorType not 0 or 1"); } /// @notice Decode a `Witnet.CBOR` structure into a native `int128[]` value. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as an `int128[]` value. function decodeInt128Array(Witnet.CBOR memory _cborValue) external pure returns(int128[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `Witnet.CBOR` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < _UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int128[] memory array = new int128[](length); for (uint64 i = 0; i < length; i++) { Witnet.CBOR memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeInt128(item); } return array; } /// @notice Decode a `Witnet.CBOR` structure into a native `string` value. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as a `string` value. function decodeString(Witnet.CBOR memory _cborValue) public pure returns(string memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == _UINT64_MAX) { bytes memory textData; bool done; while (!done) { uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType); if (itemLength < _UINT64_MAX) { textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4)); } else { done = true; } } return string(textData); } else { return string(readText(_cborValue.buffer, _cborValue.len)); } } /// @notice Decode a `Witnet.CBOR` structure into a native `string[]` value. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as an `string[]` value. function decodeStringArray(Witnet.CBOR memory _cborValue) external pure returns(string[] memory) { require(_cborValue.majorType == 4, "Tried to read `string[]` from a `Witnet.CBOR` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < _UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); string[] memory array = new string[](length); for (uint64 i = 0; i < length; i++) { Witnet.CBOR memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeString(item); } return array; } /// @notice Decode a `Witnet.CBOR` structure into a native `uint64` value. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as an `uint64` value. function decodeUint64(Witnet.CBOR memory _cborValue) public pure returns(uint64) { require(_cborValue.majorType == 0, "Tried to read `uint64` from a `Witnet.CBOR` with majorType != 0"); return readLength(_cborValue.buffer, _cborValue.additionalInformation); } /// @notice Decode a `Witnet.CBOR` structure into a native `uint64[]` value. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as an `uint64[]` value. function decodeUint64Array(Witnet.CBOR memory _cborValue) external pure returns(uint64[] memory) { require(_cborValue.majorType == 4, "Tried to read `uint64[]` from a `Witnet.CBOR` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < _UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); uint64[] memory array = new uint64[](length); for (uint64 i = 0; i < length; i++) { Witnet.CBOR memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeUint64(item); } return array; } /// @notice Decode a Witnet.CBOR structure from raw bytes. /// @dev This is the main factory for Witnet.CBOR instances, which can be later decoded into native EVM types. /// @param _cborBytes Raw bytes representing a CBOR-encoded value. /// @return A `Witnet.CBOR` instance containing a partially decoded value. function valueFromBytes(bytes memory _cborBytes) external pure returns(Witnet.CBOR memory) { Witnet.Buffer memory buffer = Witnet.Buffer(_cborBytes, 0); return valueFromBuffer(buffer); } /// @notice Decode a Witnet.CBOR structure from raw bytes. /// @dev This is an alternate factory for Witnet.CBOR instances, which can be later decoded into native EVM types. /// @param _buffer A Buffer structure representing a CBOR-encoded value. /// @return A `Witnet.CBOR` instance containing a partially decoded value. function valueFromBuffer(Witnet.Buffer memory _buffer) public pure returns(Witnet.CBOR memory) { require(_buffer.data.length > 0, "Found empty buffer when parsing CBOR value"); uint8 initialByte; uint8 majorType = 255; uint8 additionalInformation; uint64 tag = _UINT64_MAX; bool isTagged = true; while (isTagged) { // Extract basic CBOR properties from input bytes initialByte = _buffer.readUint8(); majorType = initialByte >> 5; additionalInformation = initialByte & 0x1f; // Early CBOR tag parsing. if (majorType == 6) { tag = readLength(_buffer, additionalInformation); } else { isTagged = false; } } require(majorType <= 7, "Invalid CBOR major type"); return Witnet.CBOR( _buffer, initialByte, majorType, additionalInformation, 0, tag); } /// Reads the length of the next CBOR item from a buffer, consuming a different number of bytes depending on the /// value of the `additionalInformation` argument. function readLength(Witnet.Buffer memory _buffer, uint8 additionalInformation) private pure returns(uint64) { if (additionalInformation < 24) { return additionalInformation; } if (additionalInformation == 24) { return _buffer.readUint8(); } if (additionalInformation == 25) { return _buffer.readUint16(); } if (additionalInformation == 26) { return _buffer.readUint32(); } if (additionalInformation == 27) { return _buffer.readUint64(); } if (additionalInformation == 31) { return _UINT64_MAX; } revert("Invalid length encoding (non-existent additionalInformation value)"); } /// Read the length of a CBOR indifinite-length item (arrays, maps, byte strings and text) from a buffer, consuming /// as many bytes as specified by the first byte. function readIndefiniteStringLength(Witnet.Buffer memory _buffer, uint8 majorType) private pure returns(uint64) { uint8 initialByte = _buffer.readUint8(); if (initialByte == 0xff) { return _UINT64_MAX; } uint64 length = readLength(_buffer, initialByte & 0x1f); require(length < _UINT64_MAX && (initialByte >> 5) == majorType, "Invalid indefinite length"); return length; } /// Read a text string of a given length from a buffer. Returns a `bytes memory` value for the sake of genericness, /// but it can be easily casted into a string with `string(result)`. // solium-disable-next-line security/no-assign-params function readText(Witnet.Buffer memory _buffer, uint64 _length) private pure returns(bytes memory) { bytes memory result; for (uint64 index = 0; index < _length; index++) { uint8 value = _buffer.readUint8(); if (value & 0x80 != 0) { if (value < 0xe0) { value = (value & 0x1f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 1; } else if (value < 0xf0) { value = (value & 0x0f) << 12 | (_buffer.readUint8() & 0x3f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 2; } else { value = (value & 0x0f) << 18 | (_buffer.readUint8() & 0x3f) << 12 | (_buffer.readUint8() & 0x3f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 3; } } result = abi.encodePacked(result, value); } return result; } } // File: contracts\libs\WitnetParserLib.sol /// @title A library for decoding Witnet request results /// @notice The library exposes functions to check the Witnet request success. /// and retrieve Witnet results from CBOR values into solidity types. /// @author The Witnet Foundation. library WitnetParserLib { using WitnetDecoderLib for bytes; using WitnetDecoderLib for Witnet.CBOR; /// @notice Decode raw CBOR bytes into a Witnet.Result instance. /// @param _cborBytes Raw bytes representing a CBOR-encoded value. /// @return A `Witnet.Result` instance. function resultFromCborBytes(bytes calldata _cborBytes) external pure returns (Witnet.Result memory) { Witnet.CBOR memory cborValue = _cborBytes.valueFromBytes(); return resultFromCborValue(cborValue); } /// @notice Decode a CBOR value into a Witnet.Result instance. /// @param _cborValue An instance of `Witnet.Value`. /// @return A `Witnet.Result` instance. function resultFromCborValue(Witnet.CBOR memory _cborValue) public pure returns (Witnet.Result memory) { // Witnet uses CBOR tag 39 to represent RADON error code identifiers. // [CBOR tag 39] Identifiers for CBOR: https://github.com/lucas-clemente/cbor-specs/blob/master/id.md bool success = _cborValue.tag != 39; return Witnet.Result(success, _cborValue); } /// @notice Tell if a Witnet.Result is successful. /// @param _result An instance of Witnet.Result. /// @return `true` if successful, `false` if errored. function isOk(Witnet.Result memory _result) external pure returns (bool) { return _result.success; } /// @notice Tell if a Witnet.Result is errored. /// @param _result An instance of Witnet.Result. /// @return `true` if errored, `false` if successful. function isError(Witnet.Result memory _result) external pure returns (bool) { return !_result.success; } /// @notice Decode a bytes value from a Witnet.Result as a `bytes` value. /// @param _result An instance of Witnet.Result. /// @return The `bytes` decoded from the Witnet.Result. function asBytes(Witnet.Result memory _result) external pure returns(bytes memory) { require(_result.success, "WitnetParserLib: tried to read bytes value from errored Witnet.Result"); return _result.value.decodeBytes(); } /// @notice Decode an error code from a Witnet.Result as a member of `Witnet.ErrorCodes`. /// @param _result An instance of `Witnet.Result`. /// @return The `CBORValue.Error memory` decoded from the Witnet.Result. function asErrorCode(Witnet.Result memory _result) external pure returns (Witnet.ErrorCodes) { uint64[] memory error = asRawError(_result); if (error.length == 0) { return Witnet.ErrorCodes.Unknown; } return _supportedErrorOrElseUnknown(error[0]); } /// @notice Generate a suitable error message for a member of `Witnet.ErrorCodes` and its corresponding arguments. /// @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function /// @param _result An instance of `Witnet.Result`. /// @return A tuple containing the `CBORValue.Error memory` decoded from the `Witnet.Result`, plus a loggable error message. function asErrorMessage(Witnet.Result memory _result) public pure returns (Witnet.ErrorCodes, string memory) { uint64[] memory error = asRawError(_result); if (error.length == 0) { return (Witnet.ErrorCodes.Unknown, "Unknown error (no error code)"); } Witnet.ErrorCodes errorCode = _supportedErrorOrElseUnknown(error[0]); bytes memory errorMessage; if (errorCode == Witnet.ErrorCodes.SourceScriptNotCBOR && error.length >= 2) { errorMessage = abi.encodePacked("Source script #", _utoa(error[1]), " was not a valid CBOR value"); } else if (errorCode == Witnet.ErrorCodes.SourceScriptNotArray && error.length >= 2) { errorMessage = abi.encodePacked("The CBOR value in script #", _utoa(error[1]), " was not an Array of calls"); } else if (errorCode == Witnet.ErrorCodes.SourceScriptNotRADON && error.length >= 2) { errorMessage = abi.encodePacked("The CBOR value in script #", _utoa(error[1]), " was not a valid Data Request"); } else if (errorCode == Witnet.ErrorCodes.RequestTooManySources && error.length >= 2) { errorMessage = abi.encodePacked("The request contained too many sources (", _utoa(error[1]), ")"); } else if (errorCode == Witnet.ErrorCodes.ScriptTooManyCalls && error.length >= 4) { errorMessage = abi.encodePacked( "Script #", _utoa(error[2]), " from the ", stageName(error[1]), " stage contained too many calls (", _utoa(error[3]), ")" ); } else if (errorCode == Witnet.ErrorCodes.UnsupportedOperator && error.length >= 5) { errorMessage = abi.encodePacked( "Operator code 0x", utohex(error[4]), " found at call #", _utoa(error[3]), " in script #", _utoa(error[2]), " from ", stageName(error[1]), " stage is not supported" ); } else if (errorCode == Witnet.ErrorCodes.HTTP && error.length >= 3) { errorMessage = abi.encodePacked( "Source #", _utoa(error[1]), " could not be retrieved. Failed with HTTP error code: ", _utoa(error[2] / 100), _utoa(error[2] % 100 / 10), _utoa(error[2] % 10) ); } else if (errorCode == Witnet.ErrorCodes.RetrievalTimeout && error.length >= 2) { errorMessage = abi.encodePacked( "Source #", _utoa(error[1]), " could not be retrieved because of a timeout" ); } else if (errorCode == Witnet.ErrorCodes.Underflow && error.length >= 5) { errorMessage = abi.encodePacked( "Underflow at operator code 0x", utohex(error[4]), " found at call #", _utoa(error[3]), " in script #", _utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == Witnet.ErrorCodes.Overflow && error.length >= 5) { errorMessage = abi.encodePacked( "Overflow at operator code 0x", utohex(error[4]), " found at call #", _utoa(error[3]), " in script #", _utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == Witnet.ErrorCodes.DivisionByZero && error.length >= 5) { errorMessage = abi.encodePacked( "Division by zero at operator code 0x", utohex(error[4]), " found at call #", _utoa(error[3]), " in script #", _utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == Witnet.ErrorCodes.BridgeMalformedRequest) { errorMessage = "The structure of the request is invalid and it cannot be parsed"; } else if (errorCode == Witnet.ErrorCodes.BridgePoorIncentives) { errorMessage = "The request has been rejected by the bridge node due to poor incentives"; } else if (errorCode == Witnet.ErrorCodes.BridgeOversizedResult) { errorMessage = "The request result length exceeds a bridge contract defined limit"; } else { errorMessage = abi.encodePacked("Unknown error (0x", utohex(error[0]), ")"); } return (errorCode, string(errorMessage)); } /// @notice Decode a raw error from a `Witnet.Result` as a `uint64[]`. /// @param _result An instance of `Witnet.Result`. /// @return The `uint64[]` raw error as decoded from the `Witnet.Result`. function asRawError(Witnet.Result memory _result) public pure returns(uint64[] memory) { require(!_result.success, "WitnetParserLib: Tried to read error code from successful Witnet.Result"); return _result.value.decodeUint64Array(); } /// @notice Decode a boolean value from a Witnet.Result as an `bool` value. /// @param _result An instance of Witnet.Result. /// @return The `bool` decoded from the Witnet.Result. function asBool(Witnet.Result memory _result) external pure returns (bool) { require(_result.success, "WitnetParserLib: Tried to read `bool` value from errored Witnet.Result"); return _result.value.decodeBool(); } /// @notice Decode a fixed16 (half-precision) numeric value from a Witnet.Result as an `int32` value. /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values. /// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`. /// use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. /// @param _result An instance of Witnet.Result. /// @return The `int128` decoded from the Witnet.Result. function asFixed16(Witnet.Result memory _result) external pure returns (int32) { require(_result.success, "WitnetParserLib: Tried to read `fixed16` value from errored Witnet.Result"); return _result.value.decodeFixed16(); } /// @notice Decode an array of fixed16 values from a Witnet.Result as an `int128[]` value. /// @param _result An instance of Witnet.Result. /// @return The `int128[]` decoded from the Witnet.Result. function asFixed16Array(Witnet.Result memory _result) external pure returns (int32[] memory) { require(_result.success, "WitnetParserLib: Tried to read `fixed16[]` value from errored Witnet.Result"); return _result.value.decodeFixed16Array(); } /// @notice Decode a integer numeric value from a Witnet.Result as an `int128` value. /// @param _result An instance of Witnet.Result. /// @return The `int128` decoded from the Witnet.Result. function asInt128(Witnet.Result memory _result) external pure returns (int128) { require(_result.success, "WitnetParserLib: Tried to read `int128` value from errored Witnet.Result"); return _result.value.decodeInt128(); } /// @notice Decode an array of integer numeric values from a Witnet.Result as an `int128[]` value. /// @param _result An instance of Witnet.Result. /// @return The `int128[]` decoded from the Witnet.Result. function asInt128Array(Witnet.Result memory _result) external pure returns (int128[] memory) { require(_result.success, "WitnetParserLib: Tried to read `int128[]` value from errored Witnet.Result"); return _result.value.decodeInt128Array(); } /// @notice Decode a string value from a Witnet.Result as a `string` value. /// @param _result An instance of Witnet.Result. /// @return The `string` decoded from the Witnet.Result. function asString(Witnet.Result memory _result) external pure returns(string memory) { require(_result.success, "WitnetParserLib: Tried to read `string` value from errored Witnet.Result"); return _result.value.decodeString(); } /// @notice Decode an array of string values from a Witnet.Result as a `string[]` value. /// @param _result An instance of Witnet.Result. /// @return The `string[]` decoded from the Witnet.Result. function asStringArray(Witnet.Result memory _result) external pure returns (string[] memory) { require(_result.success, "WitnetParserLib: Tried to read `string[]` value from errored Witnet.Result"); return _result.value.decodeStringArray(); } /// @notice Decode a natural numeric value from a Witnet.Result as a `uint64` value. /// @param _result An instance of Witnet.Result. /// @return The `uint64` decoded from the Witnet.Result. function asUint64(Witnet.Result memory _result) external pure returns(uint64) { require(_result.success, "WitnetParserLib: Tried to read `uint64` value from errored Witnet.Result"); return _result.value.decodeUint64(); } /// @notice Decode an array of natural numeric values from a Witnet.Result as a `uint64[]` value. /// @param _result An instance of Witnet.Result. /// @return The `uint64[]` decoded from the Witnet.Result. function asUint64Array(Witnet.Result memory _result) external pure returns (uint64[] memory) { require(_result.success, "WitnetParserLib: Tried to read `uint64[]` value from errored Witnet.Result"); return _result.value.decodeUint64Array(); } /// @notice Convert a stage index number into the name of the matching Witnet request stage. /// @param _stageIndex A `uint64` identifying the index of one of the Witnet request stages. /// @return The name of the matching stage. function stageName(uint64 _stageIndex) public pure returns (string memory) { if (_stageIndex == 0) { return "retrieval"; } else if (_stageIndex == 1) { return "aggregation"; } else if (_stageIndex == 2) { return "tally"; } else { return "unknown"; } } /// @notice Get an `Witnet.ErrorCodes` item from its `uint64` discriminant. /// @param _discriminant The numeric identifier of an error. /// @return A member of `Witnet.ErrorCodes`. function _supportedErrorOrElseUnknown(uint64 _discriminant) private pure returns (Witnet.ErrorCodes) { return Witnet.ErrorCodes(_discriminant); } /// @notice Convert a `uint64` into a 1, 2 or 3 characters long `string` representing its. /// three less significant decimal values. /// @param _u A `uint64` value. /// @return The `string` representing its decimal value. function _utoa(uint64 _u) private pure returns (string memory) { if (_u < 10) { bytes memory b1 = new bytes(1); b1[0] = bytes1(uint8(_u) + 48); return string(b1); } else if (_u < 100) { bytes memory b2 = new bytes(2); b2[0] = bytes1(uint8(_u / 10) + 48); b2[1] = bytes1(uint8(_u % 10) + 48); return string(b2); } else { bytes memory b3 = new bytes(3); b3[0] = bytes1(uint8(_u / 100) + 48); b3[1] = bytes1(uint8(_u % 100 / 10) + 48); b3[2] = bytes1(uint8(_u % 10) + 48); return string(b3); } } /// @notice Convert a `uint64` into a 2 characters long `string` representing its two less significant hexadecimal values. /// @param _u A `uint64` value. /// @return The `string` representing its hexadecimal value. function utohex(uint64 _u) private pure returns (string memory) { bytes memory b2 = new bytes(2); uint8 d0 = uint8(_u / 16) + 48; uint8 d1 = uint8(_u % 16) + 48; if (d0 > 57) d0 += 7; if (d1 > 57) d1 += 7; b2[0] = bytes1(d0); b2[1] = bytes1(d1); return string(b2); } } // File: contracts\interfaces\IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /// Returns the amount of tokens in existence. function totalSupply() external view returns (uint256); /// Returns the amount of tokens owned by `_account`. function balanceOf(address _account) external view returns (uint256); /// 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); /// 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); /// 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); /// 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); /// 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); /// 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\patterns\Payable.sol abstract contract Payable { IERC20 public immutable currency; event Received(address from, uint256 amount); event Transfer(address to, uint256 amount); constructor(address _currency) { currency = IERC20(_currency); } /// Gets current transaction price. function _getGasPrice() internal view virtual returns (uint256); /// Gets current payment value. function _getMsgValue() internal view virtual returns (uint256); /// Perform safe transfer or whatever token is used for paying rewards. function _safeTransferTo(address payable, uint256) internal virtual; } // File: contracts\impls\trustable\WitnetRequestBoardTrustableBase.sol /// @title Witnet Request Board "trustable" base implementation contract. /// @notice Contract to bridge requests to Witnet Decentralized Oracle Network. /// @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network. /// The result of the requests will be posted back to this contract by the bridge nodes too. /// @author The Witnet Foundation abstract contract WitnetRequestBoardTrustableBase is Payable, IWitnetRequestBoardAdmin, IWitnetRequestBoardAdminACLs, WitnetBoardDataACLs, WitnetRequestBoardUpgradableBase { using Witnet for bytes; using WitnetParserLib for Witnet.Result; constructor(bool _upgradable, bytes32 _versionTag, address _currency) Payable(_currency) WitnetRequestBoardUpgradableBase(_upgradable, _versionTag) {} // ================================================================================================================ // --- Overrides 'Upgradable' ------------------------------------------------------------------------------------- /// Initialize storage-context when invoked as delegatecall. /// @dev Must fail when trying to initialize same instance more than once. function initialize(bytes memory _initData) virtual external override { address _owner = _state().owner; if (_owner == address(0)) { // set owner if none set yet _owner = msg.sender; _state().owner = _owner; } else { // only owner can initialize: require(msg.sender == _owner, "WitnetRequestBoardTrustableBase: only owner"); } if (_state().base != address(0)) { // current implementation cannot be initialized more than once: require(_state().base != base(), "WitnetRequestBoardTrustableBase: already initialized"); } _state().base = base(); emit Upgraded(msg.sender, base(), codehash(), version()); // Do actual base initialization: setReporters(abi.decode(_initData, (address[]))); } /// Tells whether provided address could eventually upgrade the contract. function isUpgradableFrom(address _from) external view override returns (bool) { address _owner = _state().owner; return ( // false if the WRB is intrinsically not upgradable, or `_from` is no owner isUpgradable() && _owner == _from ); } // ================================================================================================================ // --- Full implementation of 'IWitnetRequestBoardAdmin' ---------------------------------------------------------- /// Gets admin/owner address. function owner() public view override returns (address) { return _state().owner; } /// Transfers ownership. function transferOwnership(address _newOwner) external virtual override onlyOwner { address _owner = _state().owner; if (_newOwner != _owner) { _state().owner = _newOwner; emit OwnershipTransferred(_owner, _newOwner); } } // ================================================================================================================ // --- Full implementation of 'IWitnetRequestBoardAdminACLs' ------------------------------------------------------ /// Tells whether given address is included in the active reporters control list. /// @param _reporter The address to be checked. function isReporter(address _reporter) public view override returns (bool) { return _acls().isReporter_[_reporter]; } /// Adds given addresses to the active reporters control list. /// @dev Can only be called from the owner address. /// @dev Emits the `ReportersSet` event. /// @param _reporters List of addresses to be added to the active reporters control list. function setReporters(address[] memory _reporters) public override onlyOwner { for (uint ix = 0; ix < _reporters.length; ix ++) { address _reporter = _reporters[ix]; _acls().isReporter_[_reporter] = true; } emit ReportersSet(_reporters); } /// Removes given addresses from the active reporters control list. /// @dev Can only be called from the owner address. /// @dev Emits the `ReportersUnset` event. /// @param _exReporters List of addresses to be added to the active reporters control list. function unsetReporters(address[] memory _exReporters) public override onlyOwner { for (uint ix = 0; ix < _exReporters.length; ix ++) { address _reporter = _exReporters[ix]; _acls().isReporter_[_reporter] = false; } emit ReportersUnset(_exReporters); } // ================================================================================================================ // --- Full implementation of 'IWitnetRequestBoardReporter' ------------------------------------------------------- /// Reports the Witnet-provided result to a previously posted request. /// @dev Will assume `block.timestamp` as the timestamp at which the request was solved. /// @dev Fails if: /// @dev - the `_queryId` is not in 'Posted' status. /// @dev - provided `_drTxHash` is zero; /// @dev - length of provided `_result` is zero. /// @param _queryId The unique identifier of the data request. /// @param _drTxHash The hash of the solving tally transaction in Witnet. /// @param _cborBytes The result itself as bytes. function reportResult( uint256 _queryId, bytes32 _drTxHash, bytes calldata _cborBytes ) external override onlyReporters inStatus(_queryId, Witnet.QueryStatus.Posted) { // solhint-disable not-rely-on-time _reportResult(_queryId, block.timestamp, _drTxHash, _cborBytes); } /// Reports the Witnet-provided result to a previously posted request. /// @dev Fails if: /// @dev - called from unauthorized address; /// @dev - the `_queryId` is not in 'Posted' status. /// @dev - provided `_drTxHash` is zero; /// @dev - length of provided `_result` is zero. /// @param _queryId The unique query identifier /// @param _timestamp The timestamp of the solving tally transaction in Witnet. /// @param _drTxHash The hash of the solving tally transaction in Witnet. /// @param _cborBytes The result itself as bytes. function reportResult( uint256 _queryId, uint256 _timestamp, bytes32 _drTxHash, bytes calldata _cborBytes ) external override onlyReporters inStatus(_queryId, Witnet.QueryStatus.Posted) { _reportResult(_queryId, _timestamp, _drTxHash, _cborBytes); } // ================================================================================================================ // --- Full implementation of 'IWitnetRequestBoardRequestor' ------------------------------------------------------ /// Retrieves copy of all response data related to a previously posted request, removing the whole query from storage. /// @dev Fails if the `_queryId` is not in 'Reported' status, or called from an address different to /// @dev the one that actually posted the given request. /// @param _queryId The unique query identifier. function deleteQuery(uint256 _queryId) public virtual override inStatus(_queryId, Witnet.QueryStatus.Reported) returns (Witnet.Response memory _response) { Witnet.Query storage _query = _state().queries[_queryId]; require( msg.sender == _query.request.requester, "WitnetRequestBoardTrustableBase: only requester" ); _response = _query.response; delete _state().queries[_queryId]; emit DeletedQuery(_queryId, msg.sender); } /// Requests the execution of the given Witnet Data Request in expectation that it will be relayed and solved by the Witnet DON. /// A reward amount is escrowed by the Witnet Request Board that will be transferred to the reporter who relays back the Witnet-provided /// result to this request. /// @dev Fails if: /// @dev - provided reward is too low. /// @dev - provided script is zero address. /// @dev - provided script bytecode is empty. /// @param _addr The address of a IWitnetRequest contract, containing the actual Data Request seralized bytecode. /// @return _queryId An unique query identifier. function postRequest(IWitnetRequest _addr) public payable virtual override returns (uint256 _queryId) { uint256 _value = _getMsgValue(); uint256 _gasPrice = _getGasPrice(); // Checks the tally reward is covering gas cost uint256 minResultReward = estimateReward(_gasPrice); require(_value >= minResultReward, "WitnetRequestBoardTrustableBase: reward too low"); // Validates provided script: require(address(_addr) != address(0), "WitnetRequestBoardTrustableBase: null script"); bytes memory _bytecode = _addr.bytecode(); require(_bytecode.length > 0, "WitnetRequestBoardTrustableBase: empty script"); _queryId = ++ _state().numQueries; Witnet.Request storage _request = _getRequestData(_queryId); _request.requester = msg.sender; _request.addr = _addr; _request.hash = _bytecode.hash(); _request.gasprice = _gasPrice; _request.reward = _value; // Let observers know that a new request has been posted emit PostedRequest(_queryId, msg.sender); } /// Increments the reward of a previously posted request by adding the transaction value to it. /// @dev Updates request `gasPrice` in case this method is called with a higher /// @dev gas price value than the one used in previous calls to `postRequest` or /// @dev `upgradeReward`. /// @dev Fails if the `_queryId` is not in 'Posted' status. /// @dev Fails also in case the request `gasPrice` is increased, and the new /// @dev reward value gets below new recalculated threshold. /// @param _queryId The unique query identifier. function upgradeReward(uint256 _queryId) public payable virtual override inStatus(_queryId, Witnet.QueryStatus.Posted) { Witnet.Request storage _request = _getRequestData(_queryId); uint256 _newReward = _request.reward + _getMsgValue(); uint256 _newGasPrice = _getGasPrice(); // If gas price is increased, then check if new rewards cover gas costs if (_newGasPrice > _request.gasprice) { // Checks the reward is covering gas cost uint256 _minResultReward = estimateReward(_newGasPrice); require( _newReward >= _minResultReward, "WitnetRequestBoardTrustableBase: reward too low" ); _request.gasprice = _newGasPrice; } _request.reward = _newReward; } // ================================================================================================================ // --- Full implementation of 'IWitnetRequestBoardView' ----------------------------------------------------------- /// Estimates the amount of reward we need to insert for a given gas price. /// @param _gasPrice The gas price for which we need to calculate the rewards. function estimateReward(uint256 _gasPrice) public view virtual override returns (uint256); /// Returns next request id to be generated by the Witnet Request Board. function getNextQueryId() external view override returns (uint256) { return _state().numQueries + 1; } /// Gets the whole Query data contents, if any, no matter its current status. function getQueryData(uint256 _queryId) external view override returns (Witnet.Query memory) { return _state().queries[_queryId]; } /// Gets current status of given query. function getQueryStatus(uint256 _queryId) external view override returns (Witnet.QueryStatus) { return _getQueryStatus(_queryId); } /// Retrieves the whole Request record posted to the Witnet Request Board. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique identifier of a previously posted query. function readRequest(uint256 _queryId) external view override notDeleted(_queryId) returns (Witnet.Request memory) { return _checkRequest(_queryId); } /// Retrieves the Witnet data request actual bytecode of a previously posted request. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique identifier of the request query. function readRequestBytecode(uint256 _queryId) external view override notDeleted(_queryId) returns (bytes memory _bytecode) { Witnet.Request storage _request = _getRequestData(_queryId); if (address(_request.addr) != address(0)) { // if DR's request contract address is not zero, // we assume the DR has not been deleted, so // DR's bytecode can still be fetched: _bytecode = _request.addr.bytecode(); require( _bytecode.hash() == _request.hash, "WitnetRequestBoardTrustableBase: bytecode changed after posting" ); } } /// Retrieves the gas price that any assigned reporter will have to pay when reporting /// result to a previously posted Witnet data request. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier function readRequestGasPrice(uint256 _queryId) external view override notDeleted(_queryId) returns (uint256) { return _checkRequest(_queryId).gasprice; } /// Retrieves the reward currently set for a previously posted request. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier function readRequestReward(uint256 _queryId) external view override notDeleted(_queryId) returns (uint256) { return _checkRequest(_queryId).reward; } /// Retrieves the Witnet-provided result, and metadata, to a previously posted request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier function readResponse(uint256 _queryId) external view override inStatus(_queryId, Witnet.QueryStatus.Reported) returns (Witnet.Response memory _response) { return _getResponseData(_queryId); } /// Retrieves the hash of the Witnet transaction that actually solved the referred query. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseDrTxHash(uint256 _queryId) external view override inStatus(_queryId, Witnet.QueryStatus.Reported) returns (bytes32) { return _getResponseData(_queryId).drTxHash; } /// Retrieves the address that reported the result to a previously-posted request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier function readResponseReporter(uint256 _queryId) external view override inStatus(_queryId, Witnet.QueryStatus.Reported) returns (address) { return _getResponseData(_queryId).reporter; } /// Retrieves the Witnet-provided CBOR-bytes result of a previously posted request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier function readResponseResult(uint256 _queryId) external view override inStatus(_queryId, Witnet.QueryStatus.Reported) returns (Witnet.Result memory) { Witnet.Response storage _response = _getResponseData(_queryId); return WitnetParserLib.resultFromCborBytes(_response.cborBytes); } /// Retrieves the timestamp in which the result to the referred query was solved by the Witnet DON. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseTimestamp(uint256 _queryId) external view override inStatus(_queryId, Witnet.QueryStatus.Reported) returns (uint256) { return _getResponseData(_queryId).timestamp; } // ================================================================================================================ // --- Full implementation of 'IWitnetRequestParser' interface ---------------------------------------------------- /// Decode raw CBOR bytes into a Witnet.Result instance. /// @param _cborBytes Raw bytes representing a CBOR-encoded value. /// @return A `Witnet.Result` instance. function resultFromCborBytes(bytes memory _cborBytes) external pure override returns (Witnet.Result memory) { return WitnetParserLib.resultFromCborBytes(_cborBytes); } /// Decode a CBOR value into a Witnet.Result instance. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return A `Witnet.Result` instance. function resultFromCborValue(Witnet.CBOR memory _cborValue) external pure override returns (Witnet.Result memory) { return WitnetParserLib.resultFromCborValue(_cborValue); } /// Tell if a Witnet.Result is successful. /// @param _result An instance of Witnet.Result. /// @return `true` if successful, `false` if errored. function isOk(Witnet.Result memory _result) external pure override returns (bool) { return _result.isOk(); } /// Tell if a Witnet.Result is errored. /// @param _result An instance of Witnet.Result. /// @return `true` if errored, `false` if successful. function isError(Witnet.Result memory _result) external pure override returns (bool) { return _result.isError(); } /// Decode a bytes value from a Witnet.Result as a `bytes` value. /// @param _result An instance of Witnet.Result. /// @return The `bytes` decoded from the Witnet.Result. function asBytes(Witnet.Result memory _result) external pure override returns (bytes memory) { return _result.asBytes(); } /// Decode an error code from a Witnet.Result as a member of `Witnet.ErrorCodes`. /// @param _result An instance of `Witnet.Result`. /// @return The `CBORValue.Error memory` decoded from the Witnet.Result. function asErrorCode(Witnet.Result memory _result) external pure override returns (Witnet.ErrorCodes) { return _result.asErrorCode(); } /// Generate a suitable error message for a member of `Witnet.ErrorCodes` and its corresponding arguments. /// @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function /// @param _result An instance of `Witnet.Result`. /// @return A tuple containing the `CBORValue.Error memory` decoded from the `Witnet.Result`, plus a loggable error message. function asErrorMessage(Witnet.Result memory _result) external pure override returns (Witnet.ErrorCodes, string memory) { return _result.asErrorMessage(); } /// Decode a raw error from a `Witnet.Result` as a `uint64[]`. /// @param _result An instance of `Witnet.Result`. /// @return The `uint64[]` raw error as decoded from the `Witnet.Result`. function asRawError(Witnet.Result memory _result) external pure override returns(uint64[] memory) { return _result.asRawError(); } /// Decode a boolean value from a Witnet.Result as an `bool` value. /// @param _result An instance of Witnet.Result. /// @return The `bool` decoded from the Witnet.Result. function asBool(Witnet.Result memory _result) external pure override returns (bool) { return _result.asBool(); } /// Decode a fixed16 (half-precision) numeric value from a Witnet.Result as an `int32` value. /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values. /// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`. /// use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. /// @param _result An instance of Witnet.Result. /// @return The `int128` decoded from the Witnet.Result. function asFixed16(Witnet.Result memory _result) external pure override returns (int32) { return _result.asFixed16(); } /// Decode an array of fixed16 values from a Witnet.Result as an `int128[]` value. /// @param _result An instance of Witnet.Result. /// @return The `int128[]` decoded from the Witnet.Result. function asFixed16Array(Witnet.Result memory _result) external pure override returns (int32[] memory) { return _result.asFixed16Array(); } /// Decode a integer numeric value from a Witnet.Result as an `int128` value. /// @param _result An instance of Witnet.Result. /// @return The `int128` decoded from the Witnet.Result. function asInt128(Witnet.Result memory _result) external pure override returns (int128) { return _result.asInt128(); } /// Decode an array of integer numeric values from a Witnet.Result as an `int128[]` value. /// @param _result An instance of Witnet.Result. /// @return The `int128[]` decoded from the Witnet.Result. function asInt128Array(Witnet.Result memory _result) external pure override returns (int128[] memory) { return _result.asInt128Array(); } /// Decode a string value from a Witnet.Result as a `string` value. /// @param _result An instance of Witnet.Result. /// @return The `string` decoded from the Witnet.Result. function asString(Witnet.Result memory _result) external pure override returns (string memory) { return _result.asString(); } /// Decode an array of string values from a Witnet.Result as a `string[]` value. /// @param _result An instance of Witnet.Result. /// @return The `string[]` decoded from the Witnet.Result. function asStringArray(Witnet.Result memory _result) external pure override returns (string[] memory) { return _result.asStringArray(); } /// Decode a natural numeric value from a Witnet.Result as a `uint64` value. /// @param _result An instance of Witnet.Result. /// @return The `uint64` decoded from the Witnet.Result. function asUint64(Witnet.Result memory _result) external pure override returns(uint64) { return _result.asUint64(); } /// Decode an array of natural numeric values from a Witnet.Result as a `uint64[]` value. /// @param _result An instance of Witnet.Result. /// @return The `uint64[]` decoded from the Witnet.Result. function asUint64Array(Witnet.Result memory _result) external pure override returns (uint64[] memory) { return _result.asUint64Array(); } // ================================================================================================================ // --- Internal functions ----------------------------------------------------------------------------------------- function _checkRequest(uint256 _queryId) internal view returns (Witnet.Request storage _request) { _request = _getRequestData(_queryId); if (address(_request.addr) != address(0)) { // if the script contract address is not zero, // we assume the query has not been deleted, so // the request script bytecode can still be fetched: bytes memory _bytecode = _request.addr.bytecode(); require( _bytecode.hash() == _request.hash, "WitnetRequestBoardTrustableBase: bytecode changed after posting" ); } } function _reportResult( uint256 _queryId, uint256 _timestamp, bytes32 _drTxHash, bytes memory _cborBytes ) internal { require(_drTxHash != 0, "WitnetRequestBoardTrustableDefault: Witnet drTxHash cannot be zero"); // Ensures the result byes do not have zero length // This would not be a valid encoding with CBOR and could trigger a reentrancy attack require(_cborBytes.length != 0, "WitnetRequestBoardTrustableDefault: result cannot be empty"); Witnet.Query storage _query = _state().queries[_queryId]; Witnet.Response storage _response = _query.response; // solhint-disable not-rely-on-time _response.timestamp = _timestamp; _response.drTxHash = _drTxHash; _response.reporter = msg.sender; _response.cborBytes = _cborBytes; _safeTransferTo(payable(msg.sender), _query.request.reward); emit PostedResult(_queryId, msg.sender); } } // File: contracts\patterns\Destructible.sol interface Destructible { /// @dev Self-destruct the whole contract. function destruct() external; } // File: contracts\impls\trustable\WitnetRequestBoardTrustableDefault.sol /* solhint-disable var-name-mixedcase */ /// @title Witnet Request Board "trustable" implementation contract. /// @notice Contract to bridge requests to Witnet Decentralized Oracle Network. /// @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network. /// The result of the requests will be posted back to this contract by the bridge nodes too. /// @author The Witnet Foundation contract WitnetRequestBoardTrustableDefault is Destructible, WitnetRequestBoardTrustableBase { uint256 internal immutable _ESTIMATED_REPORT_RESULT_GAS; constructor( bool _upgradable, bytes32 _versionTag, uint256 _reportResultGasLimit ) WitnetRequestBoardTrustableBase(_upgradable, _versionTag, address(0)) { _ESTIMATED_REPORT_RESULT_GAS = _reportResultGasLimit; } // ================================================================================================================ // --- Overrides implementation of 'IWitnetRequestBoardView' ------------------------------------------------------ /// Estimates the amount of reward we need to insert for a given gas price. /// @param _gasPrice The gas price for which we need to calculate the rewards. function estimateReward(uint256 _gasPrice) public view virtual override returns (uint256) { return _gasPrice * _ESTIMATED_REPORT_RESULT_GAS; } // ================================================================================================================ // --- Overrides 'Destructible' ----------------------------------------------------------------------------------- /// Destroys current instance. Only callable by the owner. function destruct() external override onlyOwner { selfdestruct(payable(msg.sender)); } // ================================================================================================================ // --- Overrides 'Payable' ---------------------------------------------------------------------------------------- /// Gets current transaction price. function _getGasPrice() internal view override returns (uint256) { return tx.gasprice; } /// Gets current payment value. function _getMsgValue() internal view override returns (uint256) { return msg.value; } /// Transfers ETHs to given address. /// @param _to Recipient address. /// @param _amount Amount of ETHs to transfer. function _safeTransferTo(address payable _to, uint256 _amount) internal override { payable(_to).transfer(_amount); } }
Gets current status of given query.
function _getQueryStatus(uint256 _queryId) internal view returns (Witnet.QueryStatus) { if (_queryId == 0 || _queryId > _state().numQueries) return Witnet.QueryStatus.Unknown; else { Witnet.Query storage _query = _state().queries[_queryId]; if (_query.request.requester == address(0)) return Witnet.QueryStatus.Deleted; else if (_query.response.drTxHash != 0) return Witnet.QueryStatus.Reported; else return Witnet.QueryStatus.Posted; } }
10,928,791
./full_match/1/0x2fd8eE894E234a8b2bE30fD4595f60AA40A72A26/sources/src/abstracts/BaseRouter.sol
Similar to `_replaceAmountArgInAction(...)` but asbtracted to implement specific bridge logic./ Handles both permit actions logic flow. This function was required to avoid "stack too deep" error in `_bundleInternal()`. action either IRouter.Action.PermitWithdraw (6), or IRouter.Action.PermitBorrow (7) arg of the ongoing action actionArgsHash_ created previously withing `_bundleInternal()` to be used in permit check/
function _replaceAmountInCrossAction( Action action, bytes memory args, uint256 updateAmount ) internal pure virtual returns (bytes memory newArgs, uint256 previousAmount); function _handlePermitAction( IRouter.Action action, bytes memory arg, bytes32 actionArgsHash_ ) private returns (address) { PermitArgs memory permitArgs; { ( permitArgs.vault, permitArgs.owner, permitArgs.receiver, permitArgs.amount, permitArgs.deadline, permitArgs.v, permitArgs.r, permitArgs.s ) = abi.decode( arg, (IVaultPermissions, address, address, uint256, uint256, uint8, bytes32, bytes32) ); } _checkVaultInput(address(permitArgs.vault)); if (action == IRouter.Action.PermitWithdraw) { permitArgs.vault.permitWithdraw( permitArgs.owner, permitArgs.receiver, permitArgs.amount, permitArgs.deadline, actionArgsHash_, permitArgs.v, permitArgs.r, permitArgs.s ); permitArgs.vault.permitBorrow( permitArgs.owner, permitArgs.receiver, permitArgs.amount, permitArgs.deadline, actionArgsHash_, permitArgs.v, permitArgs.r, permitArgs.s ); revert BaseRouter__handlePermit_notPermitAction(); } return permitArgs.owner; }
3,167,828
./full_match/1/0xfbB3742628e8D19E0E2d7D8dde208821C09dE960/sources/src/Kernel.sol
Function used by kernel when migrating to a new kernel.
function changeKernel(Kernel newKernel_) external onlyKernel { kernel = newKernel_; }
4,916,110
./full_match/1/0x2Bbbdf97295F73175b12CC087cF446765931e1C3/sources/@layerzerolabs/solidity-examples/contracts/token/oft/v2/ProxyOFTV2.sol
internal functions/ _amount still may have dust if the token has transfer fee, then give the dust back to the sender check total outbound amount
function _debitFrom( address _from, uint16, bytes32, uint _amount ) internal virtual override returns (uint) { require(_from == _msgSender(), "ProxyOFT: owner is not send caller"); _amount = _transferFrom(_from, address(this), _amount); (uint amount, uint dust) = _removeDust(_amount); if (dust > 0) innerToken.safeTransfer(_from, dust); outboundAmount += amount; uint cap = _sd2ld(type(uint64).max); require(cap >= outboundAmount, "ProxyOFT: outboundAmount overflow"); return amount; }
8,317,413
pragma solidity ^0.5.16; // 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"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // Registration of fifth and subsequent airlines requires multi-party consensus of 50% of registered airlines uint256 constant MULTIPARTY_THRESHOLD = 4; uint256 constant MULTIPARTY_CONSENSUS_DIVISOR = 2; // Multi-party consensus for airline registration mapping(address => address[]) private registrationByConsensus; // Flight status codes 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; address private contractOwner; // Account used to deploy contract FlightSuretyData flightSuretyData; // Instance of FlightSuretyData address payable public dataContractAddress; uint256 public constant AIRLINE_MIN_FUND = 10 ether; //minimum fund required to participate in contract uint256 public constant MAX_INSURANCE_AMOUNT = 1 ether; /********************************************************************************************/ /* 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( flightSuretyData.isOperational(), "Contract is currently not operational" ); _; } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ /* modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } */ /** * @dev Modifier that requires the caller to be a registered airline */ modifier requireRegisteredAirline() { require( flightSuretyData.isAirlineRegistered(msg.sender), "Caller is not a registered airline" ); _; } /** * @dev Modifier that requires airline to be funded */ modifier requireAirlineIsFunded(address airline) { require( flightSuretyData.isAirlineFunded(airline) || msg.sender == contractOwner, "Airline is not funded" ); _; } /********************************************************************************************/ /* EVENTS */ /********************************************************************************************/ event AirlineRegistered(string name, address addr, uint256 votes); event AirlineFunded(address addr, uint256 amount); event FlightRegistered(address indexed airline, string flight); event FlightInsurancePurchased(address indexed passenger, uint256 amount); event InsurancePayout(address indexed airline, string flight); event RefundWithdrawal(address indexed passenger); /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor(address payable dataContract) public { contractOwner = msg.sender; dataContractAddress = dataContract; flightSuretyData = FlightSuretyData(dataContract); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public view returns (bool) { return flightSuretyData.isOperational(); } function setOperatingStatus(bool mode) public { flightSuretyData.setOperatingStatus(mode); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /*------------------------------------------------------------------------------------------*/ /* AIRLINE FUNCTIONS */ /*------------------------------------------------------------------------------------------*/ /** * @dev Add an airline to the registration queue * */ function registerAirline(string calldata name, address airline) external requireIsOperational requireAirlineIsFunded(msg.sender) returns (bool success, uint256 votes) { bool registered = false; uint256 numberOfregisteredAirlines = flightSuretyData.getRegisteredAirlineCount(); // Register first airline if (numberOfregisteredAirlines == 0) { flightSuretyData.registerAirline(name, airline); registered = true; } else if (numberOfregisteredAirlines < MULTIPARTY_THRESHOLD) { flightSuretyData.registerAirline(name, airline); registered = true; } else { // Multiparty Consensus: // Registration of fifth and subsequent airlines requires multi-party consensus of 50% of registered airlines bool alreadyVoted = false; for (uint256 i = 0; i < registrationByConsensus[airline].length; i++) { if (registrationByConsensus[airline][i] == msg.sender) { alreadyVoted = true; break; } } if (!alreadyVoted) { registrationByConsensus[airline].push(msg.sender); if ( registrationByConsensus[airline].length >= numberOfregisteredAirlines.div(MULTIPARTY_CONSENSUS_DIVISOR) ) { flightSuretyData.registerAirline(name, airline); registered = true; } } } if (registered){ emit AirlineRegistered( name, airline, registrationByConsensus[airline].length ); return (true, registrationByConsensus[airline].length); } return (false, registrationByConsensus[airline].length); } /** * @dev Returns airline name * */ function getAirlineName(address airline) external view requireIsOperational returns (string memory) { return flightSuretyData.getAirlineName(airline); } /** * @dev Returns the minimum number of votes required to register an airline * */ function getRequiredVotes() external view requireIsOperational returns (uint256 votes) { uint256 numberOfregisteredAirlines = flightSuretyData.getRegisteredAirlineCount(); return numberOfregisteredAirlines.div(MULTIPARTY_CONSENSUS_DIVISOR); } /** * @dev Returns the current number of registration votes for an airline * */ function getVotes(address airline) external view requireIsOperational returns (uint256 votes) { return registrationByConsensus[airline].length; } /** * @dev Checks whether an airline is registered * */ function isAirlineRegistered(address airline) external view requireIsOperational returns (bool) { return flightSuretyData.isAirlineRegistered(airline); } /** * @dev Check whether an airline is registered by name */ function isAirlineNameRegistered(string calldata airlineName) external view requireIsOperational returns (bool) { return flightSuretyData.isAirlineNameRegistered(airlineName); } /** * @dev funding a registered airline. * */ function fundAirline() external payable requireIsOperational requireRegisteredAirline { require( msg.value == AIRLINE_MIN_FUND, "10 Ether is required for funding" ); dataContractAddress.transfer(msg.value); flightSuretyData.fundAirline(msg.sender); emit AirlineFunded(msg.sender, msg.value); } /** * @dev Checks whether an airline paid its seed fund. * */ function isAirlineFunded(address airline) external view requireIsOperational returns (bool) { return flightSuretyData.isAirlineFunded(airline); } /** * @dev Register a future flight for insuring. * */ function registerFlight(string calldata flight, uint256 departureTime) external requireIsOperational requireAirlineIsFunded(msg.sender) { flightSuretyData.registerFlight( msg.sender, flight, departureTime, STATUS_CODE_UNKNOWN ); emit FlightRegistered(msg.sender, flight); } /** * @dev Returns all registered flights of an airline. * */ function getFlights(address airline) external view requireIsOperational returns (bytes32[] memory) { return flightSuretyData.getFlights(airline); } /** * @dev Checks whether a flight is registered. * */ function isFlightRegistered( address airline, string memory flight, uint256 departureTime ) public view requireIsOperational returns (bool) { bytes32 key = getFlightKey(airline, flight, departureTime); return flightSuretyData.isFlightRegistered(key); } function getFlightKeys() external view requireIsOperational returns (bytes32[] memory) { return flightSuretyData.getFlightKeys(); } function getFlight(bytes32 flightKey) external view requireIsOperational returns ( address airline, string memory flight, uint256 departureTime, uint8 statusCode ) { return flightSuretyData.getFlight(flightKey); } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus( address airline, string memory flight, uint256 departureTime, uint8 statusCode ) internal requireIsOperational { bytes32 key = getFlightKey(airline, flight, departureTime); flightSuretyData.updateFlightStatus(statusCode, key); if (statusCode == STATUS_CODE_LATE_AIRLINE) { flightSuretyData.creditInsurees(key); emit InsurancePayout(airline, flight); } } /** * @dev Generate a request for oracles to fetch flight information * */ function fetchFlightStatus( address airline, string calldata flight, uint256 departureTime ) external requireIsOperational { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, departureTime)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, flight, departureTime); } /** * @dev Checks whetehr a flight is delayed (status code 20) */ function IsFlightDelayed(bytes32 flightKey) external view requireIsOperational returns (bool) { return flightSuretyData.IsFlightDelayed(flightKey); } function getFlightKey( address airline, string memory flight, uint256 departureTime ) internal view requireIsOperational returns (bytes32) { return keccak256(abi.encodePacked(airline, flight, departureTime)); } /*------------------------------------------------------------------------------------------*/ /* PASSENGERS FUNCTIONS */ /*------------------------------------------------------------------------------------------*/ /** * @dev Buy insurance for a flight * */ function buyInsurance( address airline, string calldata flight, uint256 departureTime ) external payable requireIsOperational { require( msg.value <= MAX_INSURANCE_AMOUNT, "Passenger can buy insurance for a maximum of 1 ether" ); address(uint160(address(flightSuretyData))).transfer(msg.value); flightSuretyData.buyInsurance( airline, flight, departureTime, msg.sender, msg.value ); emit FlightInsurancePurchased(msg.sender, msg.value); } /** * @dev Returns all insured passengers of a flight */ function getInsurees(bytes32 flightKey) external view requireIsOperational returns (address[] memory) { return flightSuretyData.getInsurees(flightKey); } /** * @dev Returns paid insurance premium by flight info * */ function getPremium( address airline, string calldata flight, uint256 departureTime ) external view returns (uint256) { return flightSuretyData.getPremium( airline, flight, departureTime, msg.sender ); } /** * @dev Returns paid insurance premium by flight key and passenger * */ function getPremium(bytes32 flightKey, address passenger) external view requireIsOperational returns (uint256) { return flightSuretyData.getPremium(flightKey, passenger); } /** * @dev Returns passenger refunded amount by flight info * */ function getPayOutAmount( address airline, string calldata flight, uint256 departureTime ) external view returns (uint256) { return flightSuretyData.getPayOutAmount( airline, flight, departureTime, msg.sender ); } /** * @dev Returns passenger refunded amount by flight key and passenger * */ function getPayOutAmount(bytes32 flightKey, address passenger) external view requireIsOperational returns (uint256) { return flightSuretyData.getPayOutAmount(flightKey, passenger); } /** * @dev Checks whether insurance was paid to passengers * */ function isInsurancePaidOut( address airline, string calldata flight, uint256 departureTime ) external view requireIsOperational returns (bool) { bytes32 key = getFlightKey(airline, flight, departureTime); return flightSuretyData.isInsurancePaidOut(key); } /** * @dev Returns passenger total refunds (multiple flights) * */ function getBalance() external view requireIsOperational returns (uint256) { return flightSuretyData.getBalance(msg.sender); } function withdrawRefund() external requireIsOperational { flightSuretyData.payInsuree(msg.sender); emit RefundWithdrawal(msg.sender); } /*------------------------------------------------------------------------------------------*/ /* 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, departureTime) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo( address airline, string flight, uint256 departureTime, uint8 status ); event OracleReport( address airline, string flight, uint256 departureTime, 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 departureTime ); // Register an oracle with the contract function registerOracle() external payable requireIsOperational { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({isRegistered: true, indexes: indexes}); } function isOracleRegistered(address oracleAddress) public view requireIsOperational returns (bool) { return oracles[oracleAddress].isRegistered; } function getOracleRegistrationFee() external view requireIsOperational returns (uint256) { return REGISTRATION_FEE; } function getMyIndexes() external view requireIsOperational 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 departureTime, uint8 statusCode ) external requireIsOperational { 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, departureTime)); require( oracleResponses[key].isOpen, "Flight or departureTime 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, departureTime, statusCode); if ( oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES ) { emit FlightStatusInfo(airline, flight, departureTime, statusCode); // Handle flight status as appropriate processFlightStatus(airline, flight, departureTime, statusCode); } } /*------------------------------------------------------------------------------------------*/ /* UTILITIES */ /*------------------------------------------------------------------------------------------*/ // 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 } /********************************************************************************************/ /* STUBS FOR DATA CONTRACT */ /********************************************************************************************/ contract FlightSuretyData { function isOperational() external view returns (bool); function setOperatingStatus(bool mode) external; function registerAirline(string calldata name, address airline) external; function getAirlineName(address airline) external view returns (string memory); function isAirlineRegistered(address airline) external view returns (bool); function isAirlineNameRegistered(string calldata airlineName) external view returns (bool); function getRegisteredAirlineCount() external view returns (uint256); function isAirlineFunded(address airline) external view returns (bool); function registerFlight( address airline, string calldata flight, uint256 departureTime, uint8 statusCode ) external; function fundAirline(address airline) external; function getFlights(address airline) external view returns (bytes32[] memory); function getFlightKeys() external view returns (bytes32[] memory); function getFlight(bytes32 flightKey) external view returns ( address airline, string memory flight, uint256 departureTime, uint8 statusCode ); function IsFlightDelayed(bytes32 flightKey) external view returns (bool); function isFlightRegistered(bytes32 flightKey) external view returns (bool); function updateFlightStatus(uint8 statusCode, bytes32 flightKey) external; function buyInsurance( address airline, string calldata flight, uint256 departureTime, address passenger, uint256 amount ) external; function getInsurees(bytes32 flightKey) external view returns (address[] memory); function getPremium( address airline, string calldata flight, uint256 departureTime, address passenger ) external view returns (uint256); function getPremium(bytes32 flightKey, address passenger) external view returns (uint256); function getPayOutAmount( address airline, string calldata flight, uint256 departureTime, address passenger ) external view returns (uint256); function getPayOutAmount(bytes32 flightKey, address passenger) external view returns (uint256); function creditInsurees(bytes32 flightKey) external; function isInsurancePaidOut(bytes32 flightKey) external view returns (bool); function getBalance(address passenger) external view returns (uint256); function payInsuree(address payable insuree) external; }
Returns all insured passengers of a flight/
function getInsurees(bytes32 flightKey) external view requireIsOperational returns (address[] memory) { return flightSuretyData.getInsurees(flightKey); }
12,825,316