file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./TendiesBox.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract TendiesBoxWithERC20 { IERC20 public erc20Contract; TendiesBox public tendiesBoxContract; address payable withdrawAddress; uint256 perPackErc20Distribution; constructor( address _tendiesBoxContract, address _erc20Contract, address payable _withdrawAddress, uint256 _perPackErc20Distribution ) public { tendiesBoxContract = TendiesBox(_tendiesBoxContract); erc20Contract = IERC20(_erc20Contract); withdrawAddress = _withdrawAddress; perPackErc20Distribution = _perPackErc20Distribution; } function withdraw() external { require(msg.sender == withdrawAddress, "Not allowed withdraw address"); erc20Contract.transfer(msg.sender, erc20Contract.balanceOf(address(this))); } function open( uint256 _boxId, uint256 _amount ) external { // Make sure they have packs to open and we have enough tokens to distribute uint256 balance = tendiesBoxContract.balanceOf(msg.sender, _boxId); require(balance >= _amount, "Not enough boxes to open"); require(perPackErc20Distribution <= erc20Contract.balanceOf(address(this)), "Not enough tokens for swap"); tendiesBoxContract.openFor(_boxId, _amount, msg.sender); erc20Contract.transfer(msg.sender, perPackErc20Distribution); } }
Make sure they have packs to open and we have enough tokens to distribute
function open( uint256 _boxId, uint256 _amount ) external { uint256 balance = tendiesBoxContract.balanceOf(msg.sender, _boxId); require(balance >= _amount, "Not enough boxes to open"); require(perPackErc20Distribution <= erc20Contract.balanceOf(address(this)), "Not enough tokens for swap"); tendiesBoxContract.openFor(_boxId, _amount, msg.sender); erc20Contract.transfer(msg.sender, perPackErc20Distribution); }
1,017,975
pragma solidity ^0.8.5; // SPDX-License-Identifier: MIT interface IERC20 { /** * @dev Returns the total tokens supply */ 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. */ // 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, 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 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. 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; } } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(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; // msg.data is used to handle array, bytes, string } } /** * @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. * * 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. * * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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; } function getUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; _previousOwner = address(0); } } // pragma solidity >=0.5.0; interface IUniswapFactory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); 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(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // pragma solidity >=0.5.0; interface IUniswapPair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // pragma solidity >=0.6.2; interface IUniswapRouter01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } // pragma solidity >=0.6.2; interface IUniswapRouter02 is IUniswapRouter01 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract Bodl is Context, IERC20, Ownable { // change contract name using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; // reflected owned tokens mapping (address => uint256) private _tOwned; // total Owned tokens mapping (address => mapping (address => uint256)) private _allowances; // allowed allowance for spender mapping (address => bool) public _isExcludedFromFee; // excluded address from all fee mapping (address => uint256) private _transactionCheckpoint; mapping (address => bool) public _isExcludedFromReflection; // address excluded from reflection mapping (address => bool) public _isBlacklisted; // blocks an address from buy and selling mapping (address => uint256) private _excludedIndex; // to store the index of exclude address mapping(address => bool) public _isExcludedFromTransactionlock; // Address to be excluded from transaction cooldown address[] private _excluded; // storing reflection excluded address so, no reflection send to them address payable public _charityAddress = payable(0x3B573291a528dDbd87544BaBfC52abC65b2100E5); // charity Address string private _name = "Bodl"; // token name string private _symbol = "BODL"; // token symbol uint8 private _decimals = 18; // 1 token can be divided into 1e_decimals parts uint256 private constant MAX = ~uint256(0); // maximum possible number uint256 decimal value uint256 private _tTotal = 1000000 * 10**6 * 10**_decimals; uint256 private _rTotal = (MAX - (MAX % _tTotal)); // maximum _rTotal value after subtracting _tTotal remainder uint256 private _tFeeTotal; // total fee collected including tax fee and liquidity fee // All fees are with one decimal value. so if you want 0.5 set value to 5, for 10 set 100. so on... // Below Fees to be deducted and sent as tokens uint256 public _reflectionFee = 50; //reflection fee 5% uint256 private _previousReflectionFee = _reflectionFee; //reflection fee uint256 public _charityFee = 20; // charity fee 2% uint256 private _previousCharityFee = _charityFee; // charity fee uint256 public _liquidityFee = 30; // actual liquidity fee 3% uint256 private _previousLiquidityFee = _liquidityFee; // restore actual liquidity fee uint256 private _totalDeductableFee = _charityFee.add(_liquidityFee); // liquidity + charity fee on each transaction uint256 private _previousDeductableFee = _totalDeductableFee; // restore old liquidity fee uint256 private _transactionLockTime = 0; //Cool down time between each transaction per address IUniswapRouter02 public uniswapRouter; // uniswap router assiged using address address public uniswapPair; // for creating WETH pair with our token bool inSwapAndLiquify; // after each successfull swapandliquify disable the swapandliquify bool public swapAndLiquifyEnabled = true; // set auto swap to ETH and liquify collected liquidity fee uint256 public _maxTxAmount = 5000 * 10**6 * 10**_decimals; // max allowed tokens tranfer per transaction uint256 public _minTokensSwapToAndTransferTo = 500 * 10**6 * 10**_decimals; // min token liquidity fee collected before swapandLiquify event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); //event fire min token liquidity fee collected before swapandLiquify event SwapAndLiquifyEnabledUpdated(bool enabled); // event fire set auto swap to ETH and liquify collected liquidity fee event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqiudity ); // fire event how many tokens were swapedandLiquified modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } // modifier to after each successfull swapandliquify disable the swapandliquify constructor () { _rOwned[_msgSender()] = _rTotal; // assigning the max reflection token to owner's address IUniswapRouter02 _uniswapRouter = IUniswapRouter02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapPair = IUniswapFactory(_uniswapRouter.factory()) .createPair(address(this), _uniswapRouter.WETH()); // set the rest of the contract variables uniswapRouter = _uniswapRouter; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_charityAddress] = true; //exclude below addresses from transaction cooldown _isExcludedFromTransactionlock[owner()] = true; _isExcludedFromTransactionlock[address(this)] = true; _isExcludedFromTransactionlock[uniswapPair] = true; _isExcludedFromTransactionlock[_charityAddress] = true; _isExcludedFromTransactionlock[address(_uniswapRouter)] = true; //Exclude dead address from reflection _isExcludedFromReflection[address(0)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcludedFromReflection[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev approves allowance of a spender */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev transfers from a sender to receipent with subtracting spenders allowance with each successfull transfer */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev approves allowance of a spender should set it to zero first than increase */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev decrease allowance of spender that it can spend on behalf of owner */ 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 Total collected Tax fee */ function totalFeesCollected() public view returns (uint256) { return _tFeeTotal; } /** * @dev gives reflected tokens to caller */ function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcludedFromReflection[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } /** * @dev return's reflected amount of an address from given token amount with/without fee deduction */ function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } /** * @dev get's exact total tokens of an address from reflected amount */ function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } /** * @dev excludes an address from reflection reward can only be set by owner */ function excludeFromReward(address account) public onlyOwner { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude uniswap router.'); require(!_isExcludedFromReflection[account], "Account is already excluded from reflection"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcludedFromReflection[account] = true; _excluded.push(account); _excludedIndex[account] = _excluded.length - 1; } /** * @dev includes an address for reflection reward which was excluded before */ function includeInReward(address account) external onlyOwner { require(_isExcludedFromReflection[account], "Account is already included in reflection"); uint256 removeIndex = _excludedIndex[account]; _excluded[removeIndex] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcludedFromReflection[account] = false; _excluded.pop(); _excludedIndex[_excluded[removeIndex]] = removeIndex; } /** * @dev exclude an address from fee */ function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } /** * @dev include an address for fee */ function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } /** * @dev set's charity fee percentage */ function setCharityFeePercent(uint256 Fee) external onlyOwner { _charityFee = Fee; _totalDeductableFee = _liquidityFee.add(_charityFee); } /** * @dev set's reflection fee percentage */ function setReflectFeePercent(uint256 Fee) external onlyOwner { _reflectionFee = Fee; } /** * @dev set's liquidity fee percentage */ function setLiquidityFeePercent(uint256 Fee) external onlyOwner { _liquidityFee = Fee; _totalDeductableFee = _liquidityFee.add(_charityFee); } /** * @dev set's max amount of tokens percentage * that can be transfered in each transaction from an address */ function setMaxTxnTokens(uint256 maxTxTokens) external onlyOwner { _maxTxAmount = maxTxTokens.mul( 10**_decimals ); } /** * @dev set's minimmun amount of tokens required * before swaped and ETH send to wallet * same value will be used for auto swapandliquifiy threshold */ function setMinTokensSwapAndTransfer(uint256 minAmount) public onlyOwner { _minTokensSwapToAndTransferTo = minAmount.mul( 10 ** _decimals); } /** * @dev set's address */ function setCharityAddress(address payable charityAddress) external onlyOwner { _charityAddress = charityAddress; } /** * @dev Sets transactions on time periods or cooldowns. Buzz Buzz Bots. * Can only be set by owner set in seconds. */ function setTransactionCooldownTime(uint256 transactiontime) public onlyOwner { _transactionLockTime = transactiontime; } /** * @dev set's auto SwapandLiquify when contract's token balance threshold is reached */ function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } /** * @dev Exclude's an address from transactions from cooldowns. * Can only be set by owner. */ function excludedFromTransactionCooldown(address account) public onlyOwner { _isExcludedFromTransactionlock[account] = true; } /** * @dev Include's an address in transactions from cooldowns. * Can only be set by owner. */ function includeInTransactionCooldown(address account) public onlyOwner { _isExcludedFromTransactionlock[account] = false; } //to recieve ETH from uniswapRouter when swaping receive() external payable {} /** * @dev reflects to all holders, fee deducted from each transaction */ function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } /** * @dev get/calculates all values e.g taxfee, * liquidity fee, actual transfer amount to receiver, * deuction amount from sender * amount with reward to all holders * amount without reward to all holders */ function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } /** * @dev get/calculates taxfee, liquidity fee * without reward amount */ function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateReflectionFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } /** * @dev amount with reward, reflection from transaction * total deduction amount from sender with reward */ function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } /** * @dev gets current reflection rate */ function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } /** * @dev gets total supply with/without deducted * exclude caller's total owned and reflection owned */ function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } /** * @dev take's liquidity fee tokens from tansaction and saves in contract */ function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcludedFromReflection[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } /** * @dev calculates reflection fee tokens to be deducted */ function calculateReflectionFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_reflectionFee).div( 10**3 ); } /** * @dev calculates liquidity fee tokens to be deducted */ function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_totalDeductableFee).div( 10**3 ); } /** * @dev removes all fee from transaction if takefee is set to false */ function removeAllFee() private { if(_totalDeductableFee == 0&& _charityFee == 0 && _reflectionFee == 0 && _liquidityFee == 0) return; _previousLiquidityFee = _liquidityFee; _previousCharityFee = _charityFee; _previousReflectionFee = _reflectionFee; _previousDeductableFee = _totalDeductableFee; _charityFee = 0; _reflectionFee = 0; _liquidityFee = 0; _totalDeductableFee = 0; } /** * @dev restores all fee after exclude fee transaction completes */ function restoreAllFee() private { _liquidityFee = _previousLiquidityFee; _charityFee = _previousCharityFee; _reflectionFee = _previousReflectionFee; _totalDeductableFee = _previousDeductableFee; } /** * @dev approves amount of token spender can spend on behalf of an owner */ function _approve(address owner, address spender, uint256 amount) private { 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 transfers token from sender to recipient also auto * swapsandliquify if contract's token balance threshold is reached */ function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(_isBlacklisted[from] == false, "You are banned"); require(_isBlacklisted[to] == false, "The recipient is banned"); require(amount > 0, "Transfer amount must be greater than zero"); require(_isExcludedFromTransactionlock[from] || block.timestamp >= _transactionCheckpoint[from] + _transactionLockTime, "Wait for transaction cooldown time to end before making a tansaction"); require(_isExcludedFromTransactionlock[to] || block.timestamp >= _transactionCheckpoint[to] + _transactionLockTime, "Wait for transaction cooldown time to end before making a tansaction"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); _transactionCheckpoint[from] = block.timestamp; _transactionCheckpoint[to] = block.timestamp; // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >=_minTokensSwapToAndTransferTo; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapPair && swapAndLiquifyEnabled ) { contractTokenBalance =_minTokensSwapToAndTransferTo; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } /** * @dev swapsAndLiquify tokens to uniswap if swapandliquify is enabled */ function swapAndLiquify(uint256 tokenBalance) private lockTheSwap { // first split contract into fee and liquidity fee uint256 swapPercent = _charityFee.add(_liquidityFee/2); uint256 swapTokens = tokenBalance.mul(swapPercent).div(_totalDeductableFee); uint256 liquidityTokens = tokenBalance.sub(swapTokens); uint256 initialBalance = address(this).balance; swapTokensForEth(swapTokens); uint256 swappedAmount = address(this).balance.sub(initialBalance); if(_charityFee > 0) { _charityAddress.transfer(swappedAmount.mul(_charityFee).div(swapPercent)); } if(_liquidityFee > 0) { uint256 liquidityETH = swappedAmount.mul(_liquidityFee/2).div(swapPercent); // add liquidity to uniswap addLiquidity(owner(), liquidityTokens, liquidityETH); emit SwapAndLiquify(liquidityTokens, liquidityETH, liquidityTokens); } } /** * @dev swap's exact amount of tokens for ETH if swapandliquify is enabled */ function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapRouter.WETH(); _approve(address(this), address(uniswapRouter), tokenAmount); // make the swap uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } /** * @dev add's liquidy to uniswap if swapandliquify is enabled */ function addLiquidity(address recipient, uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapRouter), tokenAmount); // add the liquidity uniswapRouter.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable recipient, block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcludedFromReflection[sender] && !_isExcludedFromReflection[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcludedFromReflection[sender] && _isExcludedFromReflection[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcludedFromReflection[sender] && !_isExcludedFromReflection[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcludedFromReflection[sender] && _isExcludedFromReflection[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } /** * @dev deducteds balance from sender and * add to recipient with reward for recipient only */ function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /** * @dev deducteds balance from sender and * add to recipient with reward for sender only */ function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /** * @dev deducteds balance from sender and * add to recipient with reward for both addresses */ function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /** * @dev Transfer tokens to sender and receiver address with both excluded from reward */ function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /** * @dev Blacklist a singel wallet from buying and selling */ function blacklistSingleWallet(address account) public onlyOwner{ if(_isBlacklisted[account] == true) return; _isBlacklisted[account] = true; } /** * @dev Blacklist multiple wallets from buying and selling */ function blacklistMultipleWallets(address[] calldata accounts) public onlyOwner{ require(accounts.length < 800, "Can not blacklist more then 800 address in one transaction"); for (uint256 i; i < accounts.length; ++i) { _isBlacklisted[accounts[i]] = true; } } /** * @dev un blacklist a singel wallet from buying and selling */ function unBlacklistSingleWallet(address account) external onlyOwner{ if(_isBlacklisted[account] == false) return; _isBlacklisted[account] = false; } /** * @dev un blacklist multiple wallets from buying and selling */ function unBlacklistMultipleWallets(address[] calldata accounts) public onlyOwner{ require(accounts.length < 800, "Can not Unblacklist more then 800 address in one transaction"); for (uint256 i; i < accounts.length; ++i) { _isBlacklisted[accounts[i]] = false; } } /** * @dev recovers any tokens stuck in Contract's balance * NOTE! if ownership is renounced then it will not work * NOTE! Contract's Address and Owner's address MUST NOT * be excluded from reflection reward */ function recoverTokens() public onlyOwner { address recipient = _msgSender(); uint256 tokensToRecover = balanceOf(address(this)); uint256 currentRate = _getRate(); uint256 rTokensToRecover = tokensToRecover.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].sub(rTokensToRecover); if(_isExcludedFromReflection[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].sub(tokensToRecover); _rOwned[recipient] = _rOwned[recipient].add(rTokensToRecover); if(_isExcludedFromReflection[recipient]) _tOwned[recipient] = _tOwned[recipient].add(tokensToRecover); } /** * @dev recovers any ETH stuck in Contract's balance * NOTE! if ownership is renounced then it will not work */ function recoverETH() public onlyOwner { address payable recipient = _msgSender(); if(address(this).balance > 0) recipient.transfer(address(this).balance); } //New uniswap router version? //No problem, just change it! function setRouterAddress(address newRouter) public onlyOwner { IUniswapRouter02 _newUniswapRouter = IUniswapRouter02(newRouter); uniswapPair = IUniswapFactory(_newUniswapRouter.factory()).createPair(address(this), _newUniswapRouter.WETH()); uniswapRouter = _newUniswapRouter; } }
calculates liquidity fee tokens to be deducted/
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_totalDeductableFee).div( 10**3 ); }
14,473,020
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./libraries/UniswapLibrary.sol"; import "./BlockLock.sol"; import "./interfaces/IxTokenManager.sol"; contract xAssetCLR is Initializable, ERC20Upgradeable, OwnableUpgradeable, PausableUpgradeable, BlockLock { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 private constant SWAP_SLIPPAGE = 100; // 1% uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1% // Used to give an identical token representation uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18; int24 tickLower; int24 tickUpper; // Prices calculated using above ticks from TickMath.getSqrtRatioAtTick() uint160 priceLower; uint160 priceUpper; int128 lastTwap; // Last stored oracle twap // Max current twap vs last twap deviation percentage divisor (100 = 1%) uint256 maxTwapDeviationDivisor; IERC20 token0; IERC20 token1; uint256 public tokenId; // token id representing this uniswap position uint256 public token0DecimalMultiplier; // 10 ** (18 - token0 decimals) uint256 public token1DecimalMultiplier; // 10 ** (18 - token1 decimals) uint256 public tokenDiffDecimalMultiplier; // 10 ** (token0 decimals - token1 decimals) uint24 public poolFee; uint8 public token0Decimals; uint8 public token1Decimals; address public poolAddress; address public routerAddress; address public positionManagerAddress; IxTokenManager xTokenManager; // xToken manager contract uint32 twapPeriod; event Rebalance(); event FeeCollected(uint256 token0Fee, uint256 token1Fee); function initialize( string memory _symbol, int24 _tickLower, int24 _tickUpper, IERC20 _token0, IERC20 _token1, address _poolAddress, address _routerAddress, address _positionManagerAddress, address _xTokenManagerAddress, uint256 _maxTwapDeviationDivisor, uint8 _token0Decimals, uint8 _token1Decimals ) external initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); __ERC20_init_unchained("xAssetCLR", _symbol); tickLower = _tickLower; tickUpper = _tickUpper; priceLower = UniswapLibrary.getSqrtRatio(_tickLower); priceUpper = UniswapLibrary.getSqrtRatio(_tickUpper); if (_token0 > _token1) { token0 = _token1; token1 = _token0; token0Decimals = _token1Decimals; token1Decimals = _token0Decimals; } else { token0 = _token0; token1 = _token1; token0Decimals = _token0Decimals; token1Decimals = _token1Decimals; } token0DecimalMultiplier = 10**(TOKEN_DECIMAL_REPRESENTATION - token0Decimals); token1DecimalMultiplier = 10**(TOKEN_DECIMAL_REPRESENTATION - token1Decimals); tokenDiffDecimalMultiplier = 10**((UniswapLibrary.subAbs(token0Decimals, token1Decimals))); maxTwapDeviationDivisor = _maxTwapDeviationDivisor; poolAddress = _poolAddress; positionManagerAddress = _positionManagerAddress; poolFee = 3000; routerAddress = _routerAddress; token0.safeIncreaseAllowance(_routerAddress, type(uint256).max); token1.safeIncreaseAllowance(_routerAddress, type(uint256).max); token0.safeIncreaseAllowance( _positionManagerAddress, type(uint256).max ); token1.safeIncreaseAllowance( _positionManagerAddress, type(uint256).max ); UniswapLibrary.approveOneInch(token0, token1); xTokenManager = IxTokenManager(_xTokenManagerAddress); lastTwap = getAsset0Price(); twapPeriod = 3600; } /* ========================================================================================= */ /* User-facing */ /* ========================================================================================= */ /** * @dev Mint xAssetCLR tokens by sending *amount* of *inputAsset* tokens * @dev amount of the other asset is auto-calculated */ function mint(uint8 inputAsset, uint256 amount) external notLocked(msg.sender) whenNotPaused() { require(amount > 0); lock(msg.sender); checkTwap(); (uint256 amount0Minted, uint256 amount1Minted) = calculateAmountsMintedSingleToken(inputAsset, amount); token0.safeTransferFrom(msg.sender, address(this), amount0Minted); token1.safeTransferFrom(msg.sender, address(this), amount1Minted); uint128 liquidityAmount = getLiquidityForAmounts(amount0Minted, amount1Minted); _mintInternal(liquidityAmount); // stake tokens in pool (uint256 stakedAmount0, uint256 stakedAmount1) = _stake(amount0Minted, amount1Minted); // Transfer back tokens we haven't been able to stake // There's up to 1% slippage when staking if ( amount0Minted.div(10**token0Decimals) > stakedAmount0.div(10**token0Decimals) ) { uint256 amountLeft = amount0Minted.sub(stakedAmount0); token0.safeTransfer(msg.sender, amountLeft); } if ( amount1Minted.div(10**token1Decimals) > stakedAmount1.div(10**token1Decimals) ) { uint256 amountLeft = amount1Minted.sub(stakedAmount1); token1.safeTransfer(msg.sender, amountLeft); } } /** * @dev Burn *amount* of xAssetCLR tokens to receive proportional * amount of pool tokens */ function burn(uint256 amount) external notLocked(msg.sender) { require(amount > 0); lock(msg.sender); checkTwap(); uint256 totalLiquidity = getTotalLiquidity(); uint256 proRataBalance = amount.mul(totalLiquidity).div(totalSupply()); super._burn(msg.sender, amount); (uint256 amount0, uint256 amount1) = getAmountsForLiquidity(uint128(proRataBalance)); uint256 unstakeAmount0 = amount0.add(amount0.div(MINT_BURN_SLIPPAGE)); uint256 unstakeAmount1 = amount1.add(amount1.div(MINT_BURN_SLIPPAGE)); _unstake(unstakeAmount0, unstakeAmount1); token0.safeTransfer(msg.sender, amount0); token1.safeTransfer(msg.sender, amount1); } function transfer(address recipient, uint256 amount) public override notLocked(msg.sender) returns (bool) { return super.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public override notLocked(sender) returns (bool) { return super.transferFrom(sender, recipient, amount); } /** * @dev Get Net Asset Value: * @dev token 0 amt * token 0 price + token1 amt * token1 price */ function getNav() public view returns (uint256) { return getStakedBalance().add(getBufferBalance()); } /** * @dev Returns amount in terms of asset 0 * @dev amount * asset 1 price */ function getAmountInAsset0Terms(uint256 amount) public view returns (uint256) { return UniswapLibrary.getAmountInAsset0Terms( amount, poolAddress, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Returns amount in terms of asset 1 * @dev amount * asset 0 price */ function getAmountInAsset1Terms(uint256 amount) public view returns (uint256) { return UniswapLibrary.getAmountInAsset1Terms( amount, poolAddress, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Get balance in xAssetCLR contract * @dev amounts are adjusted based on their token prices: * @dev token 0 amt * token 0 price + token1 amt * token1 price */ function getBufferBalance() public view returns (uint256) { (uint256 balance0, uint256 balance1) = getBufferTokenBalance(); return getAmountInAsset1Terms(balance0).add( getAmountInAsset0Terms(balance1) ); } /** * @dev Get total balance in the position * @dev amounts are adjusted based on their token prices: * @dev token 0 amt * token 0 price + token1 amt * token1 price */ function getStakedBalance() public view returns (uint256) { (uint256 amount0, uint256 amount1) = getStakedTokenBalance(); return getAmountInAsset1Terms(amount0).add( getAmountInAsset0Terms(amount1) ); } /** * @dev Get token balances in xAssetCLR contract * @dev returned balances are in wei representation */ function getBufferTokenBalance() public view returns (uint256 amount0, uint256 amount1) { return (getBufferToken0Balance(), getBufferToken1Balance()); } /** * @dev Get token0 balance in xAssetCLR */ function getBufferToken0Balance() public view returns (uint256 amount0) { return getToken0AmountInWei(token0.balanceOf(address(this))); } /** * @dev Get token1 balance in xAssetCLR */ function getBufferToken1Balance() public view returns (uint256 amount1) { return getToken1AmountInWei(token1.balanceOf(address(this))); } /** * @dev Get token balances in the position * @dev returned balances are in wei representation */ function getStakedTokenBalance() public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = getAmountsForLiquidity(getPositionLiquidity()); amount0 = getToken0AmountInWei(amount0); amount1 = getToken1AmountInWei(amount1); } /** * @dev Get total liquidity * @dev buffer liquidity + position liquidity */ function getTotalLiquidity() public view returns (uint256 amount) { (uint256 buffer0, uint256 buffer1) = getBufferTokenBalance(); uint128 bufferLiquidity = getLiquidityForAmounts(buffer0, buffer1); uint128 positionLiquidity = getPositionLiquidity(); return uint256(bufferLiquidity).add(uint256(positionLiquidity)); } /** * @dev Check how much xAssetCLR tokens will be minted on mint * @dev Uses position liquidity to calculate the amount */ function calculateMintAmount(uint256 _amount, uint256 totalSupply) public view returns (uint256 mintAmount) { if (totalSupply == 0) return _amount; uint256 previousLiquidity = getTotalLiquidity().sub(_amount); mintAmount = (_amount).mul(totalSupply).div(previousLiquidity); return mintAmount; } /* ========================================================================================= */ /* Management */ /* ========================================================================================= */ /** * @dev Collect rewards from pool and stake them in position * @dev may leave unstaked tokens in contract */ function collectAndRestake() external onlyOwnerOrManager { (uint256 amount0, uint256 amount1) = collect(); (uint256 stakeAmount0, uint256 stakeAmount1) = calculatePoolMintedAmounts(amount0, amount1); _stake(stakeAmount0, stakeAmount1); } /** * @dev Collect fees generated from position */ function collect() public onlyOwnerOrManager returns (uint256 collected0, uint256 collected1) { (collected0, collected1) = collectPosition( type(uint128).max, type(uint128).max ); emit FeeCollected(collected0, collected1); } /** * @dev Migrate the current position to a new position with different ticks */ function migratePosition(int24 newTickLower, int24 newTickUpper) public onlyOwnerOrManager { require(newTickLower != tickLower || newTickUpper != tickUpper); // withdraw entire liquidity from the position (uint256 _amount0, uint256 _amount1) = withdrawAll(); // burn current position NFT UniswapLibrary.burn(positionManagerAddress, tokenId); tokenId = 0; // set new ticks and prices tickLower = newTickLower; tickUpper = newTickUpper; priceLower = UniswapLibrary.getSqrtRatio(newTickLower); priceUpper = UniswapLibrary.getSqrtRatio(newTickUpper); (uint256 amount0, uint256 amount1) = calculatePoolMintedAmounts(_amount0, _amount1); // mint the position NFT and deposit the liquidity // set new NFT token id tokenId = createPosition(amount0, amount1); } /** * @dev Migrate the current position to a new position with different ticks * @dev Migrates position tick lower and upper by same amount of ticks * @dev Tick spacing (minimum tick difference) in pool w/ 3000 fee is 60 * @param ticks how many ticks to shift up or down * @param up whether to move tick range up or down */ function migrateParallel(uint24 ticks, bool up) external onlyOwnerOrManager { require(ticks != 0); int24 newTickLower; int24 newTickUpper; int24 ticksToShift = int24(ticks) * 60; if (up) { newTickLower = tickLower + ticksToShift; newTickUpper = tickUpper + ticksToShift; } else { newTickLower = tickLower - ticksToShift; newTickUpper = tickUpper - ticksToShift; } migratePosition(newTickLower, newTickUpper); } /** * @dev Mint function which initializes the pool position * @dev Must be called before any liquidity can be deposited */ function mintInitial(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { require(tokenId == 0); require(amount0 > 0 || amount1 > 0); checkTwap(); (uint256 amount0Minted, uint256 amount1Minted) = calculatePoolMintedAmounts(amount0, amount1); if (amount0 > 0) { token0.safeTransferFrom(msg.sender, address(this), amount0Minted); } if (amount1 > 0) { token1.safeTransferFrom(msg.sender, address(this), amount1Minted); } tokenId = createPosition(amount0Minted, amount1Minted); uint256 liquidity = uint256(getLiquidityForAmounts(amount0Minted, amount1Minted)); _mintInternal(liquidity); } /** * @dev Admin function to stake tokens * @dev used in case there's leftover tokens in the contract */ function adminRebalance() external onlyOwnerOrManager { UniswapLibrary.adminRebalance( UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }), UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: positionManagerAddress, router: routerAddress, pool: poolAddress }) ); emit Rebalance(); } /** * @dev Admin function for staking in position */ function adminStake(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { (uint256 stakeAmount0, uint256 stakeAmount1) = calculatePoolMintedAmounts(amount0, amount1); _stake(stakeAmount0, stakeAmount1); } /** * @dev Admin function for unstaking from position */ function adminUnstake(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { _unstake(amount0, amount1); } /** * @dev Admin function for swapping LP tokens in xAssetCLR * @param amount - swap amount (in t0 terms if _0for1, in t1 terms if !_0for1) * @param _0for1 - swap token 0 for 1 if true, token 1 for 0 if false */ function adminSwap(uint256 amount, bool _0for1) external onlyOwnerOrManager { if (_0for1) { swapToken0ForToken1(amount.add(amount.div(SWAP_SLIPPAGE)), amount); } else { swapToken1ForToken0(amount.add(amount.div(SWAP_SLIPPAGE)), amount); } } /** * @dev Admin function for swapping LP tokens in xAssetCLR using 1inch v3 exchange * @param minReturn - how much output tokens to receive on swap, in 18 decimals * @param _0for1 - swap token 0 for token 1 if true, token 1 for token 0 if false * @param _oneInchData - 1inch calldata, generated off-chain using their v3 api */ function adminSwapOneInch( uint256 minReturn, bool _0for1, bytes memory _oneInchData ) external onlyOwnerOrManager { UniswapLibrary.oneInchSwap( minReturn, _0for1, UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }), _oneInchData ); } /** * @dev Stake liquidity in position */ function _stake(uint256 amount0, uint256 amount1) private returns (uint256 stakedAmount0, uint256 stakedAmount1) { return UniswapLibrary.stake( amount0, amount1, positionManagerAddress, tokenId ); } /** * @dev Unstake liquidity from position */ function _unstake(uint256 amount0, uint256 amount1) private returns (uint256 collected0, uint256 collected1) { uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); (uint256 _amount0, uint256 _amount1) = unstakePosition(liquidityAmount); return collectPosition(uint128(_amount0), uint128(_amount1)); } /** * @dev Withdraws all current liquidity from the position */ function withdrawAll() private returns (uint256 _amount0, uint256 _amount1) { // Collect fees collect(); (_amount0, _amount1) = unstakePosition(getPositionLiquidity()); collectPosition(uint128(_amount0), uint128(_amount1)); } /** * @dev Creates the NFT token representing the pool position * @dev Mint initial liquidity */ function createPosition(uint256 amount0, uint256 amount1) private returns (uint256 _tokenId) { UniswapLibrary.TokenDetails memory tokenDetails = UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }); UniswapLibrary.PositionDetails memory positionDetails = UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: positionManagerAddress, router: routerAddress, pool: poolAddress }); return UniswapLibrary.createPosition( amount0, amount1, positionManagerAddress, tokenDetails, positionDetails ); } /** * @dev Unstakes a given amount of liquidity from the Uni V3 position * @param liquidity amount of liquidity to unstake * @return amount0 token0 amount unstaked * @return amount1 token1 amount unstaked */ function unstakePosition(uint128 liquidity) private returns (uint256 amount0, uint256 amount1) { UniswapLibrary.PositionDetails memory positionDetails = UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: positionManagerAddress, router: routerAddress, pool: poolAddress }); return UniswapLibrary.unstakePosition(liquidity, positionDetails); } function _mintInternal(uint256 _amount) private { uint256 mintAmount = calculateMintAmount(_amount, totalSupply()); return super._mint(msg.sender, mintAmount); } /* * Emergency function in case of errant transfer * of any token directly to contract */ function withdrawToken(address token, address receiver) external onlyOwnerOrManager { require(token != address(token0) && token != address(token1)); uint256 tokenBal = IERC20(address(token)).balanceOf(address(this)); if (tokenBal > 0) { IERC20(address(token)).safeTransfer(receiver, tokenBal); } } function pauseContract() external onlyOwnerOrManager returns (bool) { _pause(); return true; } function unpauseContract() external onlyOwnerOrManager returns (bool) { _unpause(); return true; } modifier onlyOwnerOrManager { require( msg.sender == owner() || xTokenManager.isManager(msg.sender, address(this)), "Function may be called only by owner or manager" ); _; } /* ========================================================================================= */ /* Uniswap helpers */ /* ========================================================================================= */ /** * @dev Swap token 0 for token 1 in xAssetCLR using Uni V3 Pool * @dev amounts should be in 18 decimals * @param amountIn - amount as maximum input for swap, in token 0 terms * @param amountOut - amount as output for swap, in token 0 terms */ function swapToken0ForToken1(uint256 amountIn, uint256 amountOut) private { UniswapLibrary.swapToken0ForToken1( amountIn, amountOut, UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: positionManagerAddress, router: routerAddress, pool: poolAddress }), UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }) ); } /** * @dev Swap token 1 for token 0 in xAssetCLR using Uni V3 Pool * @dev amounts should be in 18 decimals * @param amountIn - amount as maximum input for swap, in token 1 terms * @param amountOut - amount as output for swap, in token 1 terms */ function swapToken1ForToken0(uint256 amountIn, uint256 amountOut) private { UniswapLibrary.swapToken1ForToken0( getAmountInAsset0Terms(amountIn), getAmountInAsset0Terms(amountOut), UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: positionManagerAddress, router: routerAddress, pool: poolAddress }), UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }) ); } /** * @dev Collect token amounts from pool position */ function collectPosition(uint128 amount0, uint128 amount1) private returns (uint256 collected0, uint256 collected1) { return UniswapLibrary.collectPosition( amount0, amount1, tokenId, positionManagerAddress ); } /** * @dev Change pool fee and address */ function changePool(address _poolAddress, uint24 _poolFee) external onlyOwnerOrManager { poolAddress = _poolAddress; poolFee = _poolFee; } // Returns the current liquidity in the position function getPositionLiquidity() public view returns (uint128 liquidity) { return UniswapLibrary.getPositionLiquidity( positionManagerAddress, tokenId ); } /** * @dev Get asset 0 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset0Price() public view returns (int128) { return UniswapLibrary.getAsset0Price( poolAddress, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Get asset 1 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset1Price() public view returns (int128) { return UniswapLibrary.getAsset1Price( poolAddress, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Checks if twap deviates too much from the previous twap */ function checkTwap() private { lastTwap = UniswapLibrary.checkTwap( poolAddress, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier, lastTwap, maxTwapDeviationDivisor ); } /** * @dev Reset last twap if oracle price is consistently above the max deviation */ function resetTwap() external onlyOwnerOrManager { lastTwap = getAsset0Price(); } /** * @dev Set the max twap deviation divisor * @dev if twap moves more than the divisor specified * @dev mint, burn and mintInitial functions are locked */ function setMaxTwapDeviationDivisor(uint256 newDeviationDivisor) external onlyOwnerOrManager { maxTwapDeviationDivisor = newDeviationDivisor; } /** * @dev Set the oracle reading twap period * @dev Twap used is [now - twapPeriod, now] */ function setTwapPeriod(uint32 newPeriod) external onlyOwnerOrManager { require(newPeriod >= 360); twapPeriod = newPeriod; } /** * @dev Calculates the amounts deposited/withdrawn from the pool * amount0, amount1 - amounts to deposit/withdraw * amount0Minted, amount1Minted - actual amounts which can be deposited */ function calculatePoolMintedAmounts(uint256 amount0, uint256 amount1) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount ); } /** * @dev Calculates single-side minted amount * @param inputAsset - use token0 if 0, token1 else * @param amount - amount to deposit/withdraw */ function calculateAmountsMintedSingleToken(uint8 inputAsset, uint256 amount) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount; if (inputAsset == 0) { liquidityAmount = getLiquidityForAmounts(amount, type(uint112).max); } else { liquidityAmount = getLiquidityForAmounts(type(uint112).max, amount); } (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount ); } function getLiquidityForAmounts(uint256 amount0, uint256 amount1) public view returns (uint128 liquidity) { liquidity = UniswapLibrary.getLiquidityForAmounts( amount0, amount1, priceLower, priceUpper, poolAddress ); } function getAmountsForLiquidity(uint128 liquidity) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = UniswapLibrary.getAmountsForLiquidity( liquidity, priceLower, priceUpper, poolAddress ); } /** * @dev Get lower and upper ticks of the pool position */ function getTicks() external view returns (int24 tick0, int24 tick1) { return (tickLower, tickUpper); } /** * Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken0AmountInWei(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken0AmountInWei( amount, token0Decimals, token0DecimalMultiplier ); } /** * Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken1AmountInWei(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken1AmountInWei( amount, token1Decimals, token1DecimalMultiplier ); } /** * Returns token0 amount in token0Decimals */ function getToken0AmountInNativeDecimals(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken0AmountInNativeDecimals( amount, token0Decimals, token0DecimalMultiplier ); } /** * Returns token1 amount in token1Decimals */ function getToken1AmountInNativeDecimals(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken1AmountInNativeDecimals( amount, token1Decimals, token1DecimalMultiplier ); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/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 { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @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 virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol"; import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol"; import "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "@uniswap/v3-core/contracts/libraries/TickMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./ABDKMath64x64.sol"; import "./Utils.sol"; /** * Helper library for Uniswap functions * Used in xAssetCLR */ library UniswapLibrary { using SafeMath for uint256; using SafeERC20 for IERC20; uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18; uint256 private constant SWAP_SLIPPAGE = 50; // 2% uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1% uint256 private constant BUFFER_TARGET = 20; // 5% target // 1inch v3 exchange address address private constant oneInchExchange = 0x11111112542D85B3EF69AE05771c2dCCff4fAa26; struct TokenDetails { address token0; address token1; uint256 token0DecimalMultiplier; uint256 token1DecimalMultiplier; uint256 tokenDiffDecimalMultiplier; uint8 token0Decimals; uint8 token1Decimals; } struct PositionDetails { uint24 poolFee; uint32 twapPeriod; uint160 priceLower; uint160 priceUpper; uint256 tokenId; address positionManager; address router; address pool; } struct AmountsMinted { uint256 amount0ToMint; uint256 amount1ToMint; uint256 amount0Minted; uint256 amount1Minted; } /* ========================================================================================= */ /* Uni V3 Pool Helper functions */ /* ========================================================================================= */ /** * @dev Returns the current pool price */ function getPoolPrice(address _pool) public view returns (uint160) { IUniswapV3Pool pool = IUniswapV3Pool(_pool); (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return sqrtRatioX96; } /** * @dev Returns the current pool liquidity */ function getPoolLiquidity(address _pool) public view returns (uint128) { IUniswapV3Pool pool = IUniswapV3Pool(_pool); return pool.liquidity(); } /** * @dev Calculate pool liquidity for given token amounts */ function getLiquidityForAmounts( uint256 amount0, uint256 amount1, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint128 liquidity) { liquidity = LiquidityAmounts.getLiquidityForAmounts( getPoolPrice(pool), priceLower, priceUpper, amount0, amount1 ); } /** * @dev Calculate token amounts for given pool liquidity */ function getAmountsForLiquidity( uint128 liquidity, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( getPoolPrice(pool), priceLower, priceUpper, liquidity ); } /** * @dev Calculates the amounts deposited/withdrawn from the pool * @param amount0 - token0 amount to deposit/withdraw * @param amount1 - token1 amount to deposit/withdraw */ function calculatePoolMintedAmounts( uint256 amount0, uint256 amount1, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount = getLiquidityForAmounts( amount0, amount1, priceLower, priceUpper, pool ); (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount, priceLower, priceUpper, pool ); } /** * @dev Get asset 0 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset0Price( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (int128) { uint32[] memory secondsArray = new uint32[](2); // get earliest oracle observation time IUniswapV3Pool poolImpl = IUniswapV3Pool(pool); uint32 observationTime = getObservationTime(poolImpl); uint32 currTimestamp = uint32(block.timestamp); uint32 earliestObservationSecondsAgo = currTimestamp - observationTime; if ( twapPeriod == 0 || !Utils.lte( currTimestamp, observationTime, currTimestamp - twapPeriod ) ) { // set to earliest observation time if: // a) twap period is 0 (not set) // b) now - twap period is before earliest observation secondsArray[0] = earliestObservationSecondsAgo; } else { secondsArray[0] = twapPeriod; } secondsArray[1] = 0; (int56[] memory prices, ) = poolImpl.observe(secondsArray); int128 twap = Utils.getTWAP(prices, secondsArray[0]); if (token1Decimals > token0Decimals) { // divide twap by token decimal difference twap = ABDKMath64x64.mul( twap, ABDKMath64x64.divu(1, tokenDiffDecimalMultiplier) ); } else if (token0Decimals > token1Decimals) { // multiply twap by token decimal difference int128 multiplierFixed = ABDKMath64x64.fromUInt(tokenDiffDecimalMultiplier); twap = ABDKMath64x64.mul(twap, multiplierFixed); } return twap; } /** * @dev Get asset 1 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset1Price( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (int128) { return ABDKMath64x64.inv( getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ) ); } /** * @dev Returns amount in terms of asset 0 * @dev amount * asset 1 price */ function getAmountInAsset0Terms( uint256 amount, address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (uint256) { return ABDKMath64x64.mulu( getAsset1Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ), amount ); } /** * @dev Returns amount in terms of asset 1 * @dev amount * asset 0 price */ function getAmountInAsset1Terms( uint256 amount, address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (uint256) { return ABDKMath64x64.mulu( getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ), amount ); } /** * @dev Returns the earliest oracle observation time */ function getObservationTime(IUniswapV3Pool _pool) public view returns (uint32) { IUniswapV3Pool pool = _pool; (, , uint16 index, uint16 cardinality, , , ) = pool.slot0(); uint16 oldestObservationIndex = (index + 1) % cardinality; (uint32 observationTime, , , bool initialized) = pool.observations(oldestObservationIndex); if (!initialized) (observationTime, , , ) = pool.observations(0); return observationTime; } /** * @dev Checks if twap deviates too much from the previous twap * @return current twap */ function checkTwap( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier, int128 lastTwap, uint256 maxTwapDeviationDivisor ) public view returns (int128) { int128 twap = getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); int128 _lastTwap = lastTwap; int128 deviation = _lastTwap > twap ? _lastTwap - twap : twap - _lastTwap; int128 maxDeviation = ABDKMath64x64.mul( twap, ABDKMath64x64.divu(1, maxTwapDeviationDivisor) ); require(deviation <= maxDeviation, "Wrong twap"); return twap; } /** * @dev get tick spacing corresponding to pool fee amount */ function getTickSpacingForFee(uint24 fee) public pure returns (int24) { if (fee == 500) { return 10; } else if (fee == 3000) { return 60; } else if (fee == 10000) { return 200; } else { return 0; } } /* ========================================================================================= */ /* Uni V3 Swap Router Helper functions */ /* ========================================================================================= */ /** * @dev Swap token 0 for token 1 in xAssetCLR contract * @dev amountIn and amountOut should be in 18 decimals always * @dev amountIn and amountOut are in token 0 terms */ function swapToken0ForToken1( uint256 amountIn, uint256 amountOut, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 _amountOut) { amountOut = getAmountInAsset1Terms( amountOut, positionDetails.pool, positionDetails.twapPeriod, tokenDetails.token0Decimals, tokenDetails.token1Decimals, tokenDetails.tokenDiffDecimalMultiplier ); uint256 token0Balance = getBufferToken0Balance( IERC20(tokenDetails.token0), tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); require( token0Balance > amountIn, "Swap token 0 for token 1: not enough token 0 balance" ); amountIn = getToken0AmountInNativeDecimals( amountIn, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amountOut = getToken1AmountInNativeDecimals( amountOut, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); ISwapRouter(positionDetails.router).exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: tokenDetails.token0, tokenOut: tokenDetails.token1, fee: positionDetails.poolFee, recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountIn, sqrtPriceLimitX96: TickMath.MIN_SQRT_RATIO + 1 }) ); return amountOut; } /** * @dev Swap token 1 for token 0 in xAssetCLR contract * @dev amountIn and amountOut should be in 18 decimals always * @dev amountIn and amountOut are in token 0 terms */ function swapToken1ForToken0( uint256 amountIn, uint256 amountOut, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 _amountIn) { amountIn = getAmountInAsset1Terms( amountIn, positionDetails.pool, positionDetails.twapPeriod, tokenDetails.token0Decimals, tokenDetails.token1Decimals, tokenDetails.tokenDiffDecimalMultiplier ); uint256 token1Balance = getBufferToken1Balance( IERC20(tokenDetails.token1), tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); require( token1Balance > amountIn, "Swap token 1 for token 0: not enough token 1 balance" ); amountIn = getToken1AmountInNativeDecimals( amountIn, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); amountOut = getToken0AmountInNativeDecimals( amountOut, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); ISwapRouter(positionDetails.router).exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: tokenDetails.token1, tokenOut: tokenDetails.token0, fee: positionDetails.poolFee, recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountIn, sqrtPriceLimitX96: TickMath.MAX_SQRT_RATIO - 1 }) ); return amountIn; } /* ========================================================================================= */ /* 1inch Swap Helper functions */ /* ========================================================================================= */ /** * @dev Swap tokens in xAssetCLR using 1inch v3 exchange * @param minReturn - required min amount out from swap, in 18 decimals * @param _0for1 - swap token0 for token1 if true, token1 for token0 if false * @param tokenDetails - xAssetCLR token 0 and token 1 details * @param _oneInchData - One inch calldata, generated off-chain from their v3 api for the swap */ function oneInchSwap( uint256 minReturn, bool _0for1, TokenDetails memory tokenDetails, bytes memory _oneInchData ) public { uint256 token0AmtSwapped; uint256 token1AmtSwapped; bool success; // inline code to prevent stack too deep errors { IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); uint256 balanceBeforeToken0 = token0.balanceOf(address(this)); uint256 balanceBeforeToken1 = token1.balanceOf(address(this)); (success, ) = oneInchExchange.call(_oneInchData); require(success, "One inch swap call failed"); uint256 balanceAfterToken0 = token0.balanceOf(address(this)); uint256 balanceAfterToken1 = token1.balanceOf(address(this)); token0AmtSwapped = subAbs(balanceAfterToken0, balanceBeforeToken0); token1AmtSwapped = subAbs(balanceAfterToken1, balanceBeforeToken1); } uint256 amountInSwapped; uint256 amountOutReceived; if (_0for1) { amountInSwapped = getToken0AmountInWei( token0AmtSwapped, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amountOutReceived = getToken1AmountInWei( token1AmtSwapped, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); } else { amountInSwapped = getToken1AmountInWei( token1AmtSwapped, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); amountOutReceived = getToken0AmountInWei( token0AmtSwapped, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); } // require minimum amount received is > min return require( amountOutReceived > minReturn, "One inch swap not enough output token amount" ); } /** * Approve 1inch v3 for swaps */ function approveOneInch(IERC20 token0, IERC20 token1) public { token0.safeApprove(oneInchExchange, type(uint256).max); token1.safeApprove(oneInchExchange, type(uint256).max); } /* ========================================================================================= */ /* NFT Position Manager Helpers */ /* ========================================================================================= */ /** * @dev Returns the current liquidity in a position represented by tokenId NFT */ function getPositionLiquidity(address positionManager, uint256 tokenId) public view returns (uint128 liquidity) { (, , , , , , , liquidity, , , , ) = INonfungiblePositionManager( positionManager ) .positions(tokenId); } /** * @dev Stake liquidity in position represented by tokenId NFT */ function stake( uint256 amount0, uint256 amount1, address positionManager, uint256 tokenId ) public returns (uint256 stakedAmount0, uint256 stakedAmount1) { (, stakedAmount0, stakedAmount1) = INonfungiblePositionManager( positionManager ) .increaseLiquidity( INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amount0, amount1Desired: amount1, amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)), deadline: block.timestamp }) ); } /** * @dev Unstake liquidity from position represented by tokenId NFT * @dev using amount0 and amount1 instead of liquidity */ function unstake( uint256 amount0, uint256 amount1, PositionDetails memory positionDetails ) public returns (uint256 collected0, uint256 collected1) { uint128 liquidityAmount = getLiquidityForAmounts( amount0, amount1, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); (uint256 _amount0, uint256 _amount1) = unstakePosition(liquidityAmount, positionDetails); return collectPosition( uint128(_amount0), uint128(_amount1), positionDetails.tokenId, positionDetails.positionManager ); } /** * @dev Unstakes a given amount of liquidity from the Uni V3 position * @param liquidity amount of liquidity to unstake * @return amount0 token0 amount unstaked * @return amount1 token1 amount unstaked */ function unstakePosition( uint128 liquidity, PositionDetails memory positionDetails ) public returns (uint256 amount0, uint256 amount1) { INonfungiblePositionManager positionManager = INonfungiblePositionManager(positionDetails.positionManager); (uint256 _amount0, uint256 _amount1) = getAmountsForLiquidity( liquidity, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); (amount0, amount1) = positionManager.decreaseLiquidity( INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId: positionDetails.tokenId, liquidity: liquidity, amount0Min: _amount0.sub(_amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: _amount1.sub(_amount1.div(MINT_BURN_SLIPPAGE)), deadline: block.timestamp }) ); } /** * @dev Collect token amounts from pool position */ function collectPosition( uint128 amount0, uint128 amount1, uint256 tokenId, address positionManager ) public returns (uint256 collected0, uint256 collected1) { (collected0, collected1) = INonfungiblePositionManager(positionManager) .collect( INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: amount0, amount1Max: amount1 }) ); } /** * @dev Creates the NFT token representing the pool position * @dev Mint initial liquidity */ function createPosition( uint256 amount0, uint256 amount1, address positionManager, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public returns (uint256 _tokenId) { (_tokenId, , , ) = INonfungiblePositionManager(positionManager).mint( INonfungiblePositionManager.MintParams({ token0: tokenDetails.token0, token1: tokenDetails.token1, fee: positionDetails.poolFee, tickLower: getTickFromPrice(positionDetails.priceLower), tickUpper: getTickFromPrice(positionDetails.priceUpper), amount0Desired: amount0, amount1Desired: amount1, amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)), recipient: address(this), deadline: block.timestamp }) ); } /** * @dev burn NFT representing a pool position with tokenId * @dev uses NFT Position Manager */ function burn(address positionManager, uint256 tokenId) public { INonfungiblePositionManager(positionManager).burn(tokenId); } /* ========================================================================================= */ /* xAssetCLR Helpers */ /* ========================================================================================= */ /** * @dev Admin function to stake tokens * @dev used in case there's leftover tokens in the contract */ function adminRebalance( TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public { (uint256 token0Balance, uint256 token1Balance) = getBufferTokenBalance(tokenDetails); token0Balance = getToken0AmountInNativeDecimals( token0Balance, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); token1Balance = getToken1AmountInNativeDecimals( token1Balance, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); (uint256 stakeAmount0, uint256 stakeAmount1) = checkIfAmountsMatchAndSwap( token0Balance, token1Balance, positionDetails, tokenDetails ); require( stakeAmount0 != 0 && stakeAmount1 != 0, "Rebalance amounts are 0" ); (uint256 amount0, uint256 amount1) = calculatePoolMintedAmounts( stakeAmount0, stakeAmount1, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); stake( amount0, amount1, positionDetails.positionManager, positionDetails.tokenId ); } /** * @dev Check if token amounts match before attempting rebalance in xAssetCLR * @dev Uniswap contract requires deposits at a precise token ratio * @dev If they don't match, swap the tokens so as to deposit as much as possible * @param amount0ToMint how much token0 amount we want to deposit/withdraw * @param amount1ToMint how much token1 amount we want to deposit/withdraw */ function checkIfAmountsMatchAndSwap( uint256 amount0ToMint, uint256 amount1ToMint, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 amount0, uint256 amount1) { (uint256 amount0Minted, uint256 amount1Minted) = calculatePoolMintedAmounts( amount0ToMint, amount1ToMint, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); if ( amount0Minted < amount0ToMint.sub(amount0ToMint.div(MINT_BURN_SLIPPAGE)) || amount1Minted < amount1ToMint.sub(amount1ToMint.div(MINT_BURN_SLIPPAGE)) ) { // calculate liquidity ratio = // minted liquidity / total pool liquidity // used to calculate swap impact in pool uint256 mintLiquidity = getLiquidityForAmounts( amount0ToMint, amount1ToMint, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); uint256 poolLiquidity = getPoolLiquidity(positionDetails.pool); int128 liquidityRatio = poolLiquidity == 0 ? 0 : int128(ABDKMath64x64.divuu(mintLiquidity, poolLiquidity)); (amount0, amount1) = restoreTokenRatios( liquidityRatio, AmountsMinted({ amount0ToMint: amount0ToMint, amount1ToMint: amount1ToMint, amount0Minted: amount0Minted, amount1Minted: amount1Minted }), tokenDetails, positionDetails ); } else { (amount0, amount1) = (amount0ToMint, amount1ToMint); } } /** * @dev Swap tokens in xAssetCLR so as to keep a ratio which is required for * @dev depositing/withdrawing liquidity to/from Uniswap pool */ function restoreTokenRatios( int128 liquidityRatio, AmountsMinted memory amountsMinted, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) private returns (uint256 amount0, uint256 amount1) { // after normalization, returned swap amount will be in wei representation uint256 swapAmount; { int128 asset0Price = getAsset0Price( positionDetails.pool, positionDetails.twapPeriod, tokenDetails.token0Decimals, tokenDetails.token1Decimals, tokenDetails.tokenDiffDecimalMultiplier ); // Swap amount returned is always in asset 0 terms swapAmount = Utils.calculateSwapAmount( Utils.AmountsMinted({ amount0ToMint: getToken0AmountInWei( amountsMinted.amount0ToMint, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), amount1ToMint: getToken1AmountInWei( amountsMinted.amount1ToMint, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ), amount0Minted: getToken0AmountInWei( amountsMinted.amount0Minted, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), amount1Minted: getToken1AmountInWei( amountsMinted.amount1Minted, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ) }), liquidityRatio, asset0Price ); if (swapAmount == 0) { return ( amountsMinted.amount0ToMint, amountsMinted.amount1ToMint ); } } uint256 swapAmountWithSlippage = swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)); uint256 mul1 = amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted); uint256 mul2 = amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted); (uint256 balance0, uint256 balance1) = getBufferTokenBalance(tokenDetails); if (mul1 > mul2) { if (balance0 < swapAmountWithSlippage) { swapAmountWithSlippage = balance0; } // Swap tokens uint256 amountOut = swapToken0ForToken1( swapAmountWithSlippage, swapAmount, positionDetails, tokenDetails ); amount0 = amountsMinted.amount0ToMint.sub( getToken0AmountInNativeDecimals( swapAmount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) ); // amountOut is already in native decimals amount1 = amountsMinted.amount1ToMint.add(amountOut); } else if (mul1 < mul2) { balance1 = getAmountInAsset0Terms( balance1, positionDetails.pool, positionDetails.twapPeriod, tokenDetails.token0Decimals, tokenDetails.token1Decimals, tokenDetails.tokenDiffDecimalMultiplier ); if (balance1 < swapAmountWithSlippage) { swapAmountWithSlippage = balance1; } // Swap tokens uint256 amountIn = swapToken1ForToken0( swapAmountWithSlippage, swapAmount, positionDetails, tokenDetails ); amount0 = amountsMinted.amount0ToMint.add( getToken0AmountInNativeDecimals( swapAmount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) ); // amountIn is already in native decimals amount1 = amountsMinted.amount1ToMint.sub(amountIn); } } /** * @dev Withdraw *amount* of token 0 or token 1 * @param forToken0 withdraw balance for token0 (true) or token1 (false) * @param amount token0 or token1 amount we want to withdraw */ function withdrawSingleToken( bool forToken0, uint256 amount, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) private { uint256 currBalance; uint256 unstakeAmount0; uint256 unstakeAmount1; uint256 swapAmount; IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); uint256 startBalance = forToken0 ? getBufferToken0Balance( token0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) : getBufferToken1Balance( token1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); do { // calculate how much we can withdraw (unstakeAmount0, unstakeAmount1) = calculatePoolMintedAmounts( getToken0AmountInNativeDecimals( amount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), getToken1AmountInNativeDecimals( amount, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ), positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); // withdraw both tokens unstake(unstakeAmount0, unstakeAmount1, positionDetails); // swap the excess amount of token 0 for token 1 or vice-versa if (forToken0) { // unstakeAmount1 needs to be in token 0 terms unstakeAmount1 = getAmountInAsset0Terms( unstakeAmount1, positionDetails.pool, positionDetails.twapPeriod, tokenDetails.token0Decimals, tokenDetails.token1Decimals, tokenDetails.tokenDiffDecimalMultiplier ); swapAmount = getToken1AmountInWei( unstakeAmount1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); swapToken1ForToken0( swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)), swapAmount, positionDetails, tokenDetails ); currBalance = getBufferToken0Balance( token0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); } else { swapAmount = getToken0AmountInWei( unstakeAmount0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); swapToken0ForToken1( swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)), swapAmount, positionDetails, tokenDetails ); currBalance = getBufferToken1Balance( token1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); } } while (currBalance < startBalance.add(amount)); } /** * @dev Get token balances in xAssetCLR contract * @dev returned balances are in wei representation */ function getBufferTokenBalance(TokenDetails memory tokenDetails) public view returns (uint256 amount0, uint256 amount1) { IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); return ( getBufferToken0Balance( token0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), getBufferToken1Balance( token1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ) ); } // Get token balances in the position function getStakedTokenBalance( TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = getAmountsForLiquidity( getPositionLiquidity( positionDetails.positionManager, positionDetails.tokenId ), positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); amount0 = getToken0AmountInWei( amount0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amount1 = getToken1AmountInWei( amount1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); } /** * @dev Get token0 balance in xAssetCLR */ function getBufferToken0Balance( IERC20 token0, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public view returns (uint256 amount0) { return getToken0AmountInWei( token0.balanceOf(address(this)), token0Decimals, token0DecimalMultiplier ); } /** * @dev Get token1 balance in xAssetCLR */ function getBufferToken1Balance( IERC20 token1, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public view returns (uint256 amount1) { return getToken1AmountInWei( token1.balanceOf(address(this)), token1Decimals, token1DecimalMultiplier ); } /* ========================================================================================= */ /* Miscellaneous */ /* ========================================================================================= */ /** * @dev Returns token0 amount in token0Decimals */ function getToken0AmountInNativeDecimals( uint256 amount, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public pure returns (uint256) { if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.div(token0DecimalMultiplier); } return amount; } /** * @dev Returns token1 amount in token1Decimals */ function getToken1AmountInNativeDecimals( uint256 amount, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public pure returns (uint256) { if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.div(token1DecimalMultiplier); } return amount; } /** * @dev Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken0AmountInWei( uint256 amount, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public pure returns (uint256) { if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.mul(token0DecimalMultiplier); } return amount; } /** * @dev Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken1AmountInWei( uint256 amount, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public pure returns (uint256) { if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.mul(token1DecimalMultiplier); } return amount; } /** * @dev get price from tick */ function getSqrtRatio(int24 tick) public pure returns (uint160) { return TickMath.getSqrtRatioAtTick(tick); } /** * @dev get tick from price */ function getTickFromPrice(uint160 price) public pure returns (int24) { return TickMath.getTickAtSqrtRatio(price); } /** * @dev Subtract two numbers and return absolute value */ function subAbs(uint256 amount0, uint256 amount1) public pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0); } // Subtract two numbers and return 0 if result is < 0 function sub0(uint256 amount0, uint256 amount1) public pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : 0; } function calculateFee(uint256 _value, uint256 _feeDivisor) public pure returns (uint256 fee) { if (_feeDivisor > 0) { fee = _value.div(_feeDivisor); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; /** Contract which implements locking of functions via a notLocked modifier Functions are locked per address. */ contract BlockLock { // how many blocks are the functions locked for uint256 private constant BLOCK_LOCK_COUNT = 6; // last block for which this address is timelocked mapping(address => uint256) public lastLockedBlock; function lock(address _address) internal { lastLockedBlock[_address] = block.number + BLOCK_LOCK_COUNT; } modifier notLocked(address lockedAddress) { require( lastLockedBlock[lockedAddress] <= block.number, "Address is temporarily locked" ); _; } } //SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IxTokenManager { /** * @dev Add a manager to an xAsset fund */ function addManager(address manager, address fund) external; /** * @dev Remove a manager from an xAsset fund */ function removeManager(address manager, address fund) external; /** * @dev Check if an address is a manager for a fund */ function isManager(address manager, address fund) external view returns (bool); /** * @dev Set revenue controller */ function setRevenueController(address controller) external; /** * @dev Check if address is revenue controller */ function isRevenueController(address caller) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT 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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol'; import './IPoolInitializer.sol'; import './IERC721Permit.sol'; import './IPeripheryImmutableState.sol'; import '../libraries/PoolAddress.sol'; /// @title Non-fungible token for positions /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred /// and authorized. interface INonfungiblePositionManager is IPoolInitializer, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit { /// @notice Emitted when liquidity is increased for a position NFT /// @dev Also emitted when a token is minted /// @param tokenId The ID of the token for which liquidity was increased /// @param liquidity The amount by which liquidity for the NFT position was increased /// @param amount0 The amount of token0 that was paid for the increase in liquidity /// @param amount1 The amount of token1 that was paid for the increase in liquidity event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when liquidity is decreased for a position NFT /// @param tokenId The ID of the token for which liquidity was decreased /// @param liquidity The amount by which liquidity for the NFT position was decreased /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when tokens are collected for a position NFT /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior /// @param tokenId The ID of the token for which underlying tokens were collected /// @param recipient The address of the account that received the collected tokens /// @param amount0 The amount of token0 owed to the position that was collected /// @param amount1 The amount of token1 owed to the position that was collected event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1); /// @notice Returns the position information 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 position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { 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); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity 0.7.6; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt(int256 x) internal pure returns (int128) { require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt(int128 x) internal pure returns (int64) { return int64(x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt(uint256 x) internal pure returns (int128) { require(x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt(int128 x) internal pure returns (uint64) { require(x >= 0); return uint64(x >> 64); } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul(int128 x, int128 y) internal pure returns (int128) { int256 result = (int256(x) * y) >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu(int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require(x >= 0); uint256 lo = (uint256(x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256(x) * (y >> 128); require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require( hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo ); return hi + lo; } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu(uint256 x, uint256 y) internal pure returns (int128) { require(y != 0); uint128 result = divuu(x, y); require(result <= uint128(MAX_64x64)); return int128(result); } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv(int128 x) internal pure returns (int128) { require(x != 0); int256 result = int256(0x100000000000000000000000000000000) / x; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow(int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu(uint256(x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu(uint256(uint128(-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require(absoluteResult <= 0x80000000000000000000000000000000); return -int128(absoluteResult); // We rely on overflow behavior here } else { require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128(absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu(uint256 x, uint256 y) internal pure returns (uint128) { require(y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1); require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert(xh == hi >> 128); result += xl / y; } require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128(result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu(uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= uint256(xe); else x <<= uint256(-xe); uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if ( result >= 0x8000000000000000000000000000000000000000000000000000000000000000 ) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require(re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if ( x >= 0x8000000000000000000000000000000000000000000000000000000000000000 ) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require(xe < 128); // Overflow } } if (re > 0) result <<= uint256(re); else if (re < 0) result >>= uint256(-re); return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu(uint256 x) internal pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128(r < r1 ? r : r1); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./ABDKMath64x64.sol"; /** * Library with utility functions for xAssetCLR */ library Utils { using SafeMath for uint256; struct AmountsMinted { uint256 amount0ToMint; uint256 amount1ToMint; uint256 amount0Minted; uint256 amount1Minted; } /** Get asset 1 twap price for the period of [now - secondsAgo, now] */ function getTWAP(int56[] memory prices, uint32 secondsAgo) internal pure returns (int128) { // Formula is // 1.0001 ^ (currentPrice - pastPrice) / secondsAgo if (secondsAgo == 0) { return ABDKMath64x64.fromInt(1); } int256 diff = int256(prices[1]) - int256(prices[0]); uint256 priceDiff = diff < 0 ? uint256(-diff) : uint256(diff); int128 fraction = ABDKMath64x64.divu(priceDiff, uint256(secondsAgo)); int128 twap = ABDKMath64x64.pow( ABDKMath64x64.divu(10001, 10000), uint256(ABDKMath64x64.toUInt(fraction)) ); // This is necessary because we cannot call .pow on unsigned integers // And thus when asset0Price > asset1Price we need to reverse the value twap = diff < 0 ? ABDKMath64x64.inv(twap) : twap; return twap; } /** * Helper function to calculate how much to swap when * staking or withdrawing from Uni V3 Pools * Goal of this function is to calibrate the staking tokens amounts * When we want to stake, for example, 100 token0 and 10 token1 * But pool price demands 100 token0 and 40 token1 * We cannot directly stake 100 t0 and 10 t1, so we swap enough * to be able to stake the value of 100 t0 and 10 t1 */ function calculateSwapAmount( AmountsMinted memory amountsMinted, int128 liquidityRatio, int128 asset0Price ) internal pure returns (uint256 swapAmount) { // formula is more complicated than xU3LP case // it includes the asset prices, and considers the swap impact on the pool // base formula is this: // n - swap amt, x - amount 0 to mint, y - amount 1 to mint, // z - amount 0 minted, t - amount 1 minted, p0 - asset 0 price // l - liquidity ratio (current mint liquidity vs total pool liq) // (X - n) / (Y + n * p0) = (Z + l * n) / (T - l * n * p0) -> // n = (X * T - Y * Z) / (p0 * l * X + p0 * Z + l * Y + T) uint256 mul1 = amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted); uint256 mul2 = amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted); uint256 sub = subAbs(mul1, mul2); uint256 add1 = ABDKMath64x64.mulu(liquidityRatio, amountsMinted.amount1ToMint); uint256 add2 = ABDKMath64x64.mulu( asset0Price, ABDKMath64x64.mulu(liquidityRatio, amountsMinted.amount0ToMint) ); uint256 add3 = ABDKMath64x64.mulu(asset0Price, amountsMinted.amount0Minted); uint256 add = add1.add(add2).add(add3).add(amountsMinted.amount1Minted); // Some numbers are too big to fit in ABDK's div 128-bit representation // So calculate the root of the equation and then raise to the 2nd power int128 nRatio = ABDKMath64x64.divu( ABDKMath64x64.sqrtu(sub), ABDKMath64x64.sqrtu(add) ); int64 n = ABDKMath64x64.toInt(nRatio); swapAmount = uint256(n)**2; } /** * @dev Returns amount in terms of asset 0 * @dev amount * asset 1 price */ function getAmountInAsset0Terms(uint256 amount, int128 asset1Price) public pure returns (uint256) { return ABDKMath64x64.mulu(asset1Price, amount); } /** * @dev Returns amount in terms of asset 1 * @dev amount * asset 0 price */ function getAmountInAsset1Terms(uint256 amount, int128 asset0Price) public pure returns (uint256) { return ABDKMath64x64.mulu(asset0Price, amount); } // comparator for 32-bit timestamps // @return bool Whether a <= b function lte( uint32 time, uint32 a, uint32 b ) internal pure returns (bool) { if (a <= time && b <= time) return a <= b; uint256 aAdjusted = a > time ? a : a + 2**32; uint256 bAdjusted = b > time ? b : b + 2**32; return aAdjusted <= bAdjusted; } // Subtract two numbers and return absolute value function subAbs(uint256 amount0, uint256 amount1) internal pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.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: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Creates and initializes V3 Pools /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that /// require the pool to exist. interface IPoolInitializer { /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title ERC721 with permit /// @notice Extension to ERC721 that includes a permit function for signature based approvals interface IERC721Permit is IERC721 { /// @notice The permit typehash used in the permit signature /// @return The typehash for the permit function PERMIT_TYPEHASH() external pure returns (bytes32); /// @notice The domain separator used in the permit signature /// @return The domain seperator used in encoding of permit signature function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xc02f72e8ae5e68802e6d893d58ddfb0df89a2f4c9c2f04927db1186a29373660; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../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 pragma solidity ^0.7.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-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); }
Returns token0 amount in token0Decimals/
function getToken0AmountInNativeDecimals(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken0AmountInNativeDecimals( amount, token0Decimals, token0DecimalMultiplier ); }
10,200,424
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; contract Token { // total supply of tokens uint public totalSupply = 10000; // public name of token like 'Bitcoin' string public name = "My Token"; // symbol of tokejn, like 'BTC' string public symbol = "TKN"; // defines smallest fraction of token we can transfer // 18 - is most common decimals for tokin uint public decimals = 18; // list of all balances mapping (address => uint) public balances; // a user can have allowed addresses to spend some value mapping (address => mapping(address => uint)) public allowance; event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); constructor () { // deploying whole supply of token balances[msg.sender] = totalSupply; } function balanceOf(address owner) public view returns (uint) { // returns balance of the owner return balances[owner]; } // 1 * 10 ** 18 - value function transfer(address to, uint value) public returns (bool) { // checks if there is enought amount in sender balance require(balanceOf(msg.sender) >= value, 'balance to low'); // increments balance of receiver balances[to] += value; // decrement balance of sender balances[msg.sender] -= value; // emit the event emit Transfer(msg.sender, to, value); // return success return true; } function transferFrom(address from, address to, uint value) public returns (bool){ // checks if there is enought amount in from balance require(balanceOf(from) >= value, 'balance too low'); require(allowance[from][msg.sender] >= value, 'allowance too low'); // increments balance of receiver balances[to] += value; // decrement balance of owner balances[from] -= value; // emit the event emit Transfer(from, to, value); // return success return true; } function approve(address spender, uint value) public returns(bool) { // spender is allowed to spend the value from the sender allowance[msg.sender][spender] = value; // emit the event emit Approval(msg.sender, spender, value); // return success return true; } }
spender is allowed to spend the value from the sender emit the event return success
function approve(address spender, uint value) public returns(bool) { allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; }
13,006,571
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; /* * Merkle Tree Utilities for Rollup */ contract RollupMerkleUtils { /* Structs */ // A partial merkle tree which can be updated with new nodes, recomputing the root struct SparseMerkleTree { // The root bytes32 root; uint height; mapping (bytes32 => bytes32) nodes; } /* Fields */ // The default hashes bytes32[160] public defaultHashes; // A tree which is used in `update()` and `store()` SparseMerkleTree public tree; /** * @notice Initialize a new SparseMerkleUtils contract, computing the default hashes for the sparse merkle tree (SMT) */ constructor() public { // Calculate & set the default hashes setDefaultHashes(); } /* Methods */ /** * @notice Set default hashes */ function setDefaultHashes() private { // Set the initial default hash. defaultHashes[0] = keccak256(abi.encodePacked(uint(0))); for (uint i = 1; i < defaultHashes.length; i ++) { defaultHashes[i] = keccak256(abi.encodePacked(defaultHashes[i-1], defaultHashes[i-1])); } } /** * @notice Get the sparse merkle root computed from some set of data blocks. * @param _dataBlocks The data being used to generate the tree. * @return the sparse merkle tree root */ function getMerkleRoot(bytes[] calldata _dataBlocks) external view returns(bytes32) { uint nextLevelLength = _dataBlocks.length; uint currentLevel = 0; bytes32[] memory nodes = new bytes32[](nextLevelLength + 1); // Add one in case we have an odd number of leaves // Generate the leaves for (uint i = 0; i < _dataBlocks.length; i++) { nodes[i] = keccak256(_dataBlocks[i]); } if (_dataBlocks.length == 1) { return nodes[0]; } // Add a defaultNode if we've got an odd number of leaves if (nextLevelLength % 2 == 1) { nodes[nextLevelLength] = defaultHashes[currentLevel]; nextLevelLength += 1; } // Now generate each level while (nextLevelLength > 1) { currentLevel += 1; // Calculate the nodes for the currentLevel for (uint i = 0; i < nextLevelLength / 2; i++) { nodes[i] = getParent(nodes[i*2], nodes[i*2 + 1]); } nextLevelLength = nextLevelLength / 2; // Check if we will need to add an extra node if (nextLevelLength % 2 == 1 && nextLevelLength != 1) { nodes[nextLevelLength] = defaultHashes[currentLevel]; nextLevelLength += 1; } } // Alright! We should be left with a single node! Return it... return nodes[0]; } /** * @notice Calculate root from an inclusion proof. * @param _dataBlock The data block we're calculating root for. * @param _path The path from the leaf to the root. * @param _siblings The sibling nodes along the way. * @return The next level of the tree */ function computeInclusionProofRoot(bytes memory _dataBlock, uint _path, bytes32[] memory _siblings) public pure returns (bytes32) { // First compute the leaf node bytes32 computedNode = keccak256(_dataBlock); for (uint i = 0; i < _siblings.length; i++) { bytes32 sibling = _siblings[i]; uint8 isComputedRightSibling = getNthBitFromRight(_path, i); if (isComputedRightSibling == 0) { computedNode = getParent(computedNode, sibling); } else { computedNode = getParent(sibling, computedNode); } } // Check if the computed node (_root) is equal to the provided root return computedNode; } /** * @notice Verify an inclusion proof. * @param _root The root of the tree we are verifying inclusion for. * @param _dataBlock The data block we're verifying inclusion for. * @param _path The path from the leaf to the root. * @param _siblings The sibling nodes along the way. * @return The next level of the tree */ function verify(bytes32 _root, bytes memory _dataBlock, uint _path, bytes32[] memory _siblings) public pure returns (bool) { // First compute the leaf node bytes32 calculatedRoot = computeInclusionProofRoot( _dataBlock, _path, _siblings ); return calculatedRoot == _root; } /** * @notice Update the stored tree / root with a particular dataBlock at some path (no siblings needed) * @param _dataBlock The data block we're storing/verifying * @param _path The path from the leaf to the root / the index of the leaf. */ function update(bytes memory _dataBlock, uint _path) public { bytes32[] memory siblings = getSiblings(_path); store(_dataBlock, _path, siblings); } /** * @notice Update the stored tree / root with a particular leaf hash at some path (no siblings needed) * @param _leaf The leaf we're storing/verifying * @param _path The path from the leaf to the root / the index of the leaf. */ function updateLeaf(bytes32 _leaf, uint _path) public { bytes32[] memory siblings = getSiblings(_path); storeLeaf(_leaf, _path, siblings); } /** * @notice Store a particular merkle proof & verify that the root did not change. * @param _dataBlock The data block we're storing/verifying * @param _path The path from the leaf to the root / the index of the leaf. * @param _siblings The sibling nodes along the way. */ function verifyAndStore(bytes memory _dataBlock, uint _path, bytes32[] memory _siblings) public { bytes32 oldRoot = tree.root; store(_dataBlock, _path, _siblings); require(tree.root == oldRoot, "Failed same root verification check! This was an inclusion proof for a different tree!"); } /** * @notice Store a particular dataBlock & its intermediate nodes in the tree * @param _dataBlock The data block we're storing. * @param _path The path from the leaf to the root / the index of the leaf. * @param _siblings The sibling nodes along the way. */ function store(bytes memory _dataBlock, uint _path, bytes32[] memory _siblings) public { // Compute the leaf node & store the leaf bytes32 leaf = keccak256(_dataBlock); storeLeaf(leaf, _path, _siblings); } /** * @notice Store a particular leaf hash & its intermediate nodes in the tree * @param _leaf The leaf we're storing. * @param _path The path from the leaf to the root / the index of the leaf. * @param _siblings The sibling nodes along the way. */ function storeLeaf(bytes32 _leaf, uint _path, bytes32[] memory _siblings) public { // First compute the leaf node bytes32 computedNode = _leaf; for (uint i = 0; i < _siblings.length; i++) { bytes32 parent; bytes32 sibling = _siblings[i]; uint8 isComputedRightSibling = getNthBitFromRight(_path, i); if (isComputedRightSibling == 0) { parent = getParent(computedNode, sibling); // Store the node! storeNode(parent, computedNode, sibling); } else { parent = getParent(sibling, computedNode); // Store the node! storeNode(parent, sibling, computedNode); } computedNode = parent; } // Store the new root tree.root = computedNode; } /** * @notice Get siblings for a leaf at a particular index of the tree. * This is used for updates which don't include sibling nodes. * @param _path The path from the leaf to the root / the index of the leaf. * @return The sibling nodes along the way. */ function getSiblings(uint _path) public view returns (bytes32[] memory) { bytes32[] memory siblings = new bytes32[](tree.height); bytes32 computedNode = tree.root; for(uint i = tree.height; i > 0; i--) { uint siblingIndex = i-1; (bytes32 leftChild, bytes32 rightChild) = getChildren(computedNode); if (getNthBitFromRight(_path, siblingIndex) == 0) { computedNode = leftChild; siblings[siblingIndex] = rightChild; } else { computedNode = rightChild; siblings[siblingIndex] = leftChild; } } // Now store everything return siblings; } /********************* * Utility Functions * ********************/ /** * @notice Get our stored tree's root * @return The merkle root of the tree */ function getRoot() public view returns(bytes32) { return tree.root; } /** * @notice Set the tree root and height of the stored tree * @param _root The merkle root of the tree * @param _height The height of the tree */ function setMerkleRootAndHeight(bytes32 _root, uint _height) public { tree.root = _root; tree.height = _height; } /** * @notice Store node in the (in-storage) sparse merkle tree * @param _parent The parent node * @param _leftChild The left child of the parent in the tree * @param _rightChild The right child of the parent in the tree */ function storeNode(bytes32 _parent, bytes32 _leftChild, bytes32 _rightChild) public { tree.nodes[getLeftSiblingKey(_parent)] = _leftChild; tree.nodes[getRightSiblingKey(_parent)] = _rightChild; } /** * @notice Get the parent of two children nodes in the tree * @param _left The left child * @param _right The right child * @return The parent node */ function getParent(bytes32 _left, bytes32 _right) internal pure returns(bytes32) { return keccak256(abi.encodePacked(_left, _right)); } /** * @notice get the n'th bit in a uint. * For instance, if exampleUint=binary(11), getNth(exampleUint, 0) == 1, getNth(2, 1) == 1 * @param _intVal The uint we are extracting a bit out of * @param _index The index of the bit we want to extract * @return The bit (1 or 0) in a uint8 */ function getNthBitFromRight(uint _intVal, uint _index) public pure returns (uint8) { return uint8(_intVal >> _index & 1); } /** * @notice Get the children of some parent in the tree * @param _parent The parent node * @return (rightChild, leftChild) -- the two children of the parent */ function getChildren(bytes32 _parent) public view returns(bytes32, bytes32) { return (tree.nodes[getLeftSiblingKey(_parent)], tree.nodes[getRightSiblingKey(_parent)]); } /** * @notice Get the right sibling key. Note that these keys overwrite the first bit of the hash to signify if it is on the right side of the parent or on the left * @param _parent The parent node * @return the key for the left sibling (0 as the first bit) */ function getLeftSiblingKey(bytes32 _parent) public pure returns(bytes32) { return _parent & 0x0111111111111111111111111111111111111111111111111111111111111111; } /** * @notice Get the right sibling key. Note that these keys overwrite the first bit of the hash to signify if it is on the right side of the parent or on the left * @param _parent The parent node * @return the key for the right sibling (1 as the first bit) */ function getRightSiblingKey(bytes32 _parent) public pure returns(bytes32) { return _parent | 0x1000000000000000000000000000000000000000000000000000000000000000; } }
Get the parent of two children nodes in the tree _left The left child _right The right child return The parent node/
function getParent(bytes32 _left, bytes32 _right) internal pure returns(bytes32) { return keccak256(abi.encodePacked(_left, _right)); }
5,448,937
pragma solidity 0.4.25; 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 _0xBitconnect { using SafeMath for uint; /*================================= = MODIFIERS = =================================*/ modifier onlyHolders() { require(myFrontEndTokens() > 0); _; } modifier dividendHolder() { require(myDividends(true) > 0); _; } modifier onlyAdministrator() { address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint incoming, uint8 dividendRate, uint tokensMinted, address indexed referredBy ); event UserDividendRate( address user, uint divRate ); event onTokenSell( address indexed customerAddress, uint tokensBurned, uint earned ); event onReinvestment( address indexed customerAddress, uint reinvested, uint tokensMinted ); event onWithdraw( address indexed customerAddress, uint withdrawn ); event Transfer( address indexed from, address indexed to, uint tokens ); event Approval( address indexed tokenOwner, address indexed spender, uint tokens ); event Allocation( uint toBankRoll, uint toReferrer, uint toTokenHolders, uint toDivCardHolders, uint forTokens ); event Referral( address referrer, uint amountReceived ); /*===================================== = CONSTANTS = =====================================*/ uint8 constant public decimals = 18; uint constant internal magnitude = 2 ** 64; uint constant internal MULTIPLIER = 1140; uint constant internal MIN_TOK_BUYIN = 0.0001 ether; uint constant internal MIN_TOKEN_SELL_AMOUNT = 0.0001 ether; uint constant internal MIN_TOKEN_TRANSFER = 1e10; uint constant internal referrer_percentage = 25; uint constant internal MAX_SUPPLY = 1e25; ERC20Interface internal _0xBTC; uint public stakingRequirement = 100e18; /*================================ = CONFIGURABLES = ================================*/ string public name = "0xBitconnect"; string public symbol = "0xBCC"; address internal bankrollAddress; _0xBitconnectDividendCards divCardContract; /*================================ = DATASETS = ================================*/ // Tracks front & backend tokens mapping(address => uint) internal frontTokenBalanceLedger_; mapping(address => uint) internal dividendTokenBalanceLedger_; mapping(address => mapping(address => uint)) public allowed; // Tracks dividend rates for users mapping(uint8 => bool) internal validDividendRates_; mapping(address => bool) internal userSelectedRate; mapping(address => uint8) internal userDividendRate; // Payout tracking mapping(address => uint) internal referralBalance_; mapping(address => int256) internal payoutsTo_; uint public current0xbtcInvested; uint internal tokenSupply = 0; uint internal divTokenSupply = 0; uint internal profitPerDivToken; mapping(address => bool) public administrators; bool public regularPhase = false; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ constructor(address _bankrollAddress, address _divCardAddress, address _btcAddress) public { bankrollAddress = _bankrollAddress; divCardContract = _0xBitconnectDividendCards(_divCardAddress); _0xBTC = ERC20Interface(_btcAddress); administrators[msg.sender] = true; // Helps with debugging! validDividendRates_[10] = true; validDividendRates_[20] = true; validDividendRates_[30] = true; userSelectedRate[bankrollAddress] = true; userDividendRate[bankrollAddress] = 30; /*======================================= = INITIAL HEAVEN = =======================================*/ uint initiallyAssigned = 3*10**24; address heavenA = 0xA7cDc6cF8E8a4db39bc03ac675662D6E2F8F84f3; address heavenB = 0xbC539A28e85c587987297da7039949eA23b51723; userSelectedRate[heavenA] = true; userDividendRate[heavenA] = 30; userSelectedRate[heavenB] = true; userDividendRate[heavenB] = 30; tokenSupply = tokenSupply.add(initiallyAssigned); divTokenSupply = divTokenSupply.add(initiallyAssigned.mul(30)); profitPerDivToken = profitPerDivToken.add((initiallyAssigned.mul(magnitude)).div(divTokenSupply)); payoutsTo_[heavenA] += (int256)((profitPerDivToken * (initiallyAssigned.div(3)).mul(userDividendRate[heavenA]))); payoutsTo_[heavenB] += (int256)((profitPerDivToken * (initiallyAssigned.div(3)).mul(userDividendRate[heavenB]))); payoutsTo_[bankrollAddress] += (int256)((profitPerDivToken * (initiallyAssigned.div(3)).mul(userDividendRate[bankrollAddress]))); frontTokenBalanceLedger_[heavenA] = frontTokenBalanceLedger_[heavenA].add(initiallyAssigned.div(3)); dividendTokenBalanceLedger_[heavenA] = dividendTokenBalanceLedger_[heavenA].add((initiallyAssigned.div(3)).mul(userDividendRate[heavenA])); frontTokenBalanceLedger_[heavenB] = frontTokenBalanceLedger_[heavenB].add(initiallyAssigned.div(3)); dividendTokenBalanceLedger_[heavenB] = dividendTokenBalanceLedger_[heavenB].add((initiallyAssigned.div(3)).mul(userDividendRate[heavenB])); frontTokenBalanceLedger_[bankrollAddress] = frontTokenBalanceLedger_[bankrollAddress].add(initiallyAssigned.div(3)); dividendTokenBalanceLedger_[bankrollAddress] = dividendTokenBalanceLedger_[bankrollAddress].add((initiallyAssigned.div(3)).mul(userDividendRate[bankrollAddress])); } /** * Same as buy, but explicitly sets your dividend percentage. * If this has been called before, it will update your `default' dividend * percentage for regular buy transactions going forward. */ function buyAndSetDivPercentage(uint _0xbtcAmount, address _referredBy, uint8 _divChoice, string providedUnhashedPass) public returns(uint) { require(regularPhase); // Dividend percentage should be a currently accepted value. require(validDividendRates_[_divChoice]); // Set the dividend fee percentage denominator. userSelectedRate[msg.sender] = true; userDividendRate[msg.sender] = _divChoice; emit UserDividendRate(msg.sender, _divChoice); // Finally, purchase tokens. purchaseTokens(_0xbtcAmount, _referredBy, false); } // All buys except for the above one require regular phase. function buy(uint _0xbtcAmount, address _referredBy) public returns(uint) { require(regularPhase); address _customerAddress = msg.sender; require(userSelectedRate[_customerAddress]); purchaseTokens(_0xbtcAmount, _referredBy, false); } function buyAndTransfer(uint _0xbtcAmount, address _referredBy, address target) public { bytes memory empty; buyAndTransfer(_0xbtcAmount, _referredBy, target, empty, 20); } function buyAndTransfer(uint _0xbtcAmount, address _referredBy, address target, bytes _data) public { buyAndTransfer(_0xbtcAmount, _referredBy, target, _data, 20); } // Overload function buyAndTransfer(uint _0xbtcAmount, address _referredBy, address target, bytes _data, uint8 divChoice) public { require(regularPhase); address _customerAddress = msg.sender; uint256 frontendBalance = frontTokenBalanceLedger_[msg.sender]; if (userSelectedRate[_customerAddress] && divChoice == 0) { purchaseTokens(_0xbtcAmount, _referredBy, false); } else { buyAndSetDivPercentage(_0xbtcAmount, _referredBy, divChoice, "0x0"); } uint256 difference = SafeMath.sub(frontTokenBalanceLedger_[msg.sender], frontendBalance); transferTo(msg.sender, target, difference, _data); } // No Fallback functionality function () public { revert(); } function reinvest() dividendHolder() public { require(regularPhase); uint _dividends = myDividends(false); // Pay out requisite `virtual' dividends. address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256)(_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; uint _tokens = purchaseTokens(_dividends.div(1e10), address(0), true); //to 8 Decimals // Fire logging event. emit onReinvestment(_customerAddress, _dividends, _tokens); } function exit() public { require(regularPhase); // Retrieve token balance for caller, then sell them all. address _customerAddress = msg.sender; uint _tokens = frontTokenBalanceLedger_[_customerAddress]; if (_tokens > 0) sell(_tokens); withdraw(_customerAddress); } function withdraw(address _recipient) dividendHolder() public { require(regularPhase); // Setup data address _customerAddress = msg.sender; uint _dividends = myDividends(false); // update dividend tracker payoutsTo_[_customerAddress] += (int256)(_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; if (_recipient == address(0x0)) { _recipient = msg.sender; } _dividends = _dividends.div(1e10); //to 8 decimals _0xBTC.transfer(_recipient, _dividends); // Fire logging event. emit onWithdraw(_recipient, _dividends); } // Sells front-end tokens. function sell(uint _amountOfTokens) onlyHolders() public { require(regularPhase); require(_amountOfTokens <= frontTokenBalanceLedger_[msg.sender]); uint _frontEndTokensToBurn = _amountOfTokens; // Calculate how many dividend tokens this action burns. // Computed as the caller's average dividend rate multiplied by the number of front-end tokens held. // As an additional guard, we ensure that the dividend rate is between 2 and 50 inclusive. uint userDivRate = getUserAverageDividendRate(msg.sender); require((2 * magnitude) <= userDivRate && (50 * magnitude) >= userDivRate); uint _divTokensToBurn = (_frontEndTokensToBurn.mul(userDivRate)).div(magnitude); // Calculate 0xbtc received before dividends uint _0xbtc = tokensTo0xbtc_(_frontEndTokensToBurn); if (_0xbtc > current0xbtcInvested) { // Well, congratulations, you've emptied the coffers. current0xbtcInvested = 0; } else { current0xbtcInvested = current0xbtcInvested - _0xbtc; } // Calculate dividends generated from the sale. uint _dividends = (_0xbtc.mul(getUserAverageDividendRate(msg.sender)).div(100)).div(magnitude); // Calculate 0xbtc receivable net of dividends. uint _taxed0xbtc = _0xbtc.sub(_dividends); // Burn the sold tokens (both front-end and back-end variants). tokenSupply = tokenSupply.sub(_frontEndTokensToBurn); divTokenSupply = divTokenSupply.sub(_divTokensToBurn); // Subtract the token balances for the seller frontTokenBalanceLedger_[msg.sender] = frontTokenBalanceLedger_[msg.sender].sub(_frontEndTokensToBurn); dividendTokenBalanceLedger_[msg.sender] = dividendTokenBalanceLedger_[msg.sender].sub(_divTokensToBurn); // Update dividends tracker int256 _updatedPayouts = (int256)(profitPerDivToken * _divTokensToBurn + (_taxed0xbtc * magnitude)); payoutsTo_[msg.sender] -= _updatedPayouts; // Let's avoid breaking arithmetic where we can, eh? if (divTokenSupply > 0) { // Update the value of each remaining back-end dividend token. profitPerDivToken = profitPerDivToken.add((_dividends * magnitude) / divTokenSupply); } // Fire logging event. emit onTokenSell(msg.sender, _frontEndTokensToBurn, _taxed0xbtc); } /** * Transfer tokens from the caller to a new holder. * No charge incurred for the transfer. We'd make a terrible bank. */ function transfer(address _toAddress, uint _amountOfTokens) onlyHolders() public returns(bool) { require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= frontTokenBalanceLedger_[msg.sender]); bytes memory empty; transferFromInternal(msg.sender, _toAddress, _amountOfTokens, empty); return true; } function approve(address spender, uint tokens) public returns(bool) { address _customerAddress = msg.sender; allowed[_customerAddress][spender] = tokens; // Fire logging event. emit Approval(_customerAddress, spender, tokens); // Good old ERC20. return true; } /** * Transfer tokens from the caller to a new holder: the Used By Smart Contracts edition. * No charge incurred for the transfer. No seriously, we'd make a terrible bank. */ function transferFrom(address _from, address _toAddress, uint _amountOfTokens) public returns(bool) { // Setup variables address _customerAddress = _from; bytes memory empty; // Make sure we own the tokens we're transferring, are ALLOWED to transfer that many tokens, // and are transferring at least one full token. require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= frontTokenBalanceLedger_[_customerAddress] && _amountOfTokens <= allowed[_customerAddress][msg.sender]); transferFromInternal(_from, _toAddress, _amountOfTokens, empty); // Good old ERC20. return true; } function transferTo(address _from, address _to, uint _amountOfTokens, bytes _data) public { if (_from != msg.sender) { require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= frontTokenBalanceLedger_[_from] && _amountOfTokens <= allowed[_from][msg.sender]); } else { require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= frontTokenBalanceLedger_[_from]); } transferFromInternal(_from, _to, _amountOfTokens, _data); } // Who'd have thought we'd need this thing floating around? function totalSupply() public view returns(uint256) { return tokenSupply; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ function startRegularPhase() onlyAdministrator public { regularPhase = true; } // The death of a great man demands the birth of a great son. function setAdministrator(address _newAdmin, bool _status) onlyAdministrator() public { administrators[_newAdmin] = _status; } function setStakingRequirement(uint _amountOfTokens) onlyAdministrator() public { // This plane only goes one way, lads. Never below the initial. require(_amountOfTokens >= 100e18); stakingRequirement = _amountOfTokens; } function setName(string _name) onlyAdministrator() public { name = _name; } function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } function changeBankroll(address _newBankrollAddress) onlyAdministrator public { bankrollAddress = _newBankrollAddress; } /*---------- HELPERS AND CALCULATORS ----------*/ function total0xbtcBalance() public view returns(uint) { return _0xBTC.balanceOf(address(this)); } function total0xbtcReceived() public view returns(uint) { return current0xbtcInvested; } /** * Retrieves your currently selected dividend rate. */ function getMyDividendRate() public view returns(uint8) { address _customerAddress = msg.sender; require(userSelectedRate[_customerAddress]); return userDividendRate[_customerAddress]; } /** * Retrieve the total frontend token supply */ function getFrontEndTokenSupply() public view returns(uint) { return tokenSupply; } /** * Retreive the total dividend token supply */ function getDividendTokenSupply() public view returns(uint) { return divTokenSupply; } /** * Retrieve the frontend tokens owned by the caller */ function myFrontEndTokens() public view returns(uint) { address _customerAddress = msg.sender; return getFrontEndTokenBalanceOf(_customerAddress); } /** * Retrieve the dividend tokens owned by the caller */ function myDividendTokens() public view returns(uint) { address _customerAddress = msg.sender; return getDividendTokenBalanceOf(_customerAddress); } function myReferralDividends() public view returns(uint) { return myDividends(true) - myDividends(false); } function myDividends(bool _includeReferralBonus) public view returns(uint) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress); } function theDividendsOf(bool _includeReferralBonus, address _customerAddress) public view returns(uint) { return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress); } function getFrontEndTokenBalanceOf(address _customerAddress) view public returns(uint) { return frontTokenBalanceLedger_[_customerAddress]; } function balanceOf(address _owner) view public returns(uint) { return getFrontEndTokenBalanceOf(_owner); } function getDividendTokenBalanceOf(address _customerAddress) view public returns(uint) { return dividendTokenBalanceLedger_[_customerAddress]; } function dividendsOf(address _customerAddress) view public returns(uint) { return (uint)((int256)(profitPerDivToken * dividendTokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } // Get the sell price at the user's average dividend rate function sellPrice() public view returns(uint) { uint price; // Calculate the tokens received for 0.001 0xbtc. // Divide to find the average, to calculate the price. uint tokensReceivedFor0xbtc = btcToTokens_(0.001 ether); price = (1e18 * 0.001 ether) / tokensReceivedFor0xbtc; // Factor in the user's average dividend rate uint theSellPrice = price.sub((price.mul(getUserAverageDividendRate(msg.sender)).div(100)).div(magnitude)); return theSellPrice; } // Get the buy price at a particular dividend rate function buyPrice(uint dividendRate) public view returns(uint) { uint price; // Calculate the tokens received for 100 finney. // Divide to find the average, to calculate the price. uint tokensReceivedFor0xbtc = btcToTokens_(0.001 ether); price = (1e18 * 0.001 ether) / tokensReceivedFor0xbtc; // Factor in the user's selected dividend rate uint theBuyPrice = (price.mul(dividendRate).div(100)).add(price); return theBuyPrice; } function calculateTokensReceived(uint _0xbtcToSpend) public view returns(uint) { uint fixedAmount = _0xbtcToSpend.mul(1e10); uint _dividends = (fixedAmount.mul(userDividendRate[msg.sender])).div(100); uint _taxed0xbtc = fixedAmount.sub(_dividends); uint _amountOfTokens = btcToTokens_(_taxed0xbtc); return _amountOfTokens; } // When selling tokens, we need to calculate the user's current dividend rate. // This is different from their selected dividend rate. function calculate0xbtcReceived(uint _tokensToSell) public view returns(uint) { require(_tokensToSell <= tokenSupply); uint _0xbtc = tokensTo0xbtc_(_tokensToSell); uint userAverageDividendRate = getUserAverageDividendRate(msg.sender); uint _dividends = (_0xbtc.mul(userAverageDividendRate).div(100)).div(magnitude); uint _taxed0xbtc = _0xbtc.sub(_dividends); return _taxed0xbtc.div(1e10); } /* * Get's a user's average dividend rate - which is just their divTokenBalance / tokenBalance * We multiply by magnitude to avoid precision errors. */ function getUserAverageDividendRate(address user) public view returns(uint) { return (magnitude * dividendTokenBalanceLedger_[user]).div(frontTokenBalanceLedger_[user]); } function getMyAverageDividendRate() public view returns(uint) { return getUserAverageDividendRate(msg.sender); } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ /* Purchase tokens with 0xbtc. During normal operation: 0.5% should go to the master dividend card 0.5% should go to the matching dividend card 25% of dividends should go to the referrer, if any is provided. */ function purchaseTokens(uint _incoming, address _referredBy, bool _reinvest) internal returns(uint) { require(_incoming.mul(1e10) >= MIN_TOK_BUYIN || msg.sender == bankrollAddress, "Tried to buy below the min 0xbtc buyin threshold."); uint toReferrer; uint toTokenHolders; uint toDivCardHolders; uint dividendAmount; uint tokensBought; uint remaining0xbtc = _incoming.mul(1e10); uint fee; // 1% for dividend card holders is taken off before anything else if (regularPhase) { toDivCardHolders = _incoming.mul(1e8); remaining0xbtc = remaining0xbtc.sub(toDivCardHolders); } /* Next, we tax for dividends: Dividends = (0xbtc * div%) / 100 Important note: the 1% sent to div-card holders is handled prior to any dividend taxes are considered. */ // Calculate the total dividends on this buy dividendAmount = (remaining0xbtc.mul(userDividendRate[msg.sender])).div(100); remaining0xbtc = remaining0xbtc.sub(dividendAmount); // Calculate how many tokens to buy: tokensBought = btcToTokens_(remaining0xbtc); // This is where we actually mint tokens: require(tokenSupply.add(tokensBought) <= MAX_SUPPLY); tokenSupply = tokenSupply.add(tokensBought); divTokenSupply = divTokenSupply.add(tokensBought.mul(userDividendRate[msg.sender])); /* Update the total investment tracker Note that this must be done AFTER we calculate how many tokens are bought - because btcToTokens needs to know the amount *before* investment, not *after* investment. */ current0xbtcInvested = current0xbtcInvested + remaining0xbtc; // Ccheck for referrals // 25% goes to referrers, if set // toReferrer = (dividends * 25)/100 if (_referredBy != 0x0000000000000000000000000000000000000000 && _referredBy != msg.sender && frontTokenBalanceLedger_[_referredBy] >= stakingRequirement) { toReferrer = (dividendAmount.mul(referrer_percentage)).div(100); referralBalance_[_referredBy] += toReferrer; emit Referral(_referredBy, toReferrer); } // The rest of the dividends go to token holders toTokenHolders = dividendAmount.sub(toReferrer); fee = toTokenHolders * magnitude; fee = fee - (fee - (tokensBought.mul(userDividendRate[msg.sender]) * (toTokenHolders * magnitude / (divTokenSupply)))); // Finally, increase the divToken value profitPerDivToken = profitPerDivToken.add((toTokenHolders.mul(magnitude)).div(divTokenSupply)); payoutsTo_[msg.sender] += (int256)((profitPerDivToken * tokensBought.mul(userDividendRate[msg.sender])) - fee); // Update the buyer's token amounts frontTokenBalanceLedger_[msg.sender] = frontTokenBalanceLedger_[msg.sender].add(tokensBought); dividendTokenBalanceLedger_[msg.sender] = dividendTokenBalanceLedger_[msg.sender].add(tokensBought.mul(userDividendRate[msg.sender])); if (_reinvest == false) { //Lets receive the 0xbtc _0xBTC.transferFrom(msg.sender, address(this), _incoming); } // Transfer to div cards if (regularPhase) { _0xBTC.approve(address(divCardContract), toDivCardHolders.div(1e10)); divCardContract.receiveDividends(toDivCardHolders.div(1e10), userDividendRate[msg.sender]); } // This event should help us track where all the 0xbtc is going emit Allocation(0, toReferrer, toTokenHolders, toDivCardHolders, remaining0xbtc); emit onTokenPurchase(msg.sender, _incoming, userDividendRate[msg.sender], tokensBought, _referredBy); // Sanity checking uint sum = toReferrer + toTokenHolders + toDivCardHolders + remaining0xbtc - _incoming.mul(1e10); assert(sum == 0); } // How many tokens one gets from a certain amount of 0xbtc. function btcToTokens_(uint _0xbtcAmount) public view returns(uint) { //0xbtcAmount expected as 18 decimals instead of 8 require(_0xbtcAmount > MIN_TOK_BUYIN, "Tried to buy tokens with too little 0xbtc."); uint _0xbtcTowardsVariablePriceTokens = _0xbtcAmount; uint varPriceTokens = 0; if (_0xbtcTowardsVariablePriceTokens != 0) { uint simulated0xbtcBeforeInvested = toPowerOfThreeHalves(tokenSupply.div(MULTIPLIER * 1e6)).mul(2).div(3); uint simulated0xbtcAfterInvested = simulated0xbtcBeforeInvested + _0xbtcTowardsVariablePriceTokens; uint tokensBefore = toPowerOfTwoThirds(simulated0xbtcBeforeInvested.mul(3).div(2)).mul(MULTIPLIER); uint tokensAfter = toPowerOfTwoThirds(simulated0xbtcAfterInvested.mul(3).div(2)).mul(MULTIPLIER); /* Investment IS already multiplied by 1e18; however, because this is taken to a power of (2/3), we need to multiply the result by 1e6 to get back to the correct number of decimals. */ varPriceTokens = (1e6) * tokensAfter.sub(tokensBefore); } uint totalTokensReceived = varPriceTokens; assert(totalTokensReceived > 0); return totalTokensReceived; } // How much 0xBTC we get from selling N tokens function tokensTo0xbtc_(uint _tokens) public view returns(uint) { require(_tokens >= MIN_TOKEN_SELL_AMOUNT, "Tried to sell too few tokens."); /* * i = investment, p = price, t = number of tokens * * i_current = p_initial * t_current (for t_current <= t_initial) * i_current = i_initial + (2/3)(t_current)^(3/2) (for t_current > t_initial) * * t_current = i_current / p_initial (for i_current <= i_initial) * t_current = t_initial + ((3/2)(i_current))^(2/3) (for i_current > i_initial) */ uint tokensToSellAtVariablePrice = _tokens; uint _0xbtcFromVarPriceTokens; // Now, actually calculate: if (tokensToSellAtVariablePrice != 0) { /* Note: Unlike the sister function in btcToTokens, we don't have to calculate any "virtual" token count. We have the equations for total investment above; note that this is for TOTAL. To get the 0xbtc received from this sell, we calculate the new total investment after this sell. Note that we divide by 1e6 here as the inverse of multiplying by 1e6 in btcToTokens. */ uint investmentBefore = toPowerOfThreeHalves(tokenSupply.div(MULTIPLIER * 1e6)).mul(2).div(3); uint investmentAfter = toPowerOfThreeHalves((tokenSupply - tokensToSellAtVariablePrice).div(MULTIPLIER * 1e6)).mul(2).div(3); _0xbtcFromVarPriceTokens = investmentBefore.sub(investmentAfter); } uint _0xbtcReceived = _0xbtcFromVarPriceTokens; assert(_0xbtcReceived > 0); return _0xbtcReceived; } function transferFromInternal(address _from, address _toAddress, uint _amountOfTokens, bytes _data) internal { require(regularPhase); require(_toAddress != address(0x0)); address _customerAddress = _from; uint _amountOfFrontEndTokens = _amountOfTokens; // Withdraw all outstanding dividends first (including those generated from referrals). if (theDividendsOf(true, _customerAddress) > 0) withdrawFrom(_customerAddress); // Calculate how many back-end dividend tokens to transfer. // This amount is proportional to the caller's average dividend rate multiplied by the proportion of tokens being transferred. uint _amountOfDivTokens = _amountOfFrontEndTokens.mul(getUserAverageDividendRate(_customerAddress)).div(magnitude); if (_customerAddress != msg.sender) { // Update the allowed balance. // Don't update this if we are transferring our own tokens (via transfer or buyAndTransfer) allowed[_customerAddress][msg.sender] -= _amountOfTokens; } // Exchange tokens frontTokenBalanceLedger_[_customerAddress] = frontTokenBalanceLedger_[_customerAddress].sub(_amountOfFrontEndTokens); frontTokenBalanceLedger_[_toAddress] = frontTokenBalanceLedger_[_toAddress].add(_amountOfFrontEndTokens); dividendTokenBalanceLedger_[_customerAddress] = dividendTokenBalanceLedger_[_customerAddress].sub(_amountOfDivTokens); dividendTokenBalanceLedger_[_toAddress] = dividendTokenBalanceLedger_[_toAddress].add(_amountOfDivTokens); // Recipient inherits dividend percentage if they have not already selected one. if (!userSelectedRate[_toAddress]) { userSelectedRate[_toAddress] = true; userDividendRate[_toAddress] = userDividendRate[_customerAddress]; } // Update dividend trackers payoutsTo_[_customerAddress] -= (int256)(profitPerDivToken * _amountOfDivTokens); payoutsTo_[_toAddress] += (int256)(profitPerDivToken * _amountOfDivTokens); uint length; assembly { length: = extcodesize(_toAddress) } if (length > 0) { // its a contract // note: at ethereum update ALL addresses are contracts ERC223Receiving receiver = ERC223Receiving(_toAddress); receiver.tokenFallback(_from, _amountOfTokens, _data); } // Fire logging event. emit Transfer(_customerAddress, _toAddress, _amountOfFrontEndTokens); } // Called from transferFrom. Always checks if _customerAddress has dividends. function withdrawFrom(address _customerAddress) internal { // Setup data uint _dividends = theDividendsOf(false, _customerAddress); // update dividend tracker payoutsTo_[_customerAddress] += (int256)(_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; _dividends = _dividends.div(1e10); //to 8 decimals _0xBTC.transfer(_customerAddress, _dividends); //8 decimals correction // Fire logging event. emit onWithdraw(_customerAddress, _dividends); } /*======================= = MATHS FUNCTIONS = ======================*/ function toPowerOfThreeHalves(uint x) public pure returns(uint) { // m = 3, n = 2 // sqrt(x^3) return sqrt(x ** 3); } function toPowerOfTwoThirds(uint x) public pure returns(uint) { // m = 2, n = 3 // cbrt(x^2) return cbrt(x ** 2); } function sqrt(uint x) public pure returns(uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } function cbrt(uint x) public pure returns(uint y) { uint z = (x + 1) / 3; y = x; while (z < y) { y = z; z = (x / (z * z) + 2 * z) / 3; } } } /*======================= = INTERFACES = ======================*/ interface _0xBitconnectDividendCards { function ownerOf(uint /*_divCardId*/ ) external pure returns(address); function receiveDividends(uint amount, uint divCardRate) external; } interface _0xBitconnectBankroll { function receiveDividends(uint amount) external; } interface ERC223Receiving { function tokenFallback(address _from, uint _amountOfTokens, bytes _data) external returns(bool); } // Think it's safe to say y'all know what this is. library SafeMath { function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } function div(uint a, uint b) internal pure returns(uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns(uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; assert(c >= a); return c; } }
Pay out requisite `virtual' dividends. Fire logging event.
function reinvest() dividendHolder() public { require(regularPhase); uint _dividends = myDividends(false); address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256)(_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; emit onReinvestment(_customerAddress, _dividends, _tokens); }
6,358,970
./full_match/137/0xf1B4FC3e438c62216CC581C206EC76D59347a148/sources/contracts/GamePot.sol
called by a game controller to end a game leaderboard - a list of wallets in order of descending score requires GAME_CONTROLLER role Figure out the prize pool
function endGame(address[] calldata leaderboard) public { require(hasRole(GAME_CONTROLLER_ROLE, msg.sender), "Only an address with the GAME_CONTROLLER role can do this"); require(gameState == GameState.PLAYING, "Can only start a game from the PLAYING state"); uint prizePool = 0; for(uint i = 0; i < playersInGame.length; i++) { prizePool += price; } if(leaderboard.length == 0) { clearPlayingPlayers(); gameState = GameState.COMPLETE; return; } uint paidOut = 0; for(uint i = 0; i < leaderboard.length; i++) { if(!playersInGameLookup[leaderboard[i]]) { continue; } uint award = calculateAward(leaderboard.length, i, prizePool, paidOut); if(award > 0) { paidOut += award; playerBalances[leaderboard[i]] += award; playerBalanceTotal += award; } } clearPlayingPlayers(); gameState = GameState.COMPLETE; return; }
4,716,243
./partial_match/5/0x5E39DcDB56852C537021058319A5494d2B6ff4D4/sources/ERC20_Fountain.sol
transfers tokens from one address to another make sure sending address has requested tokensupdate allowance (reduce it by tokens to be sent)make the transfer internally
function transferFrom(address fromAddress, address toAddress, uint256 amountTokens) checkTransferApproved(fromAddress , amountTokens) external returns (bool) { require( (amountTokens <= tokenBalanceLedger_[ fromAddress ]), "ERC20: Transfer not allowed - insufficient funds available." ); uint256 pastAllowance = allowance[fromAddress][msg.sender]; uint256 newAllowance = pastAllowance.sub(amountTokens); allowance[fromAddress][msg.sender] = newAllowance; transferInternal(msg.sender, toAddress, amountTokens); return true; }
16,876,320
./full_match/5/0x04996Bf06a0654C8299041086115fbB0B836683f/sources/project_/contracts/HuxleyComicsIssue4.sol
Updates value of 'canRedeemCopy' _value New value of 'canRedeemCopy'/
function setCanRedeemCopy(bool _value) external onlyOwner { canRedeemCopy = _value; }
1,946,792
./partial_match/1/0xf1Bf0Cd65B741872bC3fE506b524f1c927965B3c/sources/src/libraries/codec/ChunkCodec.sol
Return the number of transactions in current block. blockPtr The start memory offset of the block context in memory. return _numTransactions The number of transactions in current block.
function numTransactions(uint256 blockPtr) internal pure returns (uint256 _numTransactions) { assembly { _numTransactions := shr(240, mload(add(blockPtr, 56))) } }
15,709,096
pragma solidity 0.4.24; interface ERC820ImplementerInterface { /// @notice Contracts that implement an interferce in behalf of another contract must return true /// @param addr Address that the contract woll implement the interface in behalf of /// @param interfaceHash keccak256 of the name of the interface /// @return ERC820_ACCEPT_MAGIC if the contract can implement the interface represented by /// `ìnterfaceHash` in behalf of `addr` function canImplementInterfaceForAddress(address addr, bytes32 interfaceHash) view public returns(bytes32); } contract ERC820Registry { bytes4 constant InvalidID = 0xffffffff; bytes4 constant ERC165ID = 0x01ffc9a7; bytes32 constant ERC820_ACCEPT_MAGIC = keccak256("ERC820_ACCEPT_MAGIC"); mapping (address => mapping(bytes32 => address)) interfaces; mapping (address => address) managers; mapping (address => mapping(bytes4 => bool)) erc165Cache; event InterfaceImplementerSet(address indexed addr, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed addr, address indexed newManager); /// @notice Query the hash of an interface given a name /// @param interfaceName Name of the interfce function interfaceHash(string interfaceName) public pure returns(bytes32) { return keccak256(interfaceName); } /// @notice GetManager function getManager(address addr) public view returns(address) { // By default the manager of an address is the same address if (managers[addr] == 0) { return addr; } else { return managers[addr]; } } /// @notice Sets an external `manager` that will be able to call `setInterfaceImplementer()` /// on behalf of the address. /// @param _addr Address that you are defining the manager for. (0x0 if is msg.sender) /// @param newManager The address of the manager for the `addr` that will replace /// the old one. Set to 0x0 if you want to remove the manager. function setManager(address _addr, address newManager) public { address addr = _addr == 0 ? msg.sender : _addr; require(getManager(addr) == msg.sender); managers[addr] = newManager == addr ? 0 : newManager; ManagerChanged(addr, newManager); } /// @notice Query if an address implements an interface and thru which contract /// @param _addr Address that is being queried for the implementation of an interface /// (if _addr == 0 them `msg.sender` is assumed) /// @param iHash SHA3 of the name of the interface as a string /// Example `web3.utils.sha3('ERC777Token`')` /// @return The address of the contract that implements a specific interface /// or 0x0 if `addr` does not implement this interface function getInterfaceImplementer(address _addr, bytes32 iHash) constant public returns (address) { address addr = _addr == 0 ? msg.sender : _addr; if (isERC165Interface(iHash)) { bytes4 i165Hash = bytes4(iHash); return erc165InterfaceSupported(addr, i165Hash) ? addr : 0; } return interfaces[addr][iHash]; } /// @notice Sets the contract that will handle a specific interface; only /// a `manager` defined for that address can set it. /// ( Each address is the manager for itself until a new manager is defined) /// @param _addr Address that you want to define the interface for /// (if _addr == 0 them `msg.sender` is assumed) /// @param iHash SHA3 of the name of the interface as a string /// For example `web3.utils.sha3('Ierc777')` for the Ierc777 function setInterfaceImplementer(address _addr, bytes32 iHash, address implementer) public { address addr = _addr == 0 ? msg.sender : _addr; require(getManager(addr) == msg.sender); require(!isERC165Interface(iHash)); if ((implementer != 0) && (implementer!=msg.sender)) { require(ERC820ImplementerInterface(implementer).canImplementInterfaceForAddress(addr, iHash) == ERC820_ACCEPT_MAGIC); } interfaces[addr][iHash] = implementer; InterfaceImplementerSet(addr, iHash, implementer); } /// ERC165 Specific function isERC165Interface(bytes32 iHash) internal pure returns (bool) { return iHash & 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0; } function erc165InterfaceSupported(address _contract, bytes4 _interfaceId) constant public returns (bool) { if (!erc165Cache[_contract][_interfaceId]) { erc165UpdateCache(_contract, _interfaceId); } return interfaces[_contract][_interfaceId] != 0; } function erc165UpdateCache(address _contract, bytes4 _interfaceId) public { interfaces[_contract][_interfaceId] = erc165InterfaceSupported_NoCache(_contract, _interfaceId) ? _contract : 0; erc165Cache[_contract][_interfaceId] = true; } function erc165InterfaceSupported_NoCache(address _contract, bytes4 _interfaceId) public constant returns (bool) { uint256 success; uint256 result; (success, result) = noThrowCall(_contract, ERC165ID); if ((success==0)||(result==0)) { return false; } (success, result) = noThrowCall(_contract, InvalidID); if ((success==0)||(result!=0)) { return false; } (success, result) = noThrowCall(_contract, _interfaceId); if ((success==1)&&(result==1)) { return true; } return false; } function noThrowCall(address _contract, bytes4 _interfaceId) constant internal returns (uint256 success, uint256 result) { bytes4 erc165ID = ERC165ID; assembly { let x := mload(0x40) // Find empty storage location using "free memory pointer" mstore(x, erc165ID) // Place signature at begining of empty storage mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature success := staticcall( 30000, // 30k gas _contract, // To addr x, // Inputs are stored at location x 0x08, // Inputs are 8 bytes long x, // Store output over input (saves space) 0x20) // Outputs are 32 bytes long result := mload(x) // Load the result } } }
Sets the contract that will handle a specific interface; only a `manager` defined for that address can set it. ( Each address is the manager for itself until a new manager is defined) _addr Address that you want to define the interface for (if _addr == 0 them `msg.sender` is assumed) iHash SHA3 of the name of the interface as a string For example `web3.utils.sha3('Ierc777')` for the Ierc777
function setInterfaceImplementer(address _addr, bytes32 iHash, address implementer) public { address addr = _addr == 0 ? msg.sender : _addr; require(getManager(addr) == msg.sender); require(!isERC165Interface(iHash)); if ((implementer != 0) && (implementer!=msg.sender)) { require(ERC820ImplementerInterface(implementer).canImplementInterfaceForAddress(addr, iHash) == ERC820_ACCEPT_MAGIC); } interfaces[addr][iHash] = implementer; InterfaceImplementerSet(addr, iHash, implementer); }
5,864,271
./full_match/80001/0x4A8F7b3f9DF6628F6C528E80a65AaC92093DeB37/sources/project_/contracts/Factory.sol
normally 2% to factory and x% to creator of collection
function createNewCollection( string memory _name, string memory _symbol, string memory _uri, uint256 royalty_ ) public returns (address) { address[] memory payees_ = new address[](2); uint256[] memory shares_ = new uint256[](2); uint256 totalRoyalty = (factoryShare) + (royalty_); payees_[0] = address(this); shares_[0] = factoryShare; payees_[1] = _msgSender(); shares_[1] = royalty_; StandardNFT nCollection = new StandardNFT( _name, _symbol, _msgSender(), totalRoyalty, 1000, payees_, shares_ ); counterCollections++; collections[counterCollections] = payable(address(nCollection)); emit CollectionCreated( address(nCollection), _msgSender(), _name, _symbol, _uri ); return address(nCollection); }
5,651,614
pragma solidity ^0.4.11; contract Owned { address public owner; function Owned() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function setOwner(address _newOwner) onlyOwner { owner = _newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function toUINT112(uint256 a) internal constant returns(uint112) { assert(uint112(a) == a); return uint112(a); } function toUINT120(uint256 a) internal constant returns(uint120) { assert(uint120(a) == a); return uint120(a); } function toUINT128(uint256 a) internal constant returns(uint128) { assert(uint128(a) == a); return uint128(a); } } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 contract Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens //uint256 public totalSupply; function totalSupply() constant returns (uint256 supply); /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success); /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success); /// @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) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /// VEN token, ERC20 compliant contract VEN is Token, Owned { using SafeMath for uint256; string public constant name = "VeChain Token"; //The Token's name uint8 public constant decimals = 18; //Number of decimals of the smallest unit string public constant symbol = "VEN"; //An identifier // packed to 256bit to save gas usage. struct Supplies { // uint128's max value is about 3e38. // it's enough to present amount of tokens uint128 total; uint128 rawTokens; } Supplies supplies; // Packed to 256bit to save gas usage. struct Account { // uint112's max value is about 5e33. // it's enough to present amount of tokens uint112 balance; // raw token can be transformed into balance with bonus uint112 rawTokens; // safe to store timestamp uint32 lastMintedTimestamp; } // Balances for each account mapping(address => Account) accounts; // Owner of account approves the transfer of an amount to another account mapping(address => mapping(address => uint256)) allowed; // bonus that can be shared by raw tokens uint256 bonusOffered; // Constructor function VEN() { } function totalSupply() constant returns (uint256 supply){ return supplies.total; } // Send back ether sent to me function () { revert(); } // If sealed, transfer is enabled and mint is disabled function isSealed() constant returns (bool) { return owner == 0; } function lastMintedTimestamp(address _owner) constant returns(uint32) { return accounts[_owner].lastMintedTimestamp; } // Claim bonus by raw tokens function claimBonus(address _owner) internal{ require(isSealed()); if (accounts[_owner].rawTokens != 0) { uint256 realBalance = balanceOf(_owner); uint256 bonus = realBalance .sub(accounts[_owner].balance) .sub(accounts[_owner].rawTokens); accounts[_owner].balance = realBalance.toUINT112(); accounts[_owner].rawTokens = 0; if(bonus > 0){ Transfer(this, _owner, bonus); } } } // What is the balance of a particular account? function balanceOf(address _owner) constant returns (uint256 balance) { if (accounts[_owner].rawTokens == 0) return accounts[_owner].balance; if (bonusOffered > 0) { uint256 bonus = bonusOffered .mul(accounts[_owner].rawTokens) .div(supplies.rawTokens); return bonus.add(accounts[_owner].balance) .add(accounts[_owner].rawTokens); } return uint256(accounts[_owner].balance) .add(accounts[_owner].rawTokens); } // Transfer the balance from owner's account to another account function transfer(address _to, uint256 _amount) returns (bool success) { require(isSealed()); // implicitly claim bonus for both sender and receiver claimBonus(msg.sender); claimBonus(_to); // according to VEN's total supply, never overflow here if (accounts[msg.sender].balance >= _amount && _amount > 0) { accounts[msg.sender].balance -= uint112(_amount); accounts[_to].balance = _amount.add(accounts[_to].balance).toUINT112(); Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount ) returns (bool success) { require(isSealed()); // implicitly claim bonus for both sender and receiver claimBonus(_from); claimBonus(_to); // according to VEN's total supply, never overflow here if (accounts[_from].balance >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0) { accounts[_from].balance -= uint112(_amount); allowed[_from][msg.sender] -= _amount; accounts[_to].balance = _amount.add(accounts[_to].balance).toUINT112(); Transfer(_from, _to, _amount); return true; } else { return false; } } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. //if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { revert(); } ApprovalReceiver(_spender).receiveApproval(msg.sender, _value, this, _extraData); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // Mint tokens and assign to some one function mint(address _owner, uint256 _amount, bool _isRaw, uint32 timestamp) onlyOwner{ if (_isRaw) { accounts[_owner].rawTokens = _amount.add(accounts[_owner].rawTokens).toUINT112(); supplies.rawTokens = _amount.add(supplies.rawTokens).toUINT128(); } else { accounts[_owner].balance = _amount.add(accounts[_owner].balance).toUINT112(); } accounts[_owner].lastMintedTimestamp = timestamp; supplies.total = _amount.add(supplies.total).toUINT128(); Transfer(0, _owner, _amount); } // Offer bonus to raw tokens holder function offerBonus(uint256 _bonus) onlyOwner { bonusOffered = bonusOffered.add(_bonus); supplies.total = _bonus.add(supplies.total).toUINT128(); Transfer(0, this, _bonus); } // Set owner to zero address, to disable mint, and enable token transfer function seal() onlyOwner { setOwner(0); } } contract ApprovalReceiver { function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData); } // Contract to sell and distribute VEN tokens contract VENSale is Owned{ /// chart of stage transition /// /// deploy initialize startTime endTime finalize /// | <-earlyStageLasts-> | | <- closedStageLasts -> | /// O-----------O---------------O---------------------O-------------O------------------------O------------> /// Created Initialized Early Normal Closed Finalized enum Stage { NotCreated, Created, Initialized, Early, Normal, Closed, Finalized } using SafeMath for uint256; uint256 public constant totalSupply = (10 ** 9) * (10 ** 18); // 1 billion VEN, decimals set to 18 uint256 constant privateSupply = totalSupply * 9 / 100; // 9% for private ICO uint256 constant commercialPlan = totalSupply * 23 / 100; // 23% for commercial plan uint256 constant reservedForTeam = totalSupply * 5 / 100; // 5% for team uint256 constant reservedForOperations = totalSupply * 22 / 100; // 22 for operations // 59% uint256 public constant nonPublicSupply = privateSupply + commercialPlan + reservedForTeam + reservedForOperations; // 41% uint256 public constant publicSupply = totalSupply - nonPublicSupply; uint256 public constant officialLimit = 64371825 * (10 ** 18); uint256 public constant channelsLimit = publicSupply - officialLimit; // packed to 256bit struct SoldOut { uint16 placeholder; // placeholder to make struct pre-alloced // amount of tokens officially sold out. // max value of 120bit is about 1e36, it's enough for token amount uint120 official; uint120 channels; // amount of tokens sold out via channels } SoldOut soldOut; uint256 constant venPerEth = 3500; // normal exchange rate uint256 constant venPerEthEarlyStage = venPerEth + venPerEth * 15 / 100; // early stage has 15% reward uint constant minBuyInterval = 30 minutes; // each account can buy once in 30 minutes uint constant maxBuyEthAmount = 30 ether; VEN ven; // VEN token contract follows ERC20 standard address ethVault; // the account to keep received ether address venVault; // the account to keep non-public offered VEN tokens uint public constant startTime = 1503057600; // time to start sale uint public constant endTime = 1504180800; // tiem to close sale uint public constant earlyStageLasts = 3 days; // early bird stage lasts in seconds bool initialized; bool finalized; function VENSale() { soldOut.placeholder = 1; } /// @notice calculte exchange rate according to current stage /// @return exchange rate. zero if not in sale. function exchangeRate() constant returns (uint256){ if (stage() == Stage.Early) { return venPerEthEarlyStage; } if (stage() == Stage.Normal) { return venPerEth; } return 0; } /// @notice for test purpose function blockTime() constant returns (uint32) { return uint32(block.timestamp); } /// @notice estimate stage /// @return current stage function stage() constant returns (Stage) { if (finalized) { return Stage.Finalized; } if (!initialized) { // deployed but not initialized return Stage.Created; } if (blockTime() < startTime) { // not started yet return Stage.Initialized; } if (uint256(soldOut.official).add(soldOut.channels) >= publicSupply) { // all sold out return Stage.Closed; } if (blockTime() < endTime) { // in sale if (blockTime() < startTime.add(earlyStageLasts)) { // early bird stage return Stage.Early; } // normal stage return Stage.Normal; } // closed return Stage.Closed; } function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size > 0; } /// @notice entry to buy tokens function () payable { buy(); } /// @notice entry to buy tokens function buy() payable { // reject contract buyer to avoid breaking interval limit require(!isContract(msg.sender)); require(msg.value >= 0.01 ether); uint256 rate = exchangeRate(); // here don't need to check stage. rate is only valid when in sale require(rate > 0); // each account is allowed once in minBuyInterval require(blockTime() >= ven.lastMintedTimestamp(msg.sender) + minBuyInterval); uint256 requested; // and limited to maxBuyEthAmount if (msg.value > maxBuyEthAmount) { requested = maxBuyEthAmount.mul(rate); } else { requested = msg.value.mul(rate); } uint256 remained = officialLimit.sub(soldOut.official); if (requested > remained) { //exceed remained requested = remained; } uint256 ethCost = requested.div(rate); if (requested > 0) { ven.mint(msg.sender, requested, true, blockTime()); // transfer ETH to vault ethVault.transfer(ethCost); soldOut.official = requested.add(soldOut.official).toUINT120(); onSold(msg.sender, requested, ethCost); } uint256 toReturn = msg.value.sub(ethCost); if(toReturn > 0) { // return over payed ETH msg.sender.transfer(toReturn); } } /// @notice returns tokens sold officially function officialSold() constant returns (uint256) { return soldOut.official; } /// @notice returns tokens sold via channels function channelsSold() constant returns (uint256) { return soldOut.channels; } /// @notice manually offer tokens to channel function offerToChannel(address _channelAccount, uint256 _venAmount) onlyOwner { Stage stg = stage(); // since the settlement may be delayed, so it's allowed in closed stage require(stg == Stage.Early || stg == Stage.Normal || stg == Stage.Closed); soldOut.channels = _venAmount.add(soldOut.channels).toUINT120(); //should not exceed limit require(soldOut.channels <= channelsLimit); ven.mint( _channelAccount, _venAmount, true, // unsold tokens can be claimed by channels portion blockTime() ); onSold(_channelAccount, _venAmount, 0); } /// @notice initialize to prepare for sale /// @param _ven The address VEN token contract following ERC20 standard /// @param _ethVault The place to store received ETH /// @param _venVault The place to store non-publicly supplied VEN tokens function initialize( VEN _ven, address _ethVault, address _venVault) onlyOwner { require(stage() == Stage.Created); // ownership of token contract should already be this require(_ven.owner() == address(this)); require(address(_ethVault) != 0); require(address(_venVault) != 0); ven = _ven; ethVault = _ethVault; venVault = _venVault; ven.mint( venVault, reservedForTeam.add(reservedForOperations), false, // team and operations reserved portion can't share unsold tokens blockTime() ); ven.mint( venVault, privateSupply.add(commercialPlan), true, // private ICO and commercial plan can share unsold tokens blockTime() ); initialized = true; onInitialized(); } /// @notice finalize function finalize() onlyOwner { // only after closed stage require(stage() == Stage.Closed); uint256 unsold = publicSupply.sub(soldOut.official).sub(soldOut.channels); if (unsold > 0) { // unsold VEN as bonus ven.offerBonus(unsold); } ven.seal(); finalized = true; onFinalized(); } event onInitialized(); event onFinalized(); event onSold(address indexed buyer, uint256 venAmount, uint256 ethCost); }
manually offer tokens to channel since the settlement may be delayed, so it's allowed in closed stageshould not exceed limit
function offerToChannel(address _channelAccount, uint256 _venAmount) onlyOwner { Stage stg = stage(); require(stg == Stage.Early || stg == Stage.Normal || stg == Stage.Closed); soldOut.channels = _venAmount.add(soldOut.channels).toUINT120(); require(soldOut.channels <= channelsLimit); ven.mint( _channelAccount, _venAmount, blockTime() ); onSold(_channelAccount, _venAmount, 0); }
7,214,580
pragma solidity ^0.6.12; //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // // LiquidityZAP - BalancerZAP // Copyright (c) 2020 deepyr.com // // BalancerZAP takes ETH and converts to a Balancer Pool Tokens (BTP). // // 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 // // 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 <https://github.com/apguerrera/LiquidityZAP/>. // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // Authors: // * Adrian Guerrera / Deepyr Pty Ltd // // --------------------------------------------------------------------- // SPDX-License-Identifier: GPL-3.0-or-later // --------------------------------------------------------------------- import "../interfaces/IWETH9.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IBPool.sol"; import "../interfaces/IUniswapV2Pair.sol"; import "./Utils/SafeMath.sol"; import "./Utils/UniswapV2Library.sol"; contract BalancerZAP { using SafeMath for uint256; address public _token; address public _balancerPool; address public _tokenWETHPair; IWETH public _WETH; bool private initialized; function initBalancerZAP(address token, address balancerPool, address WETH, address tokenWethPair) public { require(!initialized); _token = token; _balancerPool = balancerPool; require(IERC20(_token).approve(balancerPool, uint(-1))); _WETH = IWETH(WETH); _tokenWETHPair = tokenWethPair; initialized = true; } fallback() external payable { if(msg.sender != address(_WETH)){ addLiquidityETHOnly(msg.sender); } } /** * @dev Converts ETH to Balancer Pool Tokens (BPT) */ function addLiquidityETHOnly(address payable to) public payable { require(to != address(0), "Invalid address"); uint256 buyAmount = msg.value; require(buyAmount > 0, "Insufficient ETH amount"); _WETH.deposit{value : msg.value}(); (uint256 reserveWeth, uint256 reserveTokens) = getPairReserves(); uint256 outTokens = UniswapV2Library.getAmountOut(buyAmount, reserveWeth, reserveTokens); _WETH.transfer(_tokenWETHPair, buyAmount); (address token0, address token1) = UniswapV2Library.sortTokens(address(_WETH), _token); IUniswapV2Pair(_tokenWETHPair).swap(_token == token0 ? outTokens : 0, _token == token1 ? outTokens : 0, address(this), ""); _addLiquidity(outTokens, to); } /** * @dev User needs to have approved this contract to transferFrom tokens */ function addLiquidityTokenOnly(uint256 tokenAmount, address to) public { require(to != address(0), "Invalid address"); require(tokenAmount > 0, "Insufficient token amount"); require(IERC20(_token).transferFrom(msg.sender, address(this), tokenAmount)); _addLiquidity(tokenAmount, to); } function _addLiquidity(uint256 tokenAmount, address to) internal { //mint BPTs uint256 bptTokens = IBPool(_balancerPool).joinswapExternAmountIn( _token, tokenAmount, 0); require(bptTokens > 0, "Insufficient BPT amount"); //transfer tokens to user require(IBPool(_balancerPool).transfer(to, bptTokens)); } function getPairReserves() internal view returns (uint256 wethReserves, uint256 tokenReserves) { (address token0,) = UniswapV2Library.sortTokens(address(_WETH), _token); (uint256 reserve0, uint reserve1,) = IUniswapV2Pair(_tokenWETHPair).getReserves(); (wethReserves, tokenReserves) = token0 == _token ? (reserve1, reserve0) : (reserve0, reserve1); } }
Converts ETH to Balancer Pool Tokens (BPT)/
function addLiquidityETHOnly(address payable to) public payable { require(to != address(0), "Invalid address"); uint256 buyAmount = msg.value; require(buyAmount > 0, "Insufficient ETH amount"); (uint256 reserveWeth, uint256 reserveTokens) = getPairReserves(); uint256 outTokens = UniswapV2Library.getAmountOut(buyAmount, reserveWeth, reserveTokens); _WETH.transfer(_tokenWETHPair, buyAmount); (address token0, address token1) = UniswapV2Library.sortTokens(address(_WETH), _token); IUniswapV2Pair(_tokenWETHPair).swap(_token == token0 ? outTokens : 0, _token == token1 ? outTokens : 0, address(this), ""); _addLiquidity(outTokens, to); }
2,474,093
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import "./IUserRegistry.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract BrightIdUserRegistry is Ownable, IUserRegistry { string private constant ERROR_NEWER_VERIFICATION = "NEWER VERIFICATION REGISTERED BEFORE"; string private constant ERROR_NOT_AUTHORIZED = "NOT AUTHORIZED"; string private constant ERROR_INVALID_VERIFIER = "INVALID VERIFIER"; string private constant ERROR_INVALID_CONTEXT = "INVALID CONTEXT"; bytes32 public context; address public verifier; struct Verification { uint256 time; bool isVerified; } mapping(address => Verification) public verifications; event SetBrightIdSettings(bytes32 context, address verifier); event Sponsor(address indexed addr); /** * @param _context BrightID context used for verifying users * @param _verifier BrightID verifier address that signs BrightID verifications */ constructor(bytes32 _context, address _verifier) public { // ecrecover returns zero on error require(_verifier != address(0), ERROR_INVALID_VERIFIER); context = _context; verifier = _verifier; } /** * @notice Sponsor a BrightID user by context id * @param addr BrightID context id */ function sponsor(address addr) public { emit Sponsor(addr); } /** * @notice Set BrightID settings * @param _context BrightID context used for verifying users * @param _verifier BrightID verifier address that signs BrightID verifications */ function setSettings(bytes32 _context, address _verifier) external onlyOwner { // ecrecover returns zero on error require(_verifier != address(0), ERROR_INVALID_VERIFIER); context = _context; verifier = _verifier; emit SetBrightIdSettings(_context, _verifier); } /** * @notice Check a user is verified or not * @param _user BrightID context id used for verifying users */ function isVerifiedUser(address _user) external view override returns (bool) { return verifications[_user].isVerified; } /** * @notice Register a user by BrightID verification * @param _context The context used in the users verification * @param _addrs The history of addresses used by this user in this context * @param _timestamp The BrightID node's verification timestamp * @param _v Component of signature * @param _r Component of signature * @param _s Component of signature */ function register( bytes32 _context, address[] calldata _addrs, uint256 _timestamp, uint8 _v, bytes32 _r, bytes32 _s ) external { require(context == _context, ERROR_INVALID_CONTEXT); require( verifications[_addrs[0]].time < _timestamp, ERROR_NEWER_VERIFICATION ); bytes32 message = keccak256( abi.encodePacked(_context, _addrs, _timestamp) ); address signer = ecrecover(message, _v, _r, _s); require(verifier == signer, ERROR_NOT_AUTHORIZED); verifications[_addrs[0]].time = _timestamp; verifications[_addrs[0]].isVerified = true; for (uint256 i = 1; i < _addrs.length; i++) { // update time of all previous context ids to be sure no one can use old verifications again verifications[_addrs[i]].time = _timestamp; // set old verifications unverified verifications[_addrs[i]].isVerified = false; } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; /** * @dev Interface of the registry of verified users. */ interface IUserRegistry { function isVerifiedUser(address _user) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
Check a user is verified or not _user BrightID context id used for verifying users/
function isVerifiedUser(address _user) external view override returns (bool) { return verifications[_user].isVerified; }
6,046,317
pragma ton-solidity ^0.39.0; pragma AbiHeader pubkey; pragma AbiHeader expire; pragma AbiHeader time; import '../../ton-eth-bridge-token-contracts/free-ton/contracts/interfaces/IRootTokenContract.sol'; import '../../ton-eth-bridge-token-contracts/free-ton/contracts/interfaces/ITokensReceivedCallback.sol'; import '../../ton-eth-bridge-token-contracts/free-ton/contracts/interfaces/ITONTokenWallet.sol'; import "../../ton-eth-bridge-token-contracts/free-ton/contracts/interfaces/IBurnTokensCallback.sol"; import "../../ton-eth-bridge-token-contracts/free-ton/contracts/interfaces/IBurnableByOwnerTokenWallet.sol"; import './interfaces/swapPair/ISwapPairContract.sol'; import './interfaces/swapPair/ISwapPairInformation.sol'; import './interfaces/swapPair/IUpgradeSwapPairCode.sol'; import './interfaces/rootSwapPair/IRootContractCallback.sol'; import './interfaces/helpers/ITIP3TokenDeployer.sol'; import './libraries/swapPair/SwapPairErrors.sol'; import './libraries/swapPair/SwapPairConstants.sol'; // TODO: рефакторинг: добавить комментарии чтобы было понятно что за параметры contract SwapPairContract is ITokensReceivedCallback, ISwapPairInformation, IUpgradeSwapPairCode, ISwapPairContract { address static token1; address static token2; uint static swapPairID; uint32 swapPairCodeVersion; address swapPairRootContract; address tip3Deployer; address lpTokenRootAddress; address lpTokenWalletAddress; bytes LPTokenName; uint128 constant feeNominator = 997; uint128 constant feeDenominator = 1000; uint256 liquidityTokensMinted = 0; mapping(address => uint8) tokenPositions; //Deployed token wallets addresses mapping(uint8 => address) tokenWallets; //Liquidity providers info for security reasons mapping(uint256 => LPProvidingInfo) lpInputTokensInfo; //Liquidity Pools mapping(uint8 => uint128) private lps; //Pair creation timestamp uint256 creationTimestamp; //Initialization status. // 0 - new <- not initialized // 1 - one wallet created <- not initialized // 2 - both wallets for TIP-3 created <- not initialized // 3 - deployed LP token contract <- not initialized // 4 - deployed LP token wallet <- initialized uint private initializedStatus = 0; // Tokens positions uint8 constant T1 = 0; uint8 constant T2 = 1; // Token info uint8 tokenInfoCount; IRootTokenContract.IRootTokenContractDetails T1Info; IRootTokenContract.IRootTokenContractDetails T2Info; uint8 constant wrongPayloadFormatMessage = 0; //Received payload is invalid or has wrong format."; uint8 constant unknownOperationIdorWrongPayload = 1; //Received payload contains unknow Operation ID or is malformed."; uint8 constant sumIsTooLowForSwap = 2; //Provided token amount is not enough for swap."; uint8 constant noLiquidityProvidedMessage = 3; //No liquidity provided yet. Swaps are forbidden."; uint8 constant sumIsTooLowForLPTokenWithdraw = 4; //Provided LP token amount is not enough to withdraw liquidity."; //============Contract initialization functions============ constructor(address rootContract, address tip3Deployer_, uint32 swapPairCodeVersion_) public { tvm.accept(); creationTimestamp = now; swapPairRootContract = rootContract; tip3Deployer = tip3Deployer_; swapPairCodeVersion = swapPairCodeVersion_; tokenPositions[token1] = T1; tokenPositions[token2] = T2; lps[T1] = 0; lps[T2] = 0; //Deploy tokens wallets _deployWallet(token1); _deployWallet(token2); // Get information about tokens _getTIP3Details(token1); _getTIP3Details(token2); } /** * Deploy wallet for swap pair. * @dev You cannot get address from this function so _getWalletAddress is used to get address of wallet * @param tokenRootAddress address of tip-3 root contract */ function _deployWallet(address tokenRootAddress) private view { tvm.accept(); IRootTokenContract(tokenRootAddress).deployEmptyWallet{ value: SwapPairConstants.walletDeployMessageValue }(SwapPairConstants.walletInitialBalanceAmount, tvm.pubkey(), address(this), address(this)); _getWalletAddress(tokenRootAddress); } /** * Get address of future wallet address deployed using _deployWallet * @dev getWalletAddressCallback is used to get wallet address * @param token address of tip-3 root contract */ function _getWalletAddress(address token) private view { tvm.accept(); IRootTokenContract(token).getWalletAddress{ value: SwapPairConstants.sendToRootToken, callback: this.getWalletAddressCallback }(tvm.pubkey(), address(this)); } /** * Deployed wallet address callback * @dev can be called only by token root contracts * @param walletAddress address of deployed token wallet */ function getWalletAddressCallback(address walletAddress) external onlyTokenRoot { require(initializedStatus < SwapPairConstants.contractFullyInitialized, SwapPairErrors.CONTRACT_ALREADY_INITIALIZED); tvm.accept(); if (msg.sender == token1) { tokenWallets[T1] = walletAddress; initializedStatus++; } if (msg.sender == token2) { tokenWallets[T2] = walletAddress; initializedStatus++; } if (msg.sender == lpTokenRootAddress) { lpTokenWalletAddress = walletAddress; initializedStatus++; } /* For all deployed wallets we set callback address equal to swap pair address */ _setWalletsCallbackAddress(walletAddress); /* If all wallets were deployed and LP token root is deployed - swap pair is ready We call swap pair root callback to update stored information */ if (initializedStatus == SwapPairConstants.contractFullyInitialized) { _swapPairInitializedCall(); } } /** * Set callback address for wallets * @param walletAddress Address of TIP-3 wallet */ function _setWalletsCallbackAddress(address walletAddress) private pure { tvm.accept(); ITONTokenWallet(walletAddress).setReceiveCallback{ value: 200 milliton }( address(this), false ); } /** * Get tip-3 details from root tip-3 contract * @dev function _receiveTIP3Details is used for callback * @param tokenRootAddress address of tip-3 root contract */ function _getTIP3Details(address tokenRootAddress) private pure { tvm.accept(); IRootTokenContract(tokenRootAddress).getDetails{ value: SwapPairConstants.sendToRootToken, bounce: true, callback: this._receiveTIP3Details }(); } /** * Receive requested TIP-3 details from root contract * @dev this function can be called only by know TIP-3 token root contracts (token1, token2, LP token) * @param rtcd Details about TIP-3 */ function _receiveTIP3Details(IRootTokenContract.IRootTokenContractDetails rtcd) external onlyTokenRoot { tvm.accept(); if (msg.sender == token1) { T1Info = rtcd; tokenInfoCount++; } else { T2Info = rtcd; tokenInfoCount++; } /* After we receive information about both tokens we can proceed to LP token creation This is mainly done for nice name of future LP token such as "T1 <-> T2" */ if (tokenInfoCount == 2) { this._prepareDataForTIP3Deploy(); } } /** * Build name of future TIP-3 LP token * @dev This function can be called only by contract itself */ function _prepareDataForTIP3Deploy() external view onlySelf { tvm.accept(); string res = string(T1Info.symbol); res.append("<->"); res.append(string(T2Info.symbol)); res.append(" LP"); this._deployTIP3LpToken(bytes(res), bytes(res)); } /** * Deploy TIP-3 LP token with created params * @dev This function can be called only by contract itself * @param name Name of future TIP-3 token, equal to symbol * @param symbol Symbol of future TIP-3 token */ function _deployTIP3LpToken(bytes name, bytes symbol) external onlySelf { tvm.accept(); LPTokenName = symbol; /* Another contract is required to deploy TIP-3 token */ ITIP3TokenDeployer(tip3Deployer).deployTIP3Token{ value: SwapPairConstants.tip3SendDeployGrams, bounce: true, callback: this._deployTIP3LpTokenCallback }(name, symbol, SwapPairConstants.tip3LpDecimals, 0, address(this), SwapPairConstants.tip3SendDeployGrams/2); } /** * Receive address of LP token root contract. Callback for _deployTIP3Lptoken * @dev This function can be called only by TIP-3 deployer contract * @param tip3RootContract Address of deployed LP token root contract */ function _deployTIP3LpTokenCallback(address tip3RootContract) external onlyTIP3Deployer { tvm.accept(); lpTokenRootAddress = tip3RootContract; initializedStatus++; _deployWallet(tip3RootContract); } //============TON balance function============ receive() external { // Thanks! } //============Get functions============ /** * Get general information about swap pair */ function getPairInfo() override external responsible view returns (SwapPairInfo info) { return _constructSwapPairInfo(); } /** * Get result of swap if swap would be performed right now * @param swappableTokenRoot Root of tip-3 token used for swap * @param swappableTokenAmount Amount of token for swap */ function getExchangeRate(address swappableTokenRoot, uint128 swappableTokenAmount) override external responsible view initialized tokenExistsInPair(swappableTokenRoot) returns (SwapInfo) { if (swappableTokenAmount <= 0) return SwapInfo(0, 0, 0); _SwapInfoInternal si = _calculateSwapInfo(swappableTokenRoot, swappableTokenAmount); return SwapInfo(swappableTokenAmount, si.targetTokenAmount, si.fee); } /** * Get current pool states */ function getCurrentExchangeRate() override external responsible view returns (LiquidityPoolsInfo lpi) { return LiquidityPoolsInfo(address(this), lps[T1], lps[T2], liquidityTokensMinted); } //============Functions for offchain execution============ /** * Get information for liquidity providing - how much of first and second tokens will be added to * liquidity pools * @dev Requires a lot of gas, recommended to run with runLocal * @notice This is just imitation of LP mechanism for offchain execution * @param maxFirstTokenAmount amount of first token provided to LP * @param maxSecondTokenAmount amount of second token provided to LP */ function getProvidingLiquidityInfo(uint128 maxFirstTokenAmount, uint128 maxSecondTokenAmount) override external view initialized returns (uint128 providedFirstTokenAmount, uint128 providedSecondTokenAmount) { (providedFirstTokenAmount, providedSecondTokenAmount,) = _calculateProvidingLiquidityInfo(maxFirstTokenAmount, maxSecondTokenAmount); } /** * Get information how much tokens you will receive if you burn given amount of LP tokens * @dev Requires a lot of gas, recommended to run with runLocal * @notice This is just imitation of LP mechanism for offchain execution * @param liquidityTokensAmount Amount of liquidity tokens to be burnt */ function getWithdrawingLiquidityInfo(uint256 liquidityTokensAmount) override external view initialized returns (uint128 withdrawedFirstTokenAmount, uint128 withdrawedSecondTokenAmount) { (withdrawedFirstTokenAmount, withdrawedSecondTokenAmount,) = _calculateWithdrawingLiquidityInfo(liquidityTokensAmount); } /** * Calculate amount of another token you need to provide to LP * @dev Requires a lot of gas, recommended to run with runLocal * @notice This is just imitation of LP mechanism for offchain execution * @param providingTokenRoot Address of provided tip-3 token * @param providingTokenAmount Amount of provided tip-3 tokens */ function getAnotherTokenProvidingAmount(address providingTokenRoot, uint128 providingTokenAmount) override external view initialized returns(uint128 anotherTokenAmount) { if (!_checkIsLiquidityProvided()) return 0; uint8 fromK = _getTokenPosition(providingTokenRoot); uint8 toK = fromK == T1 ? T2 : T1; return providingTokenAmount != 0 ? math.muldivc(providingTokenAmount, lps[toK], lps[fromK]) : 0; } //============LP Functions============ /** * Calculate LP providing information -> amount of first and second token provided and amount of LP token to mint * @notice This function doesn't change LP volumes. It only calculates * @param maxFirstTokenAmount Amount of first token user provided * @param maxSecondTokenAmount Amount of second token user provided */ function _calculateProvidingLiquidityInfo(uint128 maxFirstTokenAmount, uint128 maxSecondTokenAmount) private view returns (uint128 provided1, uint128 provided2, uint256 _minted) { // TODO: Антон: подумать что можно сделать с тем, что мы минтим uint256 /* If no liquidity provided than you set the initial exchange rate */ if ( !_checkIsLiquidityProvided() ) { provided1 = maxFirstTokenAmount; provided2 = maxSecondTokenAmount; _minted = uint256(provided1) * uint256(provided2); } else { uint128 maxToProvide1 = maxSecondTokenAmount != 0 ? math.muldiv(maxSecondTokenAmount, lps[T1], lps[T2]) : 0; uint128 maxToProvide2 = maxFirstTokenAmount != 0 ? math.muldiv(maxFirstTokenAmount, lps[T2], lps[T1]) : 0; if (maxToProvide1 <= maxFirstTokenAmount ) { provided1 = maxToProvide1; provided2 = maxSecondTokenAmount; _minted = math.muldiv(uint256(provided2), liquidityTokensMinted, uint256(lps[T2]) ); } else { provided1 = maxFirstTokenAmount; provided2 = maxToProvide2; _minted = math.muldiv(uint256(provided1), liquidityTokensMinted, uint256(lps[T1]) ); } } } /** * Calculate amount of tokens received if given amount of LP tokens is burnt * @notice This function doesn't change LP volumes. It only calculates * @param liquidityTokensAmount Amount of LP tokens burnt */ function _calculateWithdrawingLiquidityInfo(uint256 liquidityTokensAmount) private view returns (uint128 withdrawed1, uint128 withdrawed2, uint256 _burned) { if (liquidityTokensMinted <= 0 || liquidityTokensAmount <= 0) return (0, 0, 0); withdrawed1 = uint128(math.muldiv(uint256(lps[T1]), liquidityTokensAmount, liquidityTokensMinted)); withdrawed2 = uint128(math.muldiv(uint256(lps[T2]), liquidityTokensAmount, liquidityTokensMinted)); _burned = liquidityTokensAmount; } /** * Calculate LP providing information of only one token was provided * @notice This function doesn't change LP volumes. It only calculates * @param tokenRoot Root contract address of provided token * @param tokenAmount Amount of provided token */ function _calculateOneTokenProvidingAmount(address tokenRoot, uint128 tokenAmount) private view returns(uint128) { uint8 fromK = _getTokenPosition(tokenRoot); uint256 f = uint256(lps[fromK]); uint128 k = feeNominator+feeDenominator; uint256 b = f*k; uint256 v = f * _sqrt( k*k + math.muldiv(4*feeDenominator*feeNominator, tokenAmount, f)); return uint128((v-b)/(feeNominator+feeNominator)); } /** * Calculate swap results * @notice This function doesn't change LP volumes. It only calculates swap results * @param swappableTokenRoot Root contract address of token used for swap * @param swappableTokenAmount Amount of token used for swap */ function _calculateSwapInfo(address swappableTokenRoot, uint128 swappableTokenAmount) private view tokenExistsInPair(swappableTokenRoot) returns (_SwapInfoInternal swapInfo) { uint8 fromK = _getTokenPosition(swappableTokenRoot); uint8 toK = fromK == T1 ? T2 : T1; uint128 fee = swappableTokenAmount - math.muldivc(swappableTokenAmount, feeNominator, feeDenominator); uint128 newFromPool = lps[fromK] + swappableTokenAmount; uint128 newToPool = uint128( math.divc(uint256(lps[T1]) * uint256(lps[T2]), newFromPool - fee) ); uint128 targetTokenAmount = lps[toK] - newToPool; _SwapInfoInternal result = _SwapInfoInternal(fromK, toK, newFromPool, newToPool, targetTokenAmount, fee); return result; } /** * Wrapper for _calculateSwapInfo that changes the state of the contract * @notice This function changes LP volumes * @param swappableTokenRoot Root contract address of token used for swap * @param swappableTokenAmount Amount of tokens used for swap */ function _swap(address swappableTokenRoot, uint128 swappableTokenAmount) private returns (SwapInfo) { _SwapInfoInternal _si = _calculateSwapInfo(swappableTokenRoot, swappableTokenAmount); if (!notZeroLiquidity(swappableTokenAmount, _si.targetTokenAmount)) { return SwapInfo(0, 0, 0); } lps[_si.fromKey] = _si.newFromPool; lps[_si.toKey] = _si.newToPool; return SwapInfo(swappableTokenAmount, _si.targetTokenAmount, _si.fee); } // TODO: Антон: проверка провайдинга ликвидности по одному токену /** * Internal function used for providing liquidity using one token * @notice To provide liquidity using one token it's required to swap part of provided token amount * @param tokenRoot Root contract address of token used for liquidity providing * @param tokenAmount Amount of tokens used for liquidity providing * @param senderPubkey Public key of user that provides liquidity * @param senderAddress Address of TON wallet of user * @param lpWallet Address of user's LP wallet */ function _provideLiquidityOneToken(address tokenRoot, uint128 tokenAmount, uint256 senderPubkey, address senderAddress, address lpWallet) private tokenExistsInPair(tokenRoot) returns (uint128 provided1, uint128 provided2, uint256 toMint, uint128 inputTokenRemainder) { uint128 amount = _calculateOneTokenProvidingAmount(tokenRoot, tokenAmount); if (amount <= 0) return (0, 0, 0, 0); SwapInfo si = _swap(tokenRoot, amount); uint128 amount1 = 0; uint128 amount2 = 0; bool isT1 = (tokenRoot == token1); if ( isT1 ) { amount1 = tokenAmount - si.swappableTokenAmount; amount2 = si.targetTokenAmount; } else { amount1 = si.targetTokenAmount; amount2 = tokenAmount - si.swappableTokenAmount; } (provided1, provided2, toMint) = _provideLiquidity(amount1, amount2, senderPubkey, senderAddress, lpWallet); inputTokenRemainder = isT1 ? (amount1 - provided1) : (amount2 - provided2); } /** * Internal function for liquidity providing using both tokens * @notice This function changes LP volumes * @param amount1 Amount of first token provided by user * @param amount2 Amount of second token provided by user * @param senderPubkey Public key of user that provides liquidity * @param senderAddress Address of TON wallet of user * @param lpWallet Address of user's LP wallet */ function _provideLiquidity(uint128 amount1, uint128 amount2, uint256 senderPubkey, address senderAddress, address lpWallet) private returns (uint128 provided1, uint128 provided2, uint256 toMint) { (provided1, provided2, toMint) = _calculateProvidingLiquidityInfo(amount1, amount2); lps[T1] += provided1; lps[T2] += provided2; liquidityTokensMinted += toMint; /* If user doesn't have wallet for LP tokens - we create one for user */ if (lpWallet.value == 0) { IRootTokenContract(lpTokenRootAddress).deployWallet{ value: msg.value/2, flag: 0 }(uint128(toMint), msg.value/4, senderPubkey, senderAddress, senderAddress); } else { IRootTokenContract(lpTokenRootAddress).mint(uint128(toMint), lpWallet); } } /** * Function to return tokens not used for lqiuidity providing * @param providedByUser Amount of tokens transferred by user * @param providedAmount Amount of tokens provided to LP * @param tokenWallet Address of swap pair wallet that received tokens * @param senderTokenWallet Address of user's token wallet * @param original_gas_to Where to return remaining gas * @param payloadTB Payload attached to message */ function _tryToReturnProvidingTokens( uint128 providedByUser, uint128 providedAmount, address tokenWallet, address senderTokenWallet, address original_gas_to, TvmBuilder payloadTB ) private pure { uint128 amount = providedByUser - providedAmount; if (amount > 0) { _sendTokens(tokenWallet, senderTokenWallet, amount, original_gas_to, false, payloadTB.toCell()); } } //============Withdraw LP tokens functionality============ /** * Function to withdraw tokens from liquidity pool * @notice To interact with swap pair you need to send TIP-3 tokens with specific payload and TONs * @dev This function can be called only by contract itself * @param tokenAmount Amount of LP tokens burnt/transferred * @param lpwi Information used for token withdrawal. Contains root addresses and user's wallets * @param walletAddress Address of user's LP wallet * @param tokensBurnt If tokens were burnt or just transferred * @param send_gas_to Where to send remaining gas */ function _withdrawTokensFromLP( uint128 tokenAmount, LPWithdrawInfo lpwi, address walletAddress, bool tokensBurnt, address send_gas_to ) external onlySelf { require( _checkIsLiquidityProvided(), SwapPairErrors.NO_LIQUIDITY_PROVIDED ); (uint128 withdrawed1, uint128 withdrawed2, uint256 burned) = _calculateWithdrawingLiquidityInfo(tokenAmount); if (withdrawed1 != 0 && withdrawed2 != 0) { lps[T1] -= withdrawed1; lps[T2] -= withdrawed2; if (!tokensBurnt) { _burnTransferredLPTokens(tokenAmount); } liquidityTokensMinted -= tokenAmount; emit WithdrawLiquidity(burned, withdrawed1, withdrawed2); SwapPairContract(this)._transferTokensToWallets{ flag: 64, value: 0 }(lpwi, withdrawed1, withdrawed2, send_gas_to); } else { _fallbackWithdrawLP(walletAddress, tokenAmount, tokensBurnt); } } /** * Function to withdraw tokens from liquidity pool in one token * @notice To interact with swap pair you need to send TIP-3 tokens with specific payload and TONs * @dev This function can be called only by contract itself * @param tokenAmount Amount of LP tokens burnt/transferred * @param tokenRoot Address of desired TIP-3 token * @param tokenWallet Address of tip-3 wallet to transfer tokens to * @param lpWalletAddress Address of user's LP token wallet * @param tokensBurnt If tokens were burnt or just transferred * @param send_gas_to Where to send remaining gas */ function _withdrawOneTokenFromLP ( uint128 tokenAmount, address tokenRoot, address tokenWallet, address lpWalletAddress, bool tokensBurnt, address send_gas_to ) external onlySelf { // TODO: рефакторинг: общая часть с функцией _withdrawTokensFromLP, возможно стоит вынести в отдельный метод require( _checkIsLiquidityProvided(), SwapPairErrors.NO_LIQUIDITY_PROVIDED ); (uint128 withdrawed1, uint128 withdrawed2, uint256 burned) = _calculateWithdrawingLiquidityInfo(tokenAmount); if (withdrawed1 == 0 || withdrawed2 == 0) { _fallbackWithdrawLP(lpWalletAddress, tokenAmount, tokensBurnt); return; } lps[T1] -= withdrawed1; lps[T2] -= withdrawed2; if (!tokensBurnt) { _burnTransferredLPTokens(tokenAmount); } liquidityTokensMinted -= tokenAmount; emit WithdrawLiquidity(burned, withdrawed1, withdrawed2); bool isT1 = tokenRoot == token1; address swapableToken = isT1 ? token2 : token1; uint128 swapableAmount = isT1 ? withdrawed2 : withdrawed1; SwapInfo si = _swap(swapableToken, swapableAmount); uint128 resultAmount = si.targetTokenAmount + (isT1 ? withdrawed1 : withdrawed2); address w = tokenRoot == token1 ? tokenWallets[T1] : tokenWallets[T2]; TvmCell payload; _sendTokens(w, tokenWallet, resultAmount, send_gas_to, true, payload); } /** * Function to transfer multiple tokens to wallets * @dev This function can be called only by contract itself * @param lpwi Struct with information for token withdraw * @param t1Amount Amount of first token to transfer * @param t2Amount Amount of second token to transfer * @param send_gas_to Where to send remaining gas */ function _transferTokensToWallets( LPWithdrawInfo lpwi, uint128 t1Amount, uint128 t2Amount, address send_gas_to ) external view onlySelf { // TODO: рефакторинг: изменить названия // TODO: рефакторинг: переделать функцию bool t1ist1 = lpwi.tr1 == token1; // смотрим, не была ли перепутана последовательность адресов рут-контрактов address w1 = t1ist1 ? tokenWallets[0] : tokenWallets[1]; address w2 = t1ist1 ? tokenWallets[1] : tokenWallets[0]; uint128 t1a = t1ist1 ? t1Amount : t2Amount; uint128 t2a = t1ist1 ? t2Amount : t1Amount; TvmCell payload = _createWithdrawResultPayload(w1, t1a, w2, t2a); ITONTokenWallet(w1).transfer{value: msg.value/3}(lpwi.tw1, t1a, 0, send_gas_to, true, payload); _sendTokens(w2, lpwi.tw2, t2a, send_gas_to, true, payload); } /** * Fallback function if something went wrong during liquidity withdrawal * @param walletAddress Address of user's LP token wallet * @param tokensAmount Amount of LP tokens that were transferred/burnt * @param mintRequired Were tokens burnt or just transferred */ function _fallbackWithdrawLP( address walletAddress, uint128 tokensAmount, bool mintRequired ) private view { if (mintRequired) { IRootTokenContract(lpTokenRootAddress).mint{ value: 0, flag: 64 }(tokensAmount, walletAddress); } else { TvmBuilder payload; payload.store(sumIsTooLowForLPTokenWithdraw); _sendTokens(lpTokenWalletAddress, walletAddress, tokensAmount, address(this), true, payload.toCell()); } } /** * Burn transferred LP tokens * @param tokenAmount Amount of LP tokens to burn */ function _burnTransferredLPTokens(uint128 tokenAmount) private view { TvmCell payload; IBurnableByOwnerTokenWallet(lpTokenWalletAddress).burnByOwner{ value: msg.value/4 }(tokenAmount, 0, address(this), address(this), payload); } //============Callbacks============ /** * Function that is called when TIP-3 wallet receives tokens * @dev This function can only be called by swap pair's TIP-3 wallets * @notice This function is just a router for parsing initial payload and guessing which function to call * @param token_wallet Address of wallet that received tokens * @param token_root Root contract address of wallet * @param amount Amount of tokens transferred * @param sender_public_key Sender's public key * @param sender_address Sender's TON wallet address * @param sender_wallet Sender's token wallet address * @param original_gas_to Original gas_back address * @param updated_balance Balance of wallet after transfer * @param payload Payload attached to message */ function tokensReceivedCallback( address token_wallet, address token_root, uint128 amount, uint256 sender_public_key, address sender_address, address sender_wallet, address original_gas_to, uint128 updated_balance, TvmCell payload ) override public onlyOwnWallet { TvmSlice tmp = payload.toSlice(); (UnifiedOperation uo) = tmp.decode(UnifiedOperation); TvmBuilder failTB; failTB.store(unknownOperationIdorWrongPayload); // TODO: рефакторинг: разрулить if/else во что-то более нормальное if (msg.sender != lpTokenWalletAddress) { if (uo.operationId == SwapPairConstants.SwapPairOperation) { SwapPairContract(this)._externalSwap{ flag: 64, value: 0 }( uo.operationArgs, msg.sender, token_root, amount, sender_wallet, original_gas_to ); } else if (uo.operationId == SwapPairConstants.ProvideLiquidity) { SwapPairContract(this)._externalProvideLiquidity{ flag: 64, value: 0 }( uo.operationArgs, msg.sender, sender_public_key, amount, sender_wallet, sender_address, original_gas_to ); } else if (uo.operationId == SwapPairConstants.ProvideLiquidityOneToken) { SwapPairContract(this)._externalProvideLiquidityOneToken{ flag: 64, value: 0 }( uo.operationArgs, token_root, msg.sender, sender_public_key, amount, sender_wallet, sender_address, original_gas_to ); } else { _sendTokens(msg.sender, sender_wallet, amount, original_gas_to, true, failTB.toCell()); } } else { if (uo.operationId == SwapPairConstants.WithdrawLiquidity) { SwapPairContract(this)._externalWithdrawLiquidity{ flag: 64, value: 0 }( uo.operationArgs, amount, sender_wallet, original_gas_to, false ); } else if (uo.operationId == SwapPairConstants.WithdrawLiquidityOneToken) { SwapPairContract(this)._externalWithdrawLiquidityOneToken{ flag: 64, value: 0 }( uo.operationArgs, amount, sender_wallet, original_gas_to, false ); } else { _sendTokens(msg.sender, sender_wallet, amount, original_gas_to, true, failTB.toCell()); } } } /** * Function that is called when LP tokens are burnt * @dev This function can only be called by LP token root contract * @notice This function is just a router for parsing initial payload and guessing which function to call * @param tokensBurnt Amount of burnt tokens * @param payload Payload attached to burnt tokens * @param sender_public_key Public key of user that burnt tokens * @param sender_address Address of user's TON wallet * @param wallet_address Address of user's LP token wallet * @param send_gas_to Original gas_back address */ function burnCallback( uint128 tokensBurnt, TvmCell payload, uint256 sender_public_key, address sender_address, address wallet_address, address send_gas_to ) external view onlyLpTokenRoot { TvmSlice tmp = payload.toSlice(); (UnifiedOperation uo) = tmp.decode(UnifiedOperation); if (wallet_address == lpTokenWalletAddress) { return; } if (uo.operationId == SwapPairConstants.WithdrawLiquidity) { SwapPairContract(this)._externalWithdrawLiquidity{ flag: 64, value: 0 }( uo.operationArgs, tokensBurnt, wallet_address, send_gas_to, true ); } else if (uo.operationId == SwapPairConstants.WithdrawLiquidityOneToken) { SwapPairContract(this)._externalWithdrawLiquidity{ flag: 64, value: 0 }( uo.operationArgs, tokensBurnt, wallet_address, send_gas_to, true ); } } //============External LP functions============ /** * Function for token swap. This is top-level wrapper. * @dev This function can be called only by contract itself * @param args Decoded payload from received message * @param tokenReceiver TIP-3 wallet that received tokens * @param token_root Root contract address of transferred token * @param amount Amount of transferred tokens * @param sender_wallet Address of user's TIP-3 wallet * @param original_gas_to Where to send remaining gas */ function _externalSwap( TvmCell args, address tokenReceiver, address token_root, uint128 amount, address sender_wallet, address original_gas_to ) external onlySelf { TvmSlice tmpArgs = args.toSlice(); (bool isPayloadOk, address transferTokensTo) = _checkAndDecompressSwapPayload(tmpArgs); TvmBuilder failTB; if ( !isPayloadOk ){ failTB.store(wrongPayloadFormatMessage); _sendTokens(tokenReceiver, sender_wallet, amount, original_gas_to, true, failTB.toCell()); return; } if ( !_checkIsLiquidityProvided() ){ failTB.store(noLiquidityProvidedMessage); _sendTokens(tokenReceiver, sender_wallet, amount, original_gas_to, true, failTB.toCell()); return; } SwapInfo si = _swap(token_root, amount); if (si.targetTokenAmount != 0) { emit Swap(token_root, _getOppositeToken(token_root), si.swappableTokenAmount, si.targetTokenAmount, si.fee); address tokenWallet = tokenReceiver == tokenWallets[T1] ? tokenWallets[T2] : tokenWallets[T1]; _sendTokens(tokenWallet, transferTokensTo, si.targetTokenAmount, original_gas_to, true, _createSwapPayload(si)); } else { _sendTokens(tokenReceiver, sender_wallet, amount, original_gas_to, true, _createSwapFallbackPayload()); } } /** * Function for liquidity providing. This is top-level wrapper. * @dev This function can be called only by contract itself * @param args Decoded payload from received message * @param tokenReceiver TIP-3 wallet that received tokens * @param amount Amount of transferred tokens * @param sender_wallet Address of user's TIP-3 wallet * @param sender_address Address of user's TON wallet * @param original_gas_to Where to send remaining gas */ function _externalProvideLiquidity( TvmCell args, address tokenReceiver, uint256 sender_public_key, uint128 amount, address sender_wallet, address sender_address, address original_gas_to ) external onlySelf { TvmSlice tmpArgs = args.toSlice(); (bool isPayloadOk, address lpWallet) = _checkAndDecompressProvideLiquidityPayload(tmpArgs); TvmBuilder failTB; if ( !isPayloadOk ) { failTB.store(wrongPayloadFormatMessage); _sendTokens(tokenReceiver, sender_wallet, amount, original_gas_to, false, failTB.toCell()); return; } // TODO: рефакторинг: разнести в разные функции создание записи о пользователе TvmBuilder tb; tb.store(sender_public_key, sender_address); uint256 uniqueID = tvm.hash(tb.toCell()); if (!lpInputTokensInfo.exists(uniqueID)) { LPProvidingInfo _l = LPProvidingInfo( sender_address, sender_public_key, address.makeAddrStd(0, 0), 0, address.makeAddrStd(0, 0), 0 ); lpInputTokensInfo.add(uniqueID, _l); } // TODO: рефокторинг: изменение хранящихся данных LPProvidingInfo lppi = lpInputTokensInfo[uniqueID]; if (tokenReceiver == tokenWallets[0]) { lppi.a1 += amount; lppi.w1 = sender_wallet; } if (tokenReceiver == tokenWallets[1]) { lppi.a2 += amount; lppi.w2 = sender_wallet; } if (lppi.a1 == 0 || lppi.a2 == 0) { lpInputTokensInfo[uniqueID] = lppi; address(sender_wallet).transfer({value: 0, flag: 64}); } else { (uint128 rtp1, uint128 rtp2, ) = _provideLiquidity(lppi.a1, lppi.a2, sender_public_key, sender_address, lpWallet); emit ProvideLiquidity(liquidityTokensMinted, rtp1, rtp2); TvmBuilder payloadTB; payloadTB.store(lppi.a1, rtp1, lppi.a2, rtp2); _tryToReturnProvidingTokens(lppi.a1, rtp1, tokenWallets[T1], lppi.w1, original_gas_to, payloadTB); _tryToReturnProvidingTokens(lppi.a2, rtp2, tokenWallets[T2], lppi.w2, original_gas_to, payloadTB); delete lpInputTokensInfo[uniqueID]; } } // TODO: Антон: проверка провайдинга ликвидности по одному токену /** * Function for liquidity providing using one token. This is top-level wrapper. * @dev This function can be called only by contract itself * @param args Decoded payload from received message * @param tokenRoot Address of TIP-3 root contract * @param tokenReceiver TIP-3 wallet that received tokens * @param amount Amount of transferred tokens * @param sender_wallet Address of user's TIP-3 wallet * @param sender_address Address of user's TON wallet * @param original_gas_to Where to send remaining gas */ function _externalProvideLiquidityOneToken( TvmCell args, address tokenRoot, address tokenReceiver, uint256 sender_public_key, uint128 amount, address sender_wallet, address sender_address, address original_gas_to ) external onlySelf { TvmSlice tmpArgs = args.toSlice(); (bool isPayloadOk, address lpWallet) = _checkAndDecompressProvideLiquidityOneTokenPayload(tmpArgs); TvmBuilder failTB; if ( !isPayloadOk ){ failTB.store(wrongPayloadFormatMessage); _sendTokens(tokenReceiver, sender_wallet, amount, original_gas_to, false, failTB.toCell()); return; } if ( !_checkIsLiquidityProvided() ){ failTB.store(noLiquidityProvidedMessage); _sendTokens(tokenReceiver, sender_wallet, amount, original_gas_to, false, failTB.toCell()); return; } (uint128 provided1, uint128 provided2, , uint128 remainder) = _provideLiquidityOneToken(tokenRoot, amount, sender_public_key, sender_address, lpWallet); if (provided2 == 0 || provided1 == 0) remainder = amount; else emit ProvideLiquidity(liquidityTokensMinted, provided1, provided2); TvmBuilder payloadTB; payloadTB.store(tokenReceiver, amount, remainder, provided1, provided2); _tryToReturnProvidingTokens(remainder, 0, tokenReceiver, sender_wallet, original_gas_to, payloadTB); } /** * Function for liquidity withdrawing. This is top-level wrapper. * @dev This function can be called only by contract itself * @param args Decoded payload from received message * @param amount Amount of transferred tokens * @param sender_wallet Address of user's TIP-3 wallet * @param original_gas_to Where to send remaining gas * @param tokensBurnt Were tokens burnt or jsut transferred */ function _externalWithdrawLiquidity( TvmCell args, uint128 amount, address sender_wallet, address original_gas_to, bool tokensBurnt ) external view onlySelf { TvmSlice tmpArgs = args.toSlice(); (bool isPayloadOk, LPWithdrawInfo lpwi) = _checkAndDecompressWithdrawLiquidityPayload(tmpArgs); if ( !isPayloadOk ) { if ( tokensBurnt ) { IRootTokenContract(lpTokenRootAddress).mint{ flag: 64, value: 0 }(amount, sender_wallet); } else { TvmBuilder failTB; failTB.store(wrongPayloadFormatMessage); _sendTokens(lpTokenWalletAddress, sender_wallet, amount, original_gas_to, false, failTB.toCell()); } return; } SwapPairContract(this)._withdrawTokensFromLP{flag: 64, value: 0}(amount, lpwi, sender_wallet, tokensBurnt, original_gas_to); } /** * Function for liquidity withdrawing. This is top-level wrapper. * @dev This function can be called only by contract itself * @param args Decoded payload from received message * @param amount Amount of transferred tokens * @param sender_wallet Address of user's TIP-3 wallet * @param original_gas_to Where to send remaining gas * @param tokensBurnt Were tokens burnt or jsut transferred */ function _externalWithdrawLiquidityOneToken( TvmCell args, uint128 amount, address sender_wallet, address original_gas_to, bool tokensBurnt ) external view onlySelf { TvmSlice tmpArgs = args.toSlice(); (bool isPayloadOk, address tokenRoot, address userWallet) = _checkAndDecompressWithdrawLiquidityOneTokenPayload(tmpArgs); if ( !isPayloadOk ) { if (tokensBurnt) { IRootTokenContract(lpTokenRootAddress).mint{ flag: 64, value: 0 }(amount, sender_wallet); } else { TvmBuilder failTB; failTB.store(wrongPayloadFormatMessage); _sendTokens(lpTokenWalletAddress, sender_wallet, amount, original_gas_to, false, failTB.toCell()); } return; } SwapPairContract(this)._withdrawOneTokenFromLP{ flag: 64, value: 0 } (amount, tokenRoot, userWallet, sender_wallet, tokensBurnt, original_gas_to); return; } //============Payload manipulation functions============ /** * Check and decompress payload for swap operation * @param tmpArgs Received arguments */ function _checkAndDecompressSwapPayload(TvmSlice tmpArgs) private pure returns (bool isPayloadOk, address transferTokensTo) { bool isSizeOk = tmpArgs.hasNBitsAndRefs(SwapPairConstants.SwapOperationBits, SwapPairConstants.SwapOperationRefs); transferTokensTo = _decompressSwapPayload(tmpArgs); bool isContentOk = transferTokensTo.value != 0; isPayloadOk = isSizeOk && isContentOk; } /** * Check and decompress payload for liquidity providing operation * @param tmpArgs Received arguments */ function _checkAndDecompressProvideLiquidityPayload(TvmSlice tmpArgs) private pure returns (bool isPayloadOk, address lpTokenAddress) { bool isSizeOk = tmpArgs.hasNBitsAndRefs(SwapPairConstants.ProvideLiquidityBits, SwapPairConstants.ProvideLiquidityRefs); lpTokenAddress = _decompressProvideLiquidityPayload(tmpArgs); bool isContentOk = lpTokenAddress.value != 0 || lpTokenAddress.value == 0; isPayloadOk = isSizeOk && isContentOk; } /** * Check and decompress payload for liquidity withdrawing operation * @param tmpArgs Received arguments */ function _checkAndDecompressWithdrawLiquidityPayload(TvmSlice tmpArgs) private pure returns (bool isPayloadOk, LPWithdrawInfo lpwi) { bool isSizeOk = tmpArgs.hasNBitsAndRefs(SwapPairConstants.WithdrawOperationBits, SwapPairConstants.WithdrawOperationRefs); lpwi = _decompressWithdrawLiquidityPayload(tmpArgs); bool isContentOk = lpwi.tr1.value != 0 && lpwi.tr2.value != 0 && lpwi.tw1.value != 0 && lpwi.tw2.value != 0; isPayloadOk = isSizeOk && isContentOk; } /** * Check and decompress payload for liquidity providing using one token operation * @param tmpArgs Received arguments */ function _checkAndDecompressProvideLiquidityOneTokenPayload(TvmSlice tmpArgs) private pure returns (bool isPayloadOk, address lpTokenAddress) { bool isSizeOk = tmpArgs.hasNBitsAndRefs(SwapPairConstants.ProvideLiquidityOneBits, SwapPairConstants.ProvideLiquidityOneRefs); lpTokenAddress = _decompressProvideLiquidityOneTokenPayload(tmpArgs); bool isContentOk = lpTokenAddress.value != 0 || lpTokenAddress.value == 0; isPayloadOk = isSizeOk && isContentOk; } /** * Check and decompress payload for liquidity withdrawing using one token operation * @param tmpArgs Received arguments */ function _checkAndDecompressWithdrawLiquidityOneTokenPayload(TvmSlice tmpArgs) private pure returns (bool isPayloadOk, address tokenRoot, address userWallet) { bool isSizeOk = tmpArgs.hasNBitsAndRefs(SwapPairConstants.WithdrawOneOperationBits, SwapPairConstants.WithdrawOneOperationRefs); (tokenRoot, userWallet) = _decompresskWithdrawLiquidityOneTokenPayload(tmpArgs); bool isContentOk = (tokenRoot.value != 0) && (userWallet.value != 0); isPayloadOk = isSizeOk && isContentOk; } /** * Decompress payload for swap operation * @param tmpArgs Received arguments */ function _decompressSwapPayload(TvmSlice tmpArgs) private pure returns(address) { (address transferTokensTo) = tmpArgs.decode(address); return transferTokensTo; } /** * Decompress payload for liquidity providing operation * @param tmpArgs Received arguments */ function _decompressProvideLiquidityPayload(TvmSlice tmpArgs) private pure returns (address) { address lpWallet = tmpArgs.decode(address); return lpWallet; } /** * Decompress payload for liquidity withdrawing operation * @param tmpArgs Received arguments */ function _decompressWithdrawLiquidityPayload(TvmSlice tmpArgs) private pure returns (LPWithdrawInfo) { LPWithdrawInfo lpwi; (lpwi.tr1, lpwi.tw1) = tmpArgs.decode(address, address); TvmSlice secondPart = tmpArgs.loadRefAsSlice(); (lpwi.tr2, lpwi.tw2) = secondPart.decode(address, address); return lpwi; } /** * Decompress payload for liquidity providing using one token operation * @param tmpArgs Received arguments */ function _decompressProvideLiquidityOneTokenPayload(TvmSlice tmpArgs) private pure returns (address) { address lpWallet = tmpArgs.decode(address); return lpWallet; } /** * Decompress payload for liquidity withdrawing using one token operation * @param tmpArgs Received arguments */ function _decompresskWithdrawLiquidityOneTokenPayload(TvmSlice tmpArgs) private pure returns (address tokenRoot, address userWallet) { (tokenRoot, userWallet) = tmpArgs.decode(address, address); } /** * Create fail payload for swap operation */ function _createSwapFallbackPayload() private pure returns (TvmCell) { TvmBuilder tb; tb.store(sumIsTooLowForSwap); return tb.toCell(); } /** * Create payload with results of withdraw operation * @param w1 Address of token wallet 1 * @param t1a Amount of tokens transferred to w1 * @param w2 Address of token wallet 2 * @param t2a Amount of tokens transferred to w2 */ function _createWithdrawResultPayload(address w1, uint128 t1a, address w2, uint128 t2a) private pure returns (TvmCell) { TvmBuilder payloadB; payloadB.store(w1, t1a, w2, t2a); return payloadB.toCell(); } /** * Create payload for swap operation */ function createSwapPayload(address sendTokensTo) external override pure returns (TvmCell) { TvmBuilder tb; TvmBuilder argsBuilder; argsBuilder.store(sendTokensTo); tb.store(UnifiedOperation(SwapPairConstants.SwapPairOperation, argsBuilder.toCell())); return tb.toCell(); } /** * Create payload for liquidity providing operation * @param tip3Address Address of user's LP token wallet */ function createProvideLiquidityPayload(address tip3Address) external override pure returns (TvmCell) { TvmBuilder tb; TvmBuilder argsBuilder; argsBuilder.store(tip3Address); tb.store(UnifiedOperation(SwapPairConstants.ProvideLiquidity, argsBuilder.toCell())); return tb.toCell(); } /** * Create payload for liquidity providing using one token operation * @param tip3Address Address of user's LP token wallet */ function createProvideLiquidityOneTokenPayload(address tip3Address) external override pure returns (TvmCell) { TvmBuilder tb; TvmBuilder argsBuilder; argsBuilder.store(tip3Address); tb.store(UnifiedOperation(SwapPairConstants.ProvideLiquidityOneToken, argsBuilder.toCell())); return tb.toCell(); } /** * Create payload for liquidity withdrawing operation * @param tokenRoot1 Root contract TIP-3 address of first user's wallet * @param tokenWallet1 Address of first user's TIP-3 wallet * @param tokenRoot1 Root contract TIP-3 address of second user's wallet * @param tokenWallet1 Address of second user's TIP-3 wallet */ function createWithdrawLiquidityPayload( address tokenRoot1, address tokenWallet1, address tokenRoot2, address tokenWallet2 ) external override pure returns (TvmCell) { TvmBuilder tb; TvmBuilder payloadFirstHalf; TvmBuilder payloadSecondHalf; payloadFirstHalf.store(tokenRoot1, tokenWallet1); payloadSecondHalf.store(tokenRoot2, tokenWallet2); payloadFirstHalf.storeRef(payloadSecondHalf); tb.store(UnifiedOperation(SwapPairConstants.WithdrawLiquidity, payloadFirstHalf.toCell())); return tb.toCell(); } /** * Create payload for liquidity withdrawing using one token operation * @param tokenRoot Root contract TIP-3 address of user's wallet * @param userWallet Address of user's TIP-3 wallet */ function createWithdrawLiquidityOneTokenPayload(address tokenRoot, address userWallet) external override pure returns (TvmCell) { TvmBuilder tb; TvmBuilder argsBuilder; argsBuilder.store(tokenRoot, userWallet); tb.store(UnifiedOperation(SwapPairConstants.WithdrawLiquidityOneToken, argsBuilder.toCell())); return tb.toCell(); } //============Upgrade swap pair code part============ /** * Function to update swap pair code * @dev This function can only be called by swap pair root contract * @param newCode New swap pair's code * @param newCodeVersion New swap pair's code version */ function updateSwapPairCode(TvmCell newCode, uint32 newCodeVersion) override external onlySwapPairRoot { require( newCodeVersion > swapPairCodeVersion, SwapPairErrors.CODE_DOWNGRADE_REQUESTED ); tvm.accept(); swapPairCodeVersion = newCodeVersion; tvm.setcode(newCode); tvm.setCurrentCode(newCode); _initializeAfterCodeUpdate(); } /** * Function to check if update is required * @param newCodeVersion New swap pair's code version */ function checkIfSwapPairUpgradeRequired(uint32 newCodeVersion) override external returns(bool) { return newCodeVersion > swapPairCodeVersion; } /** * Function for reinitialization after code update */ function _initializeAfterCodeUpdate() private { //code will be added when required } //============HELPERS============ /** * Send tokens to specified TIP-3 wallet * @param walletToUse Swap pair's wallet to use * @param destinationAddress Address to transfer tokens to * @param amount Amount of tokens to transfer * @param gasBackAddress Address to return gas to * @param notify If transfer should notify receiver * @param payload Payload to attach to message */ function _sendTokens( address walletToUse, address destinationAddress, uint128 amount, address gasBackAddress, bool notify, TvmCell payload ) private pure { ITONTokenWallet(walletToUse).transfer{ value: 0, flag: 64 }(destinationAddress, amount, 0, gasBackAddress, notify, payload); } /** * Create swap payload in case of successfull swap operation * @param si Result of swap pair operation */ function _createSwapPayload(SwapInfo si) private pure returns(TvmCell) { TvmBuilder tb; tb.store(si); return tb.toCell(); } /** * Call root contract to notify about initialization */ function _swapPairInitializedCall() private view { tvm.accept(); SwapPairInfo spi = _constructSwapPairInfo(); IRootContractCallback(swapPairRootContract).swapPairInitializedCallback{ value: 0.1 ton, bounce: true }(spi); } /** * Construct swap pair info struct */ function _constructSwapPairInfo() private view returns (SwapPairInfo) { SwapPairInfo spi = SwapPairInfo( swapPairRootContract, token1, token2, lpTokenRootAddress, tokenWallets[0], tokenWallets[1], lpTokenWalletAddress, creationTimestamp, address(this), swapPairID, swapPairCodeVersion, LPTokenName ); return spi; } /** * Get token position * @param _token Address of token root */ function _getTokenPosition(address _token) private view tokenExistsInPair(_token) returns(uint8) { return tokenPositions[_token]; } /** * Get opposite TIP-3 token root address * @param _token Address of token root */ function _getOppositeToken(address _token) private view returns(address) { return _token == token1? token2 : token1; } /** * Check if liquidity is already provided */ function _checkIsLiquidityProvided() private view returns (bool) { return lps[T1] > 0 && lps[T2] > 0; } /** * Calculate sqrt of given number * @param x Number to calculate sqrt of */ function _sqrt(uint256 x) private pure returns(uint256){ uint256 z = (x+1) / 2; uint256 res = x; while(z < res) { res = z; z = ((x/z) + z) / 2; } return res; } //============Modifiers============ /** * Check if swap pair is initialized */ modifier initialized() { require(initializedStatus == SwapPairConstants.contractFullyInitialized, SwapPairErrors.CONTRACT_NOT_INITIALIZED); _; } /** * Check if msg.sender is known TIP-3 root */ modifier onlyTokenRoot() { require( msg.sender == token1 || msg.sender == token2 || msg.sender == lpTokenRootAddress, SwapPairErrors.CALLER_IS_NOT_TOKEN_ROOT ); _; } /** * Check if msg.sender is LP token root */ modifier onlyLpTokenRoot() { require( msg.sender == lpTokenRootAddress, SwapPairErrors.CALLER_IS_NOT_LP_TOKEN_ROOT ); _; } /** * Check if msg.sender is TIP-3 deployer contract */ modifier onlyTIP3Deployer() { require( msg.sender == tip3Deployer, SwapPairErrors.CALLER_IS_NOT_TIP3_DEPLOYER ); _; } /** * Check if msg.sender is swap pair's TIP-3 wallet */ modifier onlyOwnWallet() { bool b1 = tokenWallets.exists(T1) && msg.sender == tokenWallets[T1]; bool b2 = tokenWallets.exists(T2) && msg.sender == tokenWallets[T2]; bool b3 = msg.sender == lpTokenWalletAddress; require( b1 || b2 || b3, SwapPairErrors.CALLER_IS_NOT_TOKEN_WALLET ); _; } /** * Check if msg.sender is swap pair itself */ modifier onlySelf() { require(msg.sender == address(this)); _; } /** * Check if msg.sender is swap pair root contract */ modifier onlySwapPairRoot() { require( msg.sender == swapPairRootContract, SwapPairErrors.CALLER_IS_NOT_SWAP_PAIR_ROOT ); _; } /** * Check if given TIP-3 token root address is known to pair * @param _token TIP-3 token root address */ modifier tokenExistsInPair(address _token) { require( tokenPositions.exists(_token), SwapPairErrors.INVALID_TOKEN_ADDRESS ); _; } //============Too big for modifier too small for function============ /** * Check if two nubmers are not zeros * @param _amount1 first number * @param _amount2 second number */ function notZeroLiquidity(uint128 _amount1, uint128 _amount2) private pure returns(bool) { return _amount1 > 0 && _amount2 > 0; } }
Deploy wallet for swap pair. You cannot get address from this function so _getWalletAddress is used to get address of wallet tokenRootAddress address of tip-3 root contract/
function _deployWallet(address tokenRootAddress) private view { tvm.accept(); IRootTokenContract(tokenRootAddress).deployEmptyWallet{ value: SwapPairConstants.walletDeployMessageValue }(SwapPairConstants.walletInitialBalanceAmount, tvm.pubkey(), address(this), address(this)); _getWalletAddress(tokenRootAddress); }
12,637,676
./full_match/8453/0x2A0979257105834789bC6b9E1B00446DFbA8dFBa/sources/@aave/core-v3/contracts/misc/AaveProtocolDataProvider.sol
@inheritdoc IPoolDataProvider
function getUnbackedMintCap(address asset) external view override returns (uint256) { return IPool(ADDRESSES_PROVIDER.getPool()).getConfiguration(asset).getUnbackedMintCap(); }
11,545,462
./partial_match/1/0xdD668Fa631C0b3F863e3A830ca23Fe75100009e6/sources/CompoundLeverageModule.sol
MANAGER ONLY: Pays down the borrow asset to 0 selling off a given collateral asset. Any extra received borrow asset is updated as equity. No protocol fee is charged. _setToken Instance of the SetToken _collateralAsset Address of collateral asset (underlying of cToken) _repayAsset Address of asset being repaid (underlying asset e.g. DAI) _redeemQuantity Quantity of collateral asset to delever _tradeAdapterName Name of trade adapter _tradeData Arbitrary data for trade/ We use notionalRepayQuantity vs. Compound's max value uint256(-1) to handle WETH properly Update default position first to save gas on editing borrow position
function deleverToZeroBorrowBalance( ISetToken _setToken, IERC20 _collateralAsset, IERC20 _repayAsset, uint256 _redeemQuantity, string memory _tradeAdapterName, bytes memory _tradeData ) external nonReentrant onlyManagerAndValidSet(_setToken) { uint256 notionalRedeemQuantity = _redeemQuantity.preciseMul(_setToken.totalSupply()); require(borrowCTokenEnabled[_setToken][underlyingToCToken[_repayAsset]], "Borrow not enabled"); uint256 notionalRepayQuantity = underlyingToCToken[_repayAsset].borrowBalanceCurrent(address(_setToken)); ActionInfo memory deleverInfo = _createAndValidateActionInfoNotional( _setToken, _collateralAsset, _repayAsset, notionalRedeemQuantity, notionalRepayQuantity, _tradeAdapterName, false ); _redeemUnderlying(deleverInfo.setToken, deleverInfo.collateralCTokenAsset, deleverInfo.notionalSendQuantity); uint256 postTradeReceiveQuantity = _executeTrade(deleverInfo, _collateralAsset, _repayAsset, _tradeData); _repayBorrow(deleverInfo.setToken, deleverInfo.borrowCTokenAsset, _repayAsset, notionalRepayQuantity); _setToken.calculateAndEditDefaultPosition( address(_repayAsset), deleverInfo.setTotalSupply, deleverInfo.preTradeReceiveTokenBalance ); _updateLeverPositions(deleverInfo, _repayAsset); emit LeverageDecreased( _setToken, _collateralAsset, _repayAsset, deleverInfo.exchangeAdapter, deleverInfo.notionalSendQuantity, notionalRepayQuantity, ); }
2,755,409
./full_match/40/0x6F121834f781d8264A63FbE0a811ADfa351CF0Da/sources/contracts/Auctions/Crowdsale.sol
Admin can set start and end time through this function. _startTime Auction start time. _endTime Auction end time./
function setAuctionTime(uint256 _startTime, uint256 _endTime) external { require(hasAdminRole(msg.sender)); require(_startTime < 10000000000, "Crowdsale: enter an unix timestamp in seconds, not milliseconds"); require(_endTime < 10000000000, "Crowdsale: enter an unix timestamp in seconds, not milliseconds"); require(_startTime >= block.timestamp, "Crowdsale: start time is before current time"); require(_endTime > _startTime, "Crowdsale: end time must be older than start price"); require(marketStatus.commitmentsTotal == 0, "Crowdsale: auction cannot have already started"); marketInfo.startTime = BoringMath.to64(_startTime); marketInfo.endTime = BoringMath.to64(_endTime); emit AuctionTimeUpdated(_startTime,_endTime); }
9,543,968
// SPDX-License-Identifier: MPL-2.0 pragma solidity 0.8.4; import "hardhat/console.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/presets/ERC20PresetMinterPauser.sol"; import {IInbox} from "interfaces/IInbox.sol"; import {IOutbox} from "interfaces/IOutbox.sol"; import {IBridge} from "interfaces/IBridge.sol"; import {IGatewayRouter} from "interfaces/IGatewayRouter.sol"; import {ICustomGateway} from "interfaces/ICustomGateway.sol"; import {IMintRenounceable} from "interfaces/IMintRenounceable.sol"; contract ArbDevWrapper is ERC20Upgradeable, OwnableUpgradeable { using SafeERC20 for IERC20; address public l2Token; address public gateway; address public inbox; address public router; address public devAddress; bool private shouldRegisterGateway; event EscrowMint(address indexed minter, uint256 amount); function initialize( address _l2TokenAddr, address _routerAddr, address _gatewayAddr, address _inbox, address _devAddress ) public initializer { __Ownable_init(); __ERC20_init("Arb Dev Wrapper", "WDEV"); l2Token = _l2TokenAddr; router = _routerAddr; gateway = _gatewayAddr; inbox = _inbox; devAddress = _devAddress; } function escrowMint(uint256 amount) external { address msgSender = _l2Sender(); require(msgSender == l2Token, "sender must be l2 token"); _mint(gateway, amount); ERC20PresetMinterPauser(devAddress).mint(address(this), amount); emit EscrowMint(msgSender, amount); } function _l2Sender() private view returns (address) { IBridge _bridge = IInbox(inbox).bridge(); require(address(_bridge) != address(0), "bridge is zero address"); IOutbox outbox = IOutbox(_bridge.activeOutbox()); require(address(outbox) != address(0), "outbox is zero address"); return outbox.l2ToL1Sender(); } /** * Wrap DEV to create Arbitrum compatible token */ function wrap(uint256 _amount) public returns (bool) { IERC20 _token = IERC20(devAddress); require( _token.balanceOf(address(msg.sender)) >= _amount, "Insufficient balance" ); _token.safeTransferFrom(msg.sender, address(this), _amount); _mint(msg.sender, _amount); _approve(msg.sender, gateway, type(uint256).max); return true; } function wrapAndBridge( uint256 _amount, uint256 _maxGas, uint256 _gasPriceBid, bytes calldata _data ) external payable returns (bool) { wrap(_amount); IGatewayRouter(router).outboundTransfer{value: msg.value}( address(this), msg.sender, _amount, _maxGas, _gasPriceBid, _data ); return true; } /** * Burn pegged token and return DEV */ function unwrap(uint256 _amount) external returns (bool) { require(balanceOf(msg.sender) >= _amount, "Insufficient balance"); _burn(msg.sender, _amount); IERC20(devAddress).safeTransfer(msg.sender, _amount); return true; } /** Safety measure to transfer DEV to owner */ function transferDev() external onlyOwner returns (bool) { IERC20 token = IERC20(devAddress); uint256 balance = token.balanceOf(address(this)); return token.transfer(msg.sender, balance); } /** * Delete mint role */ function renounceMinter() external onlyOwner { IMintRenounceable(devAddress).renounceMinter(); } function isArbitrumEnabled() external view returns (uint16) { require(shouldRegisterGateway, "NOT_EXPECTED_CALL"); return uint16(0xa4b1); } function registerTokenOnL2( address l2CustomTokenAddress, uint256 maxSubmissionCostForCustomBridge, uint256 maxSubmissionCostForRouter, uint256 maxGas, uint256 gasPriceBid ) public payable onlyOwner { // we temporarily set `shouldRegisterGateway` to true for the callback in registerTokenToL2 to succeed bool prev = shouldRegisterGateway; shouldRegisterGateway = true; uint256 gas1 = maxSubmissionCostForCustomBridge + maxGas * gasPriceBid; uint256 gas2 = maxSubmissionCostForRouter + maxGas * gasPriceBid; require(msg.value == gas1 + gas2, "OVERPAY"); ICustomGateway(gateway).registerTokenToL2{value: gas1}( l2CustomTokenAddress, maxGas, gasPriceBid, maxSubmissionCostForCustomBridge ); IGatewayRouter(router).setGateway{value: gas2}( gateway, maxGas, gasPriceBid, maxSubmissionCostForRouter ); shouldRegisterGateway = prev; } } // 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: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ 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_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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; import "../ERC20.sol"; import "../extensions/ERC20Burnable.sol"; import "../extensions/ERC20Pausable.sol"; import "../../../access/AccessControlEnumerable.sol"; import "../../../utils/Context.sol"; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC20PresetMinterPauser is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol) ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MPL-2.0 pragma solidity ^0.8.0; import {IBridge} from "./IBridge.sol"; interface IInbox { function bridge() external view returns (IBridge); } // SPDX-License-Identifier: MPL-2.0 pragma solidity ^0.8.0; interface IOutbox { function l2ToL1Sender() external view returns (address); } // SPDX-License-Identifier: MPL-2.0 pragma solidity ^0.8.0; interface IBridge { function activeOutbox() external view returns (address); } // SPDX-License-Identifier: MPL-2.0 pragma solidity ^0.8.0; interface IGatewayRouter { function outboundTransfer( address _l1Token, address _to, uint256 _amount, uint256 _maxGas, uint256 _gasPriceBid, bytes calldata _data ) external payable returns (bytes memory res); function setGateway( address _gateway, uint256 _maxGas, uint256 _gasPriceBid, uint256 _maxSubmissionCost ) external payable returns (uint256); } // SPDX-License-Identifier: MPL-2.0 pragma solidity ^0.8.0; interface ICustomGateway { function registerTokenToL2( address _l2CustomTokenAddress, uint256 _maxGas, uint256 _gasPriceBid, uint256 _maxSubmissionCostForCustomBridge ) external payable; } // SPDX-License-Identifier: MPL-2.0 pragma solidity ^0.8.0; interface IMintRenounceable { function renounceMinter() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @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 "../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 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; /** * @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; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../security/Pausable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view 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(AccessControl, IAccessControl) { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { 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); } } // 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 "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT 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 Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT 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; /** * @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); }
Safety measure to transfer DEV to owner /
function transferDev() external onlyOwner returns (bool) { IERC20 token = IERC20(devAddress); uint256 balance = token.balanceOf(address(this)); return token.transfer(msg.sender, balance); }
13,834,163
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "./OracleConsumer.sol"; import "../Tokens/OutcomeToken.sol"; import "../Utils/Proxy.sol"; contract EventData { /* * Events */ event OutcomeTokenCreation(OutcomeToken outcomeToken, uint8 index); event OutcomeTokenSetIssuance(address indexed buyer, uint collateralTokenCount); event OutcomeTokenSetRevocation(address indexed seller, uint outcomeTokenCount); event OutcomeAssignment(int outcome); event WinningsRedemption(address indexed receiver, uint winnings); /* * Storage */ ERC20 public collateralToken; address public oracle; bool public isOutcomeSet; int public outcome; OutcomeToken[] public outcomeTokens; } /// @title Event contract - Provide basic functionality required by different event types /// @author Stefan George - <[email protected]> contract Event is OracleConsumer, EventData { /* * Public functions */ /// @dev Buys equal number of tokens of all outcomes, exchanging collateral tokens and sets of outcome tokens 1:1 /// @param collateralTokenCount Number of collateral tokens function buyAllOutcomes(uint collateralTokenCount) public { // Transfer collateral tokens to events contract require(collateralToken.transferFrom(msg.sender, this, collateralTokenCount)); // Issue new outcome tokens to sender for (uint8 i = 0; i < outcomeTokens.length; i++) outcomeTokens[i].issue(msg.sender, collateralTokenCount); emit OutcomeTokenSetIssuance(msg.sender, collateralTokenCount); } /// @dev Sells equal number of tokens of all outcomes, exchanging collateral tokens and sets of outcome tokens 1:1 /// @param outcomeTokenCount Number of outcome tokens function sellAllOutcomes(uint outcomeTokenCount) public { // Revoke sender's outcome tokens of all outcomes for (uint8 i = 0; i < outcomeTokens.length; i++) outcomeTokens[i].revoke(msg.sender, outcomeTokenCount); // Transfer collateral tokens to sender require(collateralToken.transfer(msg.sender, outcomeTokenCount)); emit OutcomeTokenSetRevocation(msg.sender, outcomeTokenCount); } /// @dev Receives a result. Caller must be the oracle. Will ignore the ID. /// @param result The result function receiveResult(bytes32 /*id*/, bytes32 result) external { // Winning outcome is not set yet in event contract but in oracle contract require(msg.sender == oracle && !isOutcomeSet); // Set winning outcome outcome = int(result); isOutcomeSet = true; emit OutcomeAssignment(outcome); } /// @dev Returns outcome count /// @return Outcome count function getOutcomeCount() public view returns (uint8) { return uint8(outcomeTokens.length); } /// @dev Returns outcome tokens array /// @return Outcome tokens function getOutcomeTokens() public view returns (OutcomeToken[]) { return outcomeTokens; } /// @dev Returns the amount of outcome tokens held by owner /// @return Outcome token distribution function getOutcomeTokenDistribution(address owner) public view returns (uint[] outcomeTokenDistribution) { outcomeTokenDistribution = new uint[](outcomeTokens.length); for (uint8 i = 0; i < outcomeTokenDistribution.length; i++) outcomeTokenDistribution[i] = outcomeTokens[i].balanceOf(owner); } /// @dev Exchanges sender's winning outcome tokens for collateral tokens /// @return Sender's winnings function redeemWinnings() public returns (uint); }
Returns the amount of outcome tokens held by owner return Outcome token distribution
function getOutcomeTokenDistribution(address owner) public view returns (uint[] outcomeTokenDistribution) { outcomeTokenDistribution = new uint[](outcomeTokens.length); for (uint8 i = 0; i < outcomeTokenDistribution.length; i++) outcomeTokenDistribution[i] = outcomeTokens[i].balanceOf(owner); }
6,350,566
./partial_match/1/0xbB67cF157beE9c5208CC9E6A18480e647E25EEaB/sources/MoneyMaker.sol
Withdraw LP tokens from MasterChef. pid => mapping(address => userInfo) UserInfo {amount, rewardDebt};emit Withdraw1(user.rewardDebt);emit TestWithdraw(msg.sender, _pid, _amount, pool.accASTPerShare, pending);to msg.sender pending amount 100 - 100 5 1/100 = 100 - 0.5 to msg.sender _amount 100 + 100 5 1/1000 = 100 + 0.5 _amount.add(_amount.mul(per2.div(1e12))
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accASTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeASTTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accASTPerShare).div(1e12); }
4,383,686
./full_match/80001/0x17CEa53eC2991445C2099Db1B31Ee978032A3A82/sources/contracts/CrowdFunding.sol
we are going to send some crpyto currency
function donateToCampaign(uint256 _id) public payable { uint256 amount=msg.value; Campaign storage campaign=campaigns[_id]; campaign.donators.push(msg.sender); campaign.donations.push(amount); if(sent){ campaign.amountCollected=campaign.amountCollected+amount; } }
5,687,822
// File: openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol pragma solidity ^0.5.16; /** * @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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @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(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/SpartanCouncil.sol /** * @title Custom NFT contract based off ERC721 but restricted by access control. * @dev made for https://sips.synthetix.io/sips/sip-93 */ contract IlluvinatiCouncil is Ownable { // Event that is emitted when a new SpartanCouncil token is minted event Mint(uint256 indexed tokenId, address to); // Event that is emitted when an existing SpartanCouncil token is burned event Burn(uint256 indexed tokenId); // Event that is emitted when an existing SpartanCouncil token is Transferred event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); // Event that is emitted when an existing SpartanCouncil token's uri is altered event TokenURISet(uint256 tokenId, string tokenURI); // Array of token ids uint256[] public tokens; // Map between an owner and their tokens mapping(address => uint256) public tokenOwned; // Maps a token to the owner address mapping(uint256 => address) public ownerOf; // Optional mapping for token URIs mapping(uint256 => string) private tokenURIs; // Token name string public name; // Token symbol string public symbol; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. * @param _name the name of the token * @param _symbol the symbol of the token */ constructor(string memory _name, string memory _symbol) public { name = _name; symbol = _symbol; } /** * @dev Modifier to check that an address is not the "0" address * @param to address the address to check */ modifier isValidAddress(address to) { require(to != address(0), "Method called with the zero address"); _; } /** * @dev Function to retrieve whether an address owns a token * @param owner address the address to check the balance of */ function balanceOf(address owner) public view isValidAddress(owner) returns (uint256) { return tokenOwned[owner] > 0 ? 1 : 0; } /** * @dev Transfer function to assign a token to another address * Reverts if the address already owns a token * @param from address the address that currently owns the token * @param to address the address to assign the token to * @param tokenId uint256 ID of the token to transfer */ function transferFrom( address from, address to, uint256 tokenId ) public isValidAddress(to) isValidAddress(from) onlyOwner { require(tokenOwned[to] == 0, "Destination address already owns a token"); require(ownerOf[tokenId] == from, "From address does not own token"); tokenOwned[from] = 0; tokenOwned[to] = tokenId; ownerOf[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Mint function to mint a new token given a tokenId and assign it to an address * Reverts if the tokenId is 0 or the token already exist * @param to address the address to assign the token to * @param tokenId uint256 ID of the token to mint */ function mint(address to, uint256 tokenId) public onlyOwner isValidAddress(to) { _mint(to, tokenId); } /** * @dev Mint function to mint a new token given a tokenId and assign it to an address * Reverts if the tokenId is 0 or the token already exist * @param to address the address to assign the token to * @param tokenId uint256 ID of the token to mint */ function mintWithTokenURI( address to, uint256 tokenId, string memory uri ) public onlyOwner isValidAddress(to) { require(bytes(uri).length > 0, "URI must be supplied"); _mint(to, tokenId); tokenURIs[tokenId] = uri; emit TokenURISet(tokenId, uri); } function _mint(address to, uint256 tokenId) private { require(tokenOwned[to] == 0, "Destination address already owns a token"); require(ownerOf[tokenId] == address(0), "ERC721: token already minted"); require(tokenId != 0, "Token ID must be greater than 0"); tokens.push(tokenId); tokenOwned[to] = tokenId; ownerOf[tokenId] = to; emit Transfer(address(0), to, tokenId); emit Mint(tokenId, to); } /** * @dev Burn function to remove a given tokenId * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to burn */ function burn(uint256 tokenId) public onlyOwner { address previousOwner = ownerOf[tokenId]; require(previousOwner != address(0), "ERC721: token does not exist"); delete tokenOwned[previousOwner]; delete ownerOf[tokenId]; for (uint256 i = 0; i < tokens.length; i++) { if (tokens[i] == tokenId) { tokens[i] = tokens[tokens.length - 1]; break; } } tokens.pop(); if (bytes(tokenURIs[tokenId]).length != 0) { delete tokenURIs[tokenId]; } emit Burn(tokenId); } /** * @dev Function to get the total supply of tokens currently available */ function totalSupply() public view returns (uint256) { return tokens.length; } /** * @dev Function to get the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to retrieve the uri for */ function tokenURI(uint256 tokenId) public view returns (string memory) { require(ownerOf[tokenId] != address(0), "ERC721: token does not exist"); string memory _tokenURI = tokenURIs[tokenId]; return _tokenURI; } /** * @dev Function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function setTokenURI(uint256 tokenId, string memory uri) public onlyOwner { require(ownerOf[tokenId] != address(0), "ERC721: token does not exist"); tokenURIs[tokenId] = uri; emit TokenURISet(tokenId, uri); } }
Function to retrieve whether an address owns a token owner address the address to check the balance of/
function balanceOf(address owner) public view isValidAddress(owner) returns (uint256) { return tokenOwned[owner] > 0 ? 1 : 0; }
211,530
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) 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 // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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 pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits */ function toUint192(uint256 value) internal pure returns (uint192) { require(value <= type(uint192).max, "SafeCast: value doesn't fit in 128 bits"); return uint192(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } } // SPDX-License-Identifier: UNLICENSED /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity 0.8.11; library BytesLib { function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) { require(_bytes.length >= _start + 1 , "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "../../../external/@openzeppelin/token/ERC20/IERC20.sol"; interface IHarvestPool { function rewardToken() external view returns (address); function lpToken() external view returns (address); function duration() external view returns (uint256); function periodFinish() external view returns (uint256); function rewardRate() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function stake(uint256 amountWei) external; // `balanceOf` would give the amount staked. // As this is 1 to 1, this is also the holder's share function balanceOf(address holder) external view returns (uint256); // total shares & total lpTokens staked function totalSupply() external view returns (uint256); function withdraw(uint256 amountWei) external; function exit() external; // get claimed rewards function earned(address holder) external view returns (uint256); // claim rewards function getReward() external; // notify function notifyRewardAmount(uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; interface IHarvestVault { function underlyingBalanceInVault() external view returns (uint256); function underlyingBalanceWithInvestment() external view returns (uint256); // function store() external view returns (address); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function strategy() external view returns (address); function setStrategy(address _strategy) external; function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external; function deposit(uint256 amountWei) external; function depositFor(uint256 amountWei, address holder) external; function withdrawAll() external; function withdraw(uint256 numberOfShares) external; function getPricePerFullShare() external view returns (uint256); function underlyingBalanceWithInvestmentForHolder(address holder) external view returns (uint256); // hard work should be callable only by the controller (by the hard worker) or by governance function doHardWork() external; function totalSupply() external view returns (uint256); function balanceOf(address user) external view returns (uint256); function approve(address user, uint256 amount) external returns (bool); function underlyingUnit() external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import './IV2SwapRouter.sol'; import './IV3SwapRouter.sol'; /// @title Router token swapping functionality interface ISwapRouter02 is IV2SwapRouter, IV3SwapRouter { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V2 interface IV2SwapRouter { /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance, /// and swap the entire amount, enabling contracts to send tokens before calling this function. /// @param amountIn The amount of token to swap /// @param amountOutMin The minimum amount of output that must be received /// @param path The ordered list of tokens to swap through /// @param to The recipient address /// @return amountOut The amount of the received token function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to ) external payable returns (uint256 amountOut); /// @notice Swaps as little as possible of one token for an exact amount of another token /// @param amountOut The amount of token to swap for /// @param amountInMax The maximum amount of input that the caller will pay /// @param path The ordered list of tokens to swap through /// @param to The recipient address /// @return amountIn The amount of token to pay function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to ) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface IV3SwapRouter{ struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance, /// and swap the entire amount, enabling contracts to send tokens before calling this function. /// @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 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance, /// and swap the entire amount, enabling contracts to send tokens before calling this function. /// @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 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// that may remain in the router after the swap. /// @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 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// that may remain in the router after the swap. /// @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); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; import "./ISwapData.sol"; interface IBaseStrategy { function underlying() external view returns (IERC20); function getStrategyBalance() external view returns (uint128); function getStrategyUnderlyingWithRewards() external view returns(uint128); function process(uint256[] calldata, bool, SwapData[] calldata) external; function processReallocation(uint256[] calldata, ProcessReallocationData calldata) external returns(uint128); function processDeposit(uint256[] calldata) external; function fastWithdraw(uint128, uint256[] calldata, SwapData[] calldata) external returns(uint128); function claimRewards(SwapData[] calldata) external; function emergencyWithdraw(address recipient, uint256[] calldata data) external; function initialize() external; function disable() external; } struct ProcessReallocationData { uint128 sharesToWithdraw; uint128 optimizedShares; uint128 optimizedWithdrawnAmount; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; /** * @notice Strict holding information how to swap the asset * @member slippage minumum output amount * @member path swap path, first byte represents an action (e.g. Uniswap V2 custom swap), rest is swap specific path */ struct SwapData { uint256 slippage; // min amount out bytes path; // 1st byte is action, then path } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "../external/@openzeppelin/utils/SafeCast.sol"; /** * @notice A collection of custom math ustils used throughout the system */ library Math { function min(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? b : a; } function getProportion128(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) { return SafeCast.toUint128(((mul1 * mul2) / div)); } function getProportion128Unchecked(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) { unchecked { return uint128((mul1 * mul2) / div); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /** @notice Handle setting zero value in a storage word as uint128 max value. * * @dev * The purpose of this is to avoid resetting a storage word to the zero value; * the gas cost of re-initializing the value is the same as setting the word originally. * so instead, if word is to be set to zero, we set it to uint128 max. * * - anytime a word is loaded from storage: call "get" * - anytime a word is written to storage: call "set" * - common operations on uints are also bundled here. * * NOTE: This library should ONLY be used when reading or writing *directly* from storage. */ library Max128Bit { uint128 internal constant ZERO = type(uint128).max; function get(uint128 a) internal pure returns(uint128) { return (a == ZERO) ? 0 : a; } function set(uint128 a) internal pure returns(uint128){ return (a == 0) ? ZERO : a; } function add(uint128 a, uint128 b) internal pure returns(uint128 c){ a = get(a); c = set(a + b); } } // SPDX-License-Identifier: BUSL-1.1 import "../interfaces/ISwapData.sol"; pragma solidity 0.8.11; /// @notice Strategy struct for all strategies struct Strategy { uint128 totalShares; /// @notice Denotes strategy completed index uint24 index; /// @notice Denotes whether strategy is removed /// @dev after removing this value can never change, hence strategy cannot be added back again bool isRemoved; /// @notice Pending geposit amount and pending shares withdrawn by all users for next index Pending pendingUser; /// @notice Used if strategies "dohardwork" hasn't been executed yet in the current index Pending pendingUserNext; /// @dev Usually a temp variable when compounding mapping(address => uint256) pendingRewards; /// @dev Usually a temp variable when compounding uint128 pendingDepositReward; /// @notice Amount of lp tokens the strategy holds, NOTE: not all strategies use it uint256 lpTokens; // ----- REALLOCATION VARIABLES ----- bool isInDepositPhase; /// @notice Used to store amount of optimized shares, so they can be substracted at the end /// @dev Only for temporary use, should be reset to 0 in same transaction uint128 optimizedSharesWithdrawn; /// @dev Underlying amount pending to be deposited from other strategies at reallocation /// @dev resets after the strategy reallocation DHW is finished uint128 pendingReallocateDeposit; /// @notice Stores amount of optimized underlying amount when reallocating /// @dev resets after the strategy reallocation DHW is finished /// @dev This is "virtual" amount that was matched between this strategy and others when reallocating uint128 pendingReallocateOptimizedDeposit; // ------------------------------------ /// @notice Total underlying amoung at index mapping(uint256 => TotalUnderlying) totalUnderlying; /// @notice Batches stored after each DHW with index as a key /// @dev Holds information for vauls to redeem newly gained shares and withdrawn amounts belonging to users mapping(uint256 => Batch) batches; /// @notice Batches stored after each DHW reallocating (if strategy was set to reallocate) /// @dev Holds information for vauls to redeem newly gained shares and withdrawn shares to complete reallocation mapping(uint256 => BatchReallocation) reallocationBatches; /// @notice Vaults holding this strategy shares mapping(address => Vault) vaults; /// @notice Future proof storage mapping(bytes32 => AdditionalStorage) additionalStorage; /// @dev Make sure to reset it to 0 after emergency withdrawal uint256 emergencyPending; } /// @notice Unprocessed deposit underlying amount and strategy share amount from users struct Pending { uint128 deposit; uint128 sharesToWithdraw; } /// @notice Struct storing total underlying balance of a strategy for an index, along with total shares at same index struct TotalUnderlying { uint128 amount; uint128 totalShares; } /// @notice Stored after executing DHW for each index. /// @dev This is used for vaults to redeem their deposit. struct Batch { /// @notice total underlying deposited in index uint128 deposited; uint128 depositedReceived; uint128 depositedSharesReceived; uint128 withdrawnShares; uint128 withdrawnReceived; } /// @notice Stored after executing reallocation DHW each index. struct BatchReallocation { /// @notice Deposited amount received from reallocation uint128 depositedReallocation; /// @notice Received shares from reallocation uint128 depositedReallocationSharesReceived; /// @notice Used to know how much tokens was received for reallocating uint128 withdrawnReallocationReceived; /// @notice Amount of shares to withdraw for reallocation uint128 withdrawnReallocationShares; } /// @notice VaultBatches could be refactored so we only have 2 structs current and next (see how Pending is working) struct Vault { uint128 shares; /// @notice Withdrawn amount as part of the reallocation uint128 withdrawnReallocationShares; /// @notice Index to action mapping(uint256 => VaultBatch) vaultBatches; } /// @notice Stores deposited and withdrawn shares by the vault struct VaultBatch { /// @notice Vault index to deposited amount mapping uint128 deposited; /// @notice Vault index to withdrawn user shares mapping uint128 withdrawnShares; } /// @notice Used for reallocation calldata struct VaultData { address vault; uint8 strategiesCount; uint256 strategiesBitwise; uint256 newProportions; } /// @notice Calldata when executing reallocatin DHW /// @notice Used in the withdraw part of the reallocation DHW struct ReallocationWithdrawData { uint256[][] reallocationTable; StratUnderlyingSlippage[] priceSlippages; RewardSlippages[] rewardSlippages; uint256[] stratIndexes; uint256[][] slippages; } /// @notice Calldata when executing reallocatin DHW /// @notice Used in the deposit part of the reallocation DHW struct ReallocationData { uint256[] stratIndexes; uint256[][] slippages; } /// @notice In case some adapters need extra storage struct AdditionalStorage { uint256 value; address addressValue; uint96 value96; } /// @notice Strategy total underlying slippage, to verify validity of the strategy state struct StratUnderlyingSlippage { uint128 min; uint128 max; } /// @notice Containig information if and how to swap strategy rewards at the DHW /// @dev Passed in by the do-hard-worker struct RewardSlippages { bool doClaim; SwapData[] swapData; } /// @notice Helper struct to compare strategy share between eachother /// @dev Used for reallocation optimization of shares (strategy matching deposits and withdrawals between eachother when reallocating) struct PriceData { uint128 totalValue; uint128 totalShares; } /// @notice Strategy reallocation values after reallocation optimization of shares was calculated struct ReallocationShares { uint128[] optimizedWithdraws; uint128[] optimizedShares; uint128[] totalSharesWithdrawn; } /// @notice Shared storage for multiple strategies /// @dev This is used when strategies are part of the same proticil (e.g. Curve 3pool) struct StrategiesShared { uint184 value; uint32 lastClaimBlock; uint32 lastUpdateBlock; uint8 stratsCount; mapping(uint256 => address) stratAddresses; mapping(bytes32 => uint256) bytesValues; } /// @notice Base storage shared betweek Spool contract and Strategies /// @dev this way we can use same values when performing delegate call /// to strategy implementations from the Spool contract abstract contract BaseStorage { // ----- DHW VARIABLES ----- /// @notice Force while DHW (all strategies) to be executed in only one transaction /// @dev This is enforced to increase the gas efficiency of the system /// Can be removed by the DAO if gas gost of the strategies goes over the block limit bool internal forceOneTxDoHardWork; /// @notice Global index of the system /// @dev Insures the correct strategy DHW execution. /// Every strategy in the system must be equal or one less than global index value /// Global index increments by 1 on every do-hard-work uint24 public globalIndex; /// @notice number of strategies unprocessed (by the do-hard-work) in the current index to be completed uint8 internal doHardWorksLeft; // ----- REALLOCATION VARIABLES ----- /// @notice Used for offchain execution to get the new reallocation table. bool internal logReallocationTable; /// @notice number of withdrawal strategies unprocessed (by the do-hard-work) in the current index /// @dev only used when reallocating /// after it reaches 0, deposit phase of the reallocation can begin uint8 public withdrawalDoHardWorksLeft; /// @notice Index at which next reallocation is set uint24 public reallocationIndex; /// @notice 2D table hash containing information of how strategies should be reallocated between eachother /// @dev Created when allocation provider sets reallocation for the vaults /// This table is stored as a hash in the system and verified on reallocation DHW /// Resets to 0 after reallocation DHW is completed bytes32 internal reallocationTableHash; /// @notice Hash of all the strategies array in the system at the time when reallocation was set for index /// @dev this array is used for the whole reallocation period even if a strategy gets exploited when reallocating. /// This way we can remove the strategy from the system and not breaking the flow of the reallocaton /// Resets when DHW is completed bytes32 internal reallocationStrategiesHash; // ----------------------------------- /// @notice Denoting if an address is the do-hard-worker mapping(address => bool) public isDoHardWorker; /// @notice Denoting if an address is the allocation provider mapping(address => bool) public isAllocationProvider; /// @notice Strategies shared storage /// @dev used as a helper storage to save common inoramation mapping(bytes32 => StrategiesShared) internal strategiesShared; /// @notice Mapping of strategy implementation address to strategy system values mapping(address => Strategy) public strategies; /// @notice Flag showing if disable was skipped when a strategy has been removed /// @dev If true disable can still be run mapping(address => bool) internal _skippedDisable; /// @notice Flag showing if after removing a strategy emergency withdraw can still be executed /// @dev If true emergency withdraw can still be executed mapping(address => bool) internal _awaitingEmergencyWithdraw; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; /// @title Common Spool contracts constants abstract contract BaseConstants { /// @dev 2 digits precision uint256 internal constant FULL_PERCENT = 100_00; /// @dev Accuracy when doing shares arithmetics uint256 internal constant ACCURACY = 10**30; } /// @title Contains USDC token related values abstract contract USDC { /// @notice USDC token contract address IERC20 internal constant USDC_ADDRESS = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../external/GNSPS-solidity-bytes-utils/BytesLib.sol"; import "../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol"; import "../external/uniswap/interfaces/ISwapRouter02.sol"; import "../interfaces/ISwapData.sol"; /// @notice Denotes swap action mode enum SwapAction { NONE, UNI_V2_DIRECT, UNI_V2_WETH, UNI_V2, UNI_V3_DIRECT, UNI_V3_WETH, UNI_V3 } /// @title Contains logic facilitating swapping using Uniswap abstract contract SwapHelper { using BytesLib for bytes; using SafeERC20 for IERC20; /// @dev The length of the bytes encoded swap action uint256 private constant ACTION_SIZE = 1; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev Maximum V2 path length (4 swaps) uint256 private constant MAX_V2_PATH = ADDR_SIZE * 3; /// @dev V3 WETH path length uint256 private constant WETH_V3_PATH_SIZE = FEE_SIZE + FEE_SIZE; /// @dev Minimum V3 custom path length (2 swaps) uint256 private constant MIN_V3_PATH = FEE_SIZE + NEXT_OFFSET; /// @dev Maximum V3 path length (4 swaps) uint256 private constant MAX_V3_PATH = FEE_SIZE + NEXT_OFFSET * 3; /// @notice Uniswap router supporting Uniswap V2 and V3 ISwapRouter02 internal immutable uniswapRouter; /// @notice Address of WETH token address private immutable WETH; /** * @notice Sets initial values * @param _uniswapRouter Uniswap router address * @param _WETH WETH token address */ constructor(ISwapRouter02 _uniswapRouter, address _WETH) { uniswapRouter = _uniswapRouter; WETH = _WETH; } /** * @notice Approve reward token and swap the `amount` to a strategy underlying asset * @param from Token to swap from * @param to Token to swap to * @param amount Amount of tokens to swap * @param swapData Swap details showing the path of the swap * @return result Amount of underlying (`to`) tokens recieved */ function _approveAndSwap( IERC20 from, IERC20 to, uint256 amount, SwapData calldata swapData ) internal virtual returns (uint256) { // if there is nothing to swap, return if(amount == 0) return 0; // if amount is not uint256 max approve unswap router to spend tokens // otherwise rewards were already sent to the router if(amount < type(uint256).max) { from.safeApprove(address(uniswapRouter), amount); } else { amount = 0; } // get swap action from first byte SwapAction action = SwapAction(swapData.path.toUint8(0)); uint256 result; if (action == SwapAction.UNI_V2_DIRECT) { // V2 Direct address[] memory path = new address[](2); result = _swapV2(from, to, amount, swapData.slippage, path); } else if (action == SwapAction.UNI_V2_WETH) { // V2 WETH address[] memory path = new address[](3); path[1] = WETH; result = _swapV2(from, to, amount, swapData.slippage, path); } else if (action == SwapAction.UNI_V2) { // V2 Custom address[] memory path = _getV2Path(swapData.path); result = _swapV2(from, to, amount, swapData.slippage, path); } else if (action == SwapAction.UNI_V3_DIRECT) { // V3 Direct result = _swapDirectV3(from, to, amount, swapData.slippage, swapData.path); } else if (action == SwapAction.UNI_V3_WETH) { // V3 WETH bytes memory wethPath = _getV3WethPath(swapData.path); result = _swapV3(from, to, amount, swapData.slippage, wethPath); } else if (action == SwapAction.UNI_V3) { // V3 Custom require(swapData.path.length > MIN_V3_PATH, "SwapHelper::_approveAndSwap: Path too short"); uint256 actualpathSize = swapData.path.length - ACTION_SIZE; require((actualpathSize - FEE_SIZE) % NEXT_OFFSET == 0 && actualpathSize <= MAX_V3_PATH, "SwapHelper::_approveAndSwap: Bad V3 path"); result = _swapV3(from, to, amount, swapData.slippage, swapData.path[ACTION_SIZE:]); } else { revert("SwapHelper::_approveAndSwap: No action"); } if (from.allowance(address(this), address(uniswapRouter)) > 0) { from.safeApprove(address(uniswapRouter), 0); } return result; } /** * @notice Swaps tokens using Uniswap V2 * @param from Token to swap from * @param to Token to swap to * @param amount Amount of tokens to swap * @param slippage Allowed slippage * @param path Steps to complete the swap * @return result Amount of underlying (`to`) tokens recieved */ function _swapV2( IERC20 from, IERC20 to, uint256 amount, uint256 slippage, address[] memory path ) internal virtual returns (uint256) { path[0] = address(from); path[path.length - 1] = address(to); return uniswapRouter.swapExactTokensForTokens( amount, slippage, path, address(this) ); } /** * @notice Swaps tokens using Uniswap V3 * @param from Token to swap from * @param to Token to swap to * @param amount Amount of tokens to swap * @param slippage Allowed slippage * @param path Steps to complete the swap * @return result Amount of underlying (`to`) tokens recieved */ function _swapV3( IERC20 from, IERC20 to, uint256 amount, uint256 slippage, bytes memory path ) internal virtual returns (uint256) { IV3SwapRouter.ExactInputParams memory params = IV3SwapRouter.ExactInputParams({ path: abi.encodePacked(address(from), path, address(to)), recipient: address(this), amountIn: amount, amountOutMinimum: slippage }); // Executes the swap. uint received = uniswapRouter.exactInput(params); return received; } /** * @notice Does a direct swap from `from` address to the `to` address using Uniswap V3 * @param from Token to swap from * @param to Token to swap to * @param amount Amount of tokens to swap * @param slippage Allowed slippage * @param fee V3 direct fee configuration * @return result Amount of underlying (`to`) tokens recieved */ function _swapDirectV3( IERC20 from, IERC20 to, uint256 amount, uint256 slippage, bytes memory fee ) internal virtual returns (uint256) { require(fee.length == FEE_SIZE + ACTION_SIZE, "SwapHelper::_swapDirectV3: Bad V3 direct fee"); IV3SwapRouter.ExactInputSingleParams memory params = IV3SwapRouter.ExactInputSingleParams( address(from), address(to), // ignore first byte fee.toUint24(ACTION_SIZE), address(this), amount, slippage, 0 ); return uniswapRouter.exactInputSingle(params); } /** * @notice Converts passed bytes to V2 path * @param pathBytes Swap path in bytes, converted to addresses * @return path list of addresses in the swap path (skipping first and last element) */ function _getV2Path(bytes calldata pathBytes) internal pure returns(address[] memory) { require(pathBytes.length > ACTION_SIZE, "SwapHelper::_getV2Path: No path provided"); uint256 actualpathSize = pathBytes.length - ACTION_SIZE; require(actualpathSize % ADDR_SIZE == 0 && actualpathSize <= MAX_V2_PATH, "SwapHelper::_getV2Path: Bad V2 path"); uint256 pathLength = actualpathSize / ADDR_SIZE; address[] memory path = new address[](pathLength + 2); // ignore first byte path[1] = pathBytes.toAddress(ACTION_SIZE); for (uint256 i = 1; i < pathLength; i++) { path[i + 1] = pathBytes.toAddress(i * ADDR_SIZE + ACTION_SIZE); } return path; } /** * @notice Get Unswap V3 path to swap tokens via WETH LP pool * @param pathBytes Swap path in bytes * @return wethPath Unswap V3 path routing via WETH pool */ function _getV3WethPath(bytes calldata pathBytes) internal view returns(bytes memory) { require(pathBytes.length == WETH_V3_PATH_SIZE + ACTION_SIZE, "SwapHelper::_getV3WethPath: Bad V3 WETH path"); // ignore first byte as it's used for swap action return abi.encodePacked(pathBytes[ACTION_SIZE:4], WETH, pathBytes[4:]); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./SwapHelper.sol"; /// @title Swap helper implementation with SwapRouter02 on Mainnet contract SwapHelperMainnet is SwapHelper { constructor() SwapHelper(ISwapRouter02(0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45), 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {} } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../interfaces/IBaseStrategy.sol"; import "../shared/BaseStorage.sol"; import "../shared/Constants.sol"; import "../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol"; import "../libraries/Math.sol"; import "../libraries/Max/128Bit.sol"; /** * @notice Implementation of the {IBaseStrategy} interface. * * @dev * This implementation of the {IBaseStrategy} is meant to operate * on single-collateral strategies and uses a delta system to calculate * whether a withdrawal or deposit needs to be performed for a particular * strategy. */ abstract contract BaseStrategy is IBaseStrategy, BaseStorage, BaseConstants { using SafeERC20 for IERC20; using Max128Bit for uint128; /* ========== CONSTANTS ========== */ /// @notice minimum shares size to avoid loss of share due to computation precision uint128 private constant MIN_SHARES = 10**8; /* ========== STATE VARIABLES ========== */ /// @notice The total slippage slots the strategy supports, used for validation of provided slippage uint256 internal immutable rewardSlippageSlots; /// @notice Slots for processing uint256 internal immutable processSlippageSlots; /// @notice Slots for reallocation uint256 internal immutable reallocationSlippageSlots; /// @notice Slots for deposit uint256 internal immutable depositSlippageSlots; /** * @notice do force claim of rewards. * * @dev * Some strategies auto claim on deposit/withdraw, * so execute the claim actions to store the reward amounts. */ bool internal immutable forceClaim; /// @notice flag to force balance validation before running process strategy /// @dev this is done so noone can manipulate the strategies before we interact with them and cause harm to the system bool internal immutable doValidateBalance; /// @notice The self address, set at initialization to allow proper share accounting address internal immutable self; /// @notice The underlying asset of the strategy IERC20 public immutable override underlying; /* ========== CONSTRUCTOR ========== */ /** * @notice Initializes the base strategy values. * * @dev * It performs certain pre-conditional validations to ensure the contract * has been initialized properly, such as that the address argument of the * underlying asset is valid. * * Slippage slots for certain strategies may be zero if there is no compounding * work to be done. * * @param _underlying token used for deposits * @param _rewardSlippageSlots slots for rewards * @param _processSlippageSlots slots for processing * @param _reallocationSlippageSlots slots for reallocation * @param _depositSlippageSlots slots for deposits * @param _forceClaim force claim of rewards * @param _doValidateBalance force balance validation */ constructor( IERC20 _underlying, uint256 _rewardSlippageSlots, uint256 _processSlippageSlots, uint256 _reallocationSlippageSlots, uint256 _depositSlippageSlots, bool _forceClaim, bool _doValidateBalance ) { require( _underlying != IERC20(address(0)), "BaseStrategy::constructor: Underlying address cannot be 0" ); self = address(this); underlying = _underlying; rewardSlippageSlots = _rewardSlippageSlots; processSlippageSlots = _processSlippageSlots; reallocationSlippageSlots = _reallocationSlippageSlots; depositSlippageSlots = _depositSlippageSlots; forceClaim = _forceClaim; doValidateBalance = _doValidateBalance; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Process the latest pending action of the strategy * * @dev * it yields amount of funds processed as well as the reward buffer of the strategy. * The function will auto-compound rewards if requested and supported. * * Requirements: * * - the slippages provided must be valid in length * - if the redeposit flag is set to true, the strategy must support * compounding of rewards * * @param slippages slippages to process * @param redeposit if redepositing is to occur * @param swapData swap data for processing */ function process(uint256[] calldata slippages, bool redeposit, SwapData[] calldata swapData) external override { slippages = _validateStrategyBalance(slippages); if (forceClaim || redeposit) { _validateRewardsSlippage(swapData); _processRewards(swapData); } if (processSlippageSlots != 0) _validateProcessSlippage(slippages); _process(slippages, 0); } /** * @notice Process first part of the reallocation DHW * @dev Withdraws for reallocation, depositn and withdraww for a user * * @param slippages Parameters to apply when performing a deposit or a withdraw * @param processReallocationData Data containing amuont of optimized and not optimized shares to withdraw * @return withdrawnReallocationReceived actual amount recieveed from peforming withdraw */ function processReallocation(uint256[] calldata slippages, ProcessReallocationData calldata processReallocationData) external override returns(uint128) { slippages = _validateStrategyBalance(slippages); if (reallocationSlippageSlots != 0) _validateReallocationSlippage(slippages); _process(slippages, processReallocationData.sharesToWithdraw); uint128 withdrawnReallocationReceived = _updateReallocationWithdraw(processReallocationData); return withdrawnReallocationReceived; } /** * @dev Update reallocation batch storage for index after withdrawing reallocated shares * @param processReallocationData Data containing amount of optimized and not optimized shares to withdraw * @return Withdrawn reallocation received */ function _updateReallocationWithdraw(ProcessReallocationData calldata processReallocationData) internal virtual returns(uint128) { Strategy storage strategy = strategies[self]; uint24 stratIndex = _getProcessingIndex(); BatchReallocation storage batch = strategy.reallocationBatches[stratIndex]; // save actual withdrawn amount, without optimized one uint128 withdrawnReallocationReceived = batch.withdrawnReallocationReceived; strategy.optimizedSharesWithdrawn += processReallocationData.optimizedShares; batch.withdrawnReallocationReceived += processReallocationData.optimizedWithdrawnAmount; batch.withdrawnReallocationShares = processReallocationData.optimizedShares + processReallocationData.sharesToWithdraw; return withdrawnReallocationReceived; } /** * @notice Process deposit * @param slippages Array of slippage parameters to apply when depositing */ function processDeposit(uint256[] calldata slippages) external override { slippages = _validateStrategyBalance(slippages); if (depositSlippageSlots != 0) _validateDepositSlippage(slippages); _processDeposit(slippages); } /** * @notice Returns total starategy balance includign pending rewards * @return strategyBalance total starategy balance includign pending rewards */ function getStrategyUnderlyingWithRewards() public view override returns(uint128) { return _getStrategyUnderlyingWithRewards(); } /** * @notice Fast withdraw * @param shares Shares to fast withdraw * @param slippages Array of slippage parameters to apply when withdrawing * @param swapData Swap slippage and path array * @return Withdrawn amount withdawn */ function fastWithdraw(uint128 shares, uint256[] calldata slippages, SwapData[] calldata swapData) external override returns(uint128) { slippages = _validateStrategyBalance(slippages); _validateRewardsSlippage(swapData); if (processSlippageSlots != 0) _validateProcessSlippage(slippages); uint128 withdrawnAmount = _processFastWithdraw(shares, slippages, swapData); strategies[self].totalShares -= shares; return withdrawnAmount; } /** * @notice Claims and possibly compounds strategy rewards. * * @param swapData swap data for processing */ function claimRewards(SwapData[] calldata swapData) external override { _validateRewardsSlippage(swapData); _processRewards(swapData); } /** * @notice Withdraws all actively deployed funds in the strategy, liquifying them in the process. * * @param recipient recipient of the withdrawn funds * @param data data necessary execute the emergency withdraw */ function emergencyWithdraw(address recipient, uint256[] calldata data) external virtual override { uint256 balanceBefore = underlying.balanceOf(address(this)); _emergencyWithdraw(recipient, data); uint256 balanceAfter = underlying.balanceOf(address(this)); uint256 withdrawnAmount = 0; if (balanceAfter > balanceBefore) { withdrawnAmount = balanceAfter - balanceBefore; } Strategy storage strategy = strategies[self]; if (strategy.emergencyPending > 0) { withdrawnAmount += strategy.emergencyPending; strategy.emergencyPending = 0; } // also withdraw all unprocessed deposit for a strategy if (strategy.pendingUser.deposit.get() > 0) { withdrawnAmount += strategy.pendingUser.deposit.get(); strategy.pendingUser.deposit = 0; } if (strategy.pendingUserNext.deposit.get() > 0) { withdrawnAmount += strategy.pendingUserNext.deposit.get(); strategy.pendingUserNext.deposit = 0; } // if strategy was already processed in the current index that hasn't finished yet, // transfer the withdrawn amount // reset total underlying to 0 if (strategy.index == globalIndex && doHardWorksLeft > 0) { uint256 withdrawnReceived = strategy.batches[strategy.index].withdrawnReceived; withdrawnAmount += withdrawnReceived; strategy.batches[strategy.index].withdrawnReceived = 0; strategy.totalUnderlying[strategy.index].amount = 0; } if (withdrawnAmount > 0) { // check if the balance is high enough to withdraw the total withdrawnAmount if (balanceAfter < withdrawnAmount) { // if not withdraw the current balance withdrawnAmount = balanceAfter; } underlying.safeTransfer(recipient, withdrawnAmount); } } /** * @notice Initialize a strategy. * @dev Execute strategy specific one-time actions if needed. */ function initialize() external virtual override {} /** * @notice Disables a strategy. * @dev Cleans strategy specific values if needed. */ function disable() external virtual override {} /* ========== INTERNAL FUNCTIONS ========== */ /** * @dev Validate strategy balance * @param slippages Check if the strategy balance is within defined min and max values * @return slippages Same array without first 2 slippages */ function _validateStrategyBalance(uint256[] calldata slippages) internal virtual returns(uint256[] calldata) { if (doValidateBalance) { require(slippages.length >= 2, "BaseStrategy:: _validateStrategyBalance: Invalid number of slippages"); uint128 strategyBalance = getStrategyBalance(); require( slippages[0] <= strategyBalance && slippages[1] >= strategyBalance, "BaseStrategy::_validateStrategyBalance: Bad strategy balance" ); return slippages[2:]; } return slippages; } /** * @dev Validate reards slippage * @param swapData Swap slippage and path array */ function _validateRewardsSlippage(SwapData[] calldata swapData) internal view virtual { if (swapData.length > 0) { require( swapData.length == _getRewardSlippageSlots(), "BaseStrategy::_validateSlippage: Invalid Number of reward slippages Defined" ); } } /** * @dev Retrieve reward slippage slots * @return Reward slippage slots */ function _getRewardSlippageSlots() internal view virtual returns(uint256) { return rewardSlippageSlots; } /** * @dev Validate process slippage * @param slippages parameters to verify validity of the strategy state */ function _validateProcessSlippage(uint256[] calldata slippages) internal view virtual { _validateSlippage(slippages.length, processSlippageSlots); } /** * @dev Validate reallocation slippage * @param slippages parameters to verify validity of the strategy state */ function _validateReallocationSlippage(uint256[] calldata slippages) internal view virtual { _validateSlippage(slippages.length, reallocationSlippageSlots); } /** * @dev Validate deposit slippage * @param slippages parameters to verify validity of the strategy state */ function _validateDepositSlippage(uint256[] calldata slippages) internal view virtual { _validateSlippage(slippages.length, depositSlippageSlots); } /** * @dev Validates the provided slippage in length. * @param currentLength actual slippage array length * @param shouldBeLength expected slippages array length */ function _validateSlippage(uint256 currentLength, uint256 shouldBeLength) internal view virtual { require( currentLength == shouldBeLength, "BaseStrategy::_validateSlippage: Invalid Number of Slippages Defined" ); } /** * @dev Retrieve processing index * @return Processing index */ function _getProcessingIndex() internal view returns(uint24) { return strategies[self].index + 1; } /** * @dev Calculates shares before they are added to the total shares * @param strategyTotalShares Total shares for strategy * @param stratTotalUnderlying Total underlying for strategy * @return newShares New shares calculated */ function _getNewSharesAfterWithdraw(uint128 strategyTotalShares, uint128 stratTotalUnderlying, uint128 depositAmount) internal pure returns(uint128 newShares){ uint128 oldUnderlying; if (stratTotalUnderlying > depositAmount) { oldUnderlying = stratTotalUnderlying - depositAmount; } if (strategyTotalShares == 0 || oldUnderlying == 0) { // Enforce minimum shares size to avoid loss of share due to computation precision newShares = (0 < depositAmount && depositAmount < MIN_SHARES) ? MIN_SHARES : depositAmount; } else { newShares = Math.getProportion128(depositAmount, strategyTotalShares, oldUnderlying); } } /** * @dev Calculates shares when they are already part of the total shares * * @param strategyTotalShares Total shares * @param stratTotalUnderlying Total underlying * @return newShares New shares calculated */ function _getNewShares(uint128 strategyTotalShares, uint128 stratTotalUnderlying, uint128 depositAmount) internal pure returns(uint128 newShares){ if (strategyTotalShares == 0 || stratTotalUnderlying == 0) { // Enforce minimum shares size to avoid loss of share due to computation precision newShares = (0 < depositAmount && depositAmount < MIN_SHARES) ? MIN_SHARES : depositAmount; } else { newShares = Math.getProportion128(depositAmount, strategyTotalShares, stratTotalUnderlying); } } /** * @dev Reset allowance to zero if previously set to a higher value. * @param token Asset * @param spender Spender address */ function _resetAllowance(IERC20 token, address spender) internal { if (token.allowance(address(this), spender) > 0) { token.safeApprove(spender, 0); } } /* ========== VIRTUAL FUNCTIONS ========== */ function getStrategyBalance() public view virtual override returns (uint128); function _processRewards(SwapData[] calldata) internal virtual; function _emergencyWithdraw(address recipient, uint256[] calldata data) internal virtual; function _process(uint256[] memory, uint128 reallocateSharesToWithdraw) internal virtual; function _processDeposit(uint256[] memory) internal virtual; function _getStrategyUnderlyingWithRewards() internal view virtual returns(uint128); function _processFastWithdraw(uint128, uint256[] memory, SwapData[] calldata) internal virtual returns(uint128); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./RewardStrategy.sol"; import "../shared/SwapHelperMainnet.sol"; /** * @notice Claim full single reward strategy logic */ abstract contract ClaimFullSingleRewardStrategy is RewardStrategy, SwapHelperMainnet { /* ========== STATE VARIABLES ========== */ IERC20 internal immutable rewardToken; /* ========== CONSTRUCTOR ========== */ /** * @notice Set initial values * @param _rewardToken Reward token contract */ constructor( IERC20 _rewardToken ) { require(address(_rewardToken) != address(0), "ClaimFullSingleRewardStrategy::constructor: Token address cannot be 0"); rewardToken = _rewardToken; } /* ========== OVERRIDDEN FUNCTIONS ========== */ /** * @notice Claim rewards * @param swapData Slippage and path array * @return Rewards */ function _claimRewards(SwapData[] calldata swapData) internal override returns(Reward[] memory) { return _claimSingleRewards(type(uint128).max, swapData); } /** * @dev Claim fast withdraw rewards * @param shares Amount of shares * @param swapData Swap slippage and path * @return Rewards */ function _claimFastWithdrawRewards(uint128 shares, SwapData[] calldata swapData) internal override returns(Reward[] memory) { return _claimSingleRewards(shares, swapData); } /* ========== PRIVATE FUNCTIONS ========== */ /** * @dev Claim single rewards * @param shares Amount of shares * @param swapData Swap slippage and path * @return rewards Collected reward amounts */ function _claimSingleRewards(uint128 shares, SwapData[] calldata swapData) private returns(Reward[] memory rewards) { if (swapData.length > 0 && swapData[0].slippage > 0) { uint128 rewardAmount = _claimStrategyReward(); if (rewardAmount > 0) { Strategy storage strategy = strategies[self]; uint128 claimedAmount = _getRewardClaimAmount(shares, rewardAmount); rewards = new Reward[](1); rewards[0] = Reward(claimedAmount, rewardToken); // if we don't claim all the rewards save the amount left, otherwise reset amount left to 0 if (rewardAmount > claimedAmount) { uint128 rewardAmountLeft = rewardAmount - claimedAmount; strategy.pendingRewards[address(rewardToken)] = rewardAmountLeft; } else if (strategy.pendingRewards[address(rewardToken)] > 0) { strategy.pendingRewards[address(rewardToken)] = 0; } } } } /* ========== VIRTUAL FUNCTIONS ========== */ function _claimStrategyReward() internal virtual returns(uint128); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./BaseStrategy.sol"; import "../libraries/Max/128Bit.sol"; import "../libraries/Math.sol"; struct ProcessInfo { uint128 totalWithdrawReceived; uint128 userDepositReceived; } /** * @notice Process strategy logic */ abstract contract ProcessStrategy is BaseStrategy { using Max128Bit for uint128; /* ========== OVERRIDDEN FUNCTIONS ========== */ /** * @notice Process the strategy pending deposits, withdrawals, and collected strategy rewards * @dev * Deposit amount amd withdrawal shares are matched between eachother, effecively only one of * those 2 is called. Shares are converted to the dollar value, based on the current strategy * total balance. This ensures the minimum amount of assets are moved around to lower the price * drift and total fees paid to the protocols the strategy is interacting with (if there are any) * * @param slippages Strategy slippage values verifying the validity of the strategy state * @param reallocateSharesToWithdraw Reallocation shares to withdraw (non-zero only if reallocation DHW is in progress, otherwise 0) */ function _process(uint256[] memory slippages, uint128 reallocateSharesToWithdraw) internal override virtual { // PREPARE Strategy storage strategy = strategies[self]; uint24 processingIndex = _getProcessingIndex(); Batch storage batch = strategy.batches[processingIndex]; uint128 strategyTotalShares = strategy.totalShares; uint128 pendingSharesToWithdraw = strategy.pendingUser.sharesToWithdraw.get(); uint128 userDeposit = strategy.pendingUser.deposit.get(); // CALCULATE THE ACTION // if withdrawing for reallocating, add shares to total withdraw shares if (reallocateSharesToWithdraw > 0) { pendingSharesToWithdraw += reallocateSharesToWithdraw; } // total deposit received from users + compound reward (if there are any) uint128 totalPendingDeposit = userDeposit; // add compound reward (pendingDepositReward) to deposit uint128 withdrawalReward = 0; if (strategy.pendingDepositReward > 0) { uint128 pendingDepositReward = strategy.pendingDepositReward; totalPendingDeposit += pendingDepositReward; // calculate compound reward (withdrawalReward) for users withdrawing in this batch if (pendingSharesToWithdraw > 0 && strategyTotalShares > 0) { withdrawalReward = Math.getProportion128(pendingSharesToWithdraw, pendingDepositReward, strategyTotalShares); // substract withdrawal reward from total deposit totalPendingDeposit -= withdrawalReward; } // Reset pendingDepositReward strategy.pendingDepositReward = 0; } // if there is no pending deposit or withdrawals, return if (totalPendingDeposit == 0 && pendingSharesToWithdraw == 0) { return; } uint128 pendingWithdrawalAmount = 0; if (pendingSharesToWithdraw > 0) { pendingWithdrawalAmount = Math.getProportion128(getStrategyBalance(), pendingSharesToWithdraw, strategyTotalShares); } // ACTION: DEPOSIT OR WITHDRAW ProcessInfo memory processInfo; if (totalPendingDeposit > pendingWithdrawalAmount) { // DEPOSIT // uint128 amount = totalPendingDeposit - pendingWithdrawalAmount; uint128 depositReceived = _deposit(totalPendingDeposit - pendingWithdrawalAmount, slippages); processInfo.totalWithdrawReceived = pendingWithdrawalAmount + withdrawalReward; // pendingWithdrawalAmount is optimized deposit: totalPendingDeposit - amount; uint128 totalDepositReceived = depositReceived + pendingWithdrawalAmount; // calculate user deposit received, excluding compound rewards processInfo.userDepositReceived = Math.getProportion128(totalDepositReceived, userDeposit, totalPendingDeposit); } else if (totalPendingDeposit < pendingWithdrawalAmount) { // WITHDRAW // uint128 amount = pendingWithdrawalAmount - totalPendingDeposit; uint128 withdrawReceived = _withdraw( // calculate back the shares from actual withdraw amount // NOTE: we can do unchecked calculation and casting as // the multiplier is always smaller than the divisor Math.getProportion128Unchecked( (pendingWithdrawalAmount - totalPendingDeposit), pendingSharesToWithdraw, pendingWithdrawalAmount ), slippages ); // optimized withdraw is total pending deposit: pendingWithdrawalAmount - amount = totalPendingDeposit; processInfo.totalWithdrawReceived = withdrawReceived + totalPendingDeposit + withdrawalReward; processInfo.userDepositReceived = userDeposit; } else { processInfo.totalWithdrawReceived = pendingWithdrawalAmount + withdrawalReward; processInfo.userDepositReceived = userDeposit; } // UPDATE STORAGE AFTER { uint128 stratTotalUnderlying = getStrategyBalance(); // Update withdraw batch if (pendingSharesToWithdraw > 0) { batch.withdrawnReceived = processInfo.totalWithdrawReceived; batch.withdrawnShares = pendingSharesToWithdraw; strategyTotalShares -= pendingSharesToWithdraw; // update reallocation batch if (reallocateSharesToWithdraw > 0) { BatchReallocation storage reallocationBatch = strategy.reallocationBatches[processingIndex]; uint128 withdrawnReallocationReceived = Math.getProportion128(processInfo.totalWithdrawReceived, reallocateSharesToWithdraw, pendingSharesToWithdraw); reallocationBatch.withdrawnReallocationReceived = withdrawnReallocationReceived; // substract reallocation values from user values batch.withdrawnReceived -= withdrawnReallocationReceived; batch.withdrawnShares -= reallocateSharesToWithdraw; } } // Update deposit batch if (userDeposit > 0) { uint128 newShares = _getNewSharesAfterWithdraw(strategyTotalShares, stratTotalUnderlying, processInfo.userDepositReceived); batch.deposited = userDeposit; batch.depositedReceived = processInfo.userDepositReceived; batch.depositedSharesReceived = newShares; strategyTotalShares += newShares; } // Update shares if (strategyTotalShares != strategy.totalShares) { strategy.totalShares = strategyTotalShares; } // Set underlying at index strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying; strategy.totalUnderlying[processingIndex].totalShares = strategyTotalShares; } } /** * @notice Process deposit * @param slippages Slippages array */ function _processDeposit(uint256[] memory slippages) internal override virtual { Strategy storage strategy = strategies[self]; uint128 depositOptimizedAmount = strategy.pendingReallocateOptimizedDeposit; uint128 optimizedSharesWithdrawn = strategy.optimizedSharesWithdrawn; uint128 depositAmount = strategy.pendingReallocateDeposit; // if a strategy is not part of reallocation return if ( depositOptimizedAmount == 0 && optimizedSharesWithdrawn == 0 && depositAmount == 0 ) { return; } uint24 processingIndex = _getProcessingIndex(); BatchReallocation storage reallocationBatch = strategy.reallocationBatches[processingIndex]; uint128 strategyTotalShares = strategy.totalShares; // get shares from optimized deposit if (depositOptimizedAmount > 0) { uint128 stratTotalUnderlying = getStrategyBalance(); uint128 newShares = _getNewShares(strategyTotalShares, stratTotalUnderlying, depositOptimizedAmount); // add new shares strategyTotalShares += newShares; // update reallocation batch reallocationBatch.depositedReallocation = depositOptimizedAmount; reallocationBatch.depositedReallocationSharesReceived = newShares; strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying; // reset strategy.pendingReallocateOptimizedDeposit = 0; } // remove optimized withdraw shares if (optimizedSharesWithdrawn > 0) { strategyTotalShares -= optimizedSharesWithdrawn; // reset strategy.optimizedSharesWithdrawn = 0; } // get shares from actual deposit if (depositAmount > 0) { // deposit uint128 depositReceived = _deposit(depositAmount, slippages); // NOTE: might return it from _deposit (only certain strategies need it) uint128 stratTotalUnderlying = getStrategyBalance(); uint128 newShares = _getNewSharesAfterWithdraw(strategyTotalShares, stratTotalUnderlying, depositReceived); // add new shares strategyTotalShares += newShares; // update reallocation batch reallocationBatch.depositedReallocation += depositReceived; reallocationBatch.depositedReallocationSharesReceived += newShares; strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying; // reset strategy.pendingReallocateDeposit = 0; } // update share storage strategy.totalUnderlying[processingIndex].totalShares = strategyTotalShares; strategy.totalShares = strategyTotalShares; } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice get the value of the strategy shares in the underlying tokens * @param shares Number of shares * @return amount Underling amount representing the `share` value of the strategy */ function _getSharesToAmount(uint256 shares) internal virtual returns(uint128 amount) { amount = Math.getProportion128( getStrategyBalance(), shares, strategies[self].totalShares ); } /** * @notice get slippage amount, and action type (withdraw/deposit). * @dev * Most significant bit represents an action, 0 for a withdrawal and 1 for deposit. * * This ensures the slippage will be used for the action intended by the do-hard-worker, * otherwise the transavtion will revert. * * @param slippageAction number containing the slippage action and the actual slippage amount * @return isDeposit Flag showing if the slippage is for the deposit action * @return slippage the slippage value cleaned of the most significant bit */ function _getSlippageAction(uint256 slippageAction) internal pure returns (bool isDeposit, uint256 slippage) { // remove most significant bit slippage = (slippageAction << 1) >> 1; // if values are not the same (the removed bit was 1) set action to deposit if (slippageAction != slippage) { isDeposit = true; } } /* ========== VIRTUAL FUNCTIONS ========== */ function _deposit(uint128 amount, uint256[] memory slippages) internal virtual returns(uint128 depositReceived); function _withdraw(uint128 shares, uint256[] memory slippages) internal virtual returns(uint128 withdrawReceived); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./ProcessStrategy.sol"; import "../shared/SwapHelper.sol"; struct Reward { uint256 amount; IERC20 token; } /** * @notice Reward strategy logic */ abstract contract RewardStrategy is ProcessStrategy, SwapHelper { /* ========== OVERRIDDEN FUNCTIONS ========== */ /** * @notice Gey strategy underlying asset with rewards * @return Total underlying */ function _getStrategyUnderlyingWithRewards() internal view override virtual returns(uint128) { Strategy storage strategy = strategies[self]; uint128 totalUnderlying = getStrategyBalance(); totalUnderlying += strategy.pendingDepositReward; return totalUnderlying; } /** * @notice Process an instant withdrawal from the protocol per users request. * * @param shares Amount of shares * @param slippages Array of slippages * @param swapData Data used in processing * @return Withdrawn amount */ function _processFastWithdraw(uint128 shares, uint256[] memory slippages, SwapData[] calldata swapData) internal override virtual returns(uint128) { uint128 withdrawRewards = _processFastWithdrawalRewards(shares, swapData); uint128 withdrawReceived = _withdraw(shares, slippages); return withdrawReceived + withdrawRewards; } /** * @notice Process rewards * @param swapData Data used in processing */ function _processRewards(SwapData[] calldata swapData) internal override virtual { Strategy storage strategy = strategies[self]; Reward[] memory rewards = _claimRewards(swapData); uint128 collectedAmount = _sellRewards(rewards, swapData); if (collectedAmount > 0) { strategy.pendingDepositReward += collectedAmount; } } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice Process fast withdrawal rewards * @param shares Amount of shares * @param swapData Values used for swapping the rewards * @return withdrawalRewards Withdrawal rewards */ function _processFastWithdrawalRewards(uint128 shares, SwapData[] calldata swapData) internal virtual returns(uint128 withdrawalRewards) { Strategy storage strategy = strategies[self]; Reward[] memory rewards = _claimFastWithdrawRewards(shares, swapData); withdrawalRewards += _sellRewards(rewards, swapData); if (strategy.pendingDepositReward > 0) { uint128 fastWithdrawCompound = Math.getProportion128(strategy.pendingDepositReward, shares, strategy.totalShares); if (fastWithdrawCompound > 0) { strategy.pendingDepositReward -= fastWithdrawCompound; withdrawalRewards += fastWithdrawCompound; } } } /** * @notice Sell rewards to the underlying token * @param rewards Rewards to sell * @param swapData Values used for swapping the rewards * @return collectedAmount Collected underlying amount */ function _sellRewards(Reward[] memory rewards, SwapData[] calldata swapData) internal virtual returns(uint128 collectedAmount) { for (uint256 i = 0; i < rewards.length; i++) { // add compound amount from current batch to the fast withdraw if (rewards[i].amount > 0) { uint128 compoundAmount = SafeCast.toUint128( _approveAndSwap( rewards[i].token, underlying, rewards[i].amount, swapData[i] ) ); // add to pending reward collectedAmount += compoundAmount; } } } /** * @notice Get reward claim amount for `shares` * @param shares Amount of shares * @param rewardAmount Total reward amount * @return rewardAmount Amount of reward for the shares */ function _getRewardClaimAmount(uint128 shares, uint256 rewardAmount) internal virtual view returns(uint128) { // for do hard work claim everything if (shares == type(uint128).max) { return SafeCast.toUint128(rewardAmount); } else { // for fast withdrawal claim calculate user withdraw amount return SafeCast.toUint128((rewardAmount * shares) / strategies[self].totalShares); } } /* ========== VIRTUAL FUNCTIONS ========== */ function _claimFastWithdrawRewards(uint128 shares, SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards); function _claimRewards(SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../ClaimFullSingleRewardStrategy.sol"; import "../../external/interfaces/harvest/Vault/IHarvestVault.sol"; import "../../external/interfaces/harvest/IHarvestPool.sol"; /** * @notice Harvest strategy implementation */ contract HarvestStrategy is ClaimFullSingleRewardStrategy { using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ /// @notice Harvest vault contract IHarvestVault public immutable vault; /// @notice Harvest pool contract IHarvestPool public immutable pool; /* ========== CONSTRUCTOR ========== */ /** * @notice Set initial values * @param _farm Farm contract * @param _vault Vault contract * @param _pool Pool contract * @param _underlying Underlying asset */ constructor( IERC20 _farm, IHarvestVault _vault, IHarvestPool _pool, IERC20 _underlying ) BaseStrategy(_underlying, 1, 0, 0, 0, false, false) ClaimFullSingleRewardStrategy(_farm) { require(address(_vault) != address(0), "HarvestStrategy::constructor: Vault address cannot be 0"); require(address(_pool) != address(0), "HarvestStrategy::constructor: Pool address cannot be 0"); vault = _vault; pool = _pool; } /* ========== VIEWS ========== */ /** * @notice Get strategy balance * @return Strategy balance */ function getStrategyBalance() public view override returns(uint128) { uint256 fTokenBalance = pool.balanceOf(address(this)); return SafeCast.toUint128(_getfTokenValue(fTokenBalance)); } /* ========== OVERRIDDEN FUNCTIONS ========== */ /** * @dev Claim strategy reward * @return Reward amount */ function _claimStrategyReward() internal override returns(uint128) { // claim uint256 rewardBefore = rewardToken.balanceOf(address(this)); pool.getReward(); uint256 rewardAmount = rewardToken.balanceOf(address(this)) - rewardBefore; // add already claimed rewards rewardAmount += strategies[self].pendingRewards[address(rewardToken)]; return SafeCast.toUint128(rewardAmount); } /** * @dev Deposit * @param amount Amount to deposit * @return Deposited amount */ function _deposit(uint128 amount, uint256[] memory) internal override returns(uint128) { // deposit underlying underlying.safeApprove(address(vault), amount); uint256 fTokenBefore = vault.balanceOf(address(this)); vault.deposit(amount); uint256 fTokenNew = vault.balanceOf(address(this)) - fTokenBefore; _resetAllowance(underlying, address(vault)); // stake fTokens vault.approve(address(pool), fTokenNew); pool.stake(fTokenNew); return SafeCast.toUint128(_getfTokenValue(fTokenNew)); } /** * @dev Withdraw * @param shares Shares to withdraw * @return Withdrawn amount */ function _withdraw(uint128 shares, uint256[] memory) internal override returns(uint128) { uint256 fTokensTotal = pool.balanceOf(address(this)); uint256 fWithdrawAmount = (fTokensTotal * shares) / strategies[self].totalShares; // withdraw staked fTokens from pool pool.withdraw(fWithdrawAmount); // withdraw fTokens from vault uint256 undelyingBefore = underlying.balanceOf(address(this)); vault.withdraw(fWithdrawAmount); uint256 undelyingWithdrawn = underlying.balanceOf(address(this)) - undelyingBefore; return SafeCast.toUint128(undelyingWithdrawn); } /** * @dev Emergency withdraw */ function _emergencyWithdraw(address, uint256[] calldata) internal override { pool.exit(); vault.withdraw(vault.balanceOf(address(this))); } /* ========== PRIVATE FUNCTIONS ========== */ /** * @dev Return value of fTokens in the underlying asset * @param fTokenAmount Amount of fTokens * @return value in the underlying asset */ function _getfTokenValue(uint256 fTokenAmount) private view returns(uint256) { if (fTokenAmount == 0) return 0; uint256 vaultTotal = vault.underlyingBalanceWithInvestment(); return (vaultTotal * fTokenAmount) / vault.totalSupply(); } }
Returns total starategy balance includign pending rewards return strategyBalance total starategy balance includign pending rewards/
function getStrategyUnderlyingWithRewards() public view override returns(uint128) { return _getStrategyUnderlyingWithRewards(); }
18,124
./partial_match/1/0x85F66f5Ee2435bDCbE12c115bFd592462ECbDb5c/sources/MakerDaoGateway.sol
don't forget to approve DAI before repaying pass -1 to daiAmount to repay all outstanding debt repay all outstanding debt
function repayDai(bytes32 cdpId, uint daiAmount, bool payFeeInDai) whenNotPaused isCdpOwner(cdpId) public { if (daiAmount > 0) { uint _daiAmount = daiAmount; if (_daiAmount == uint(- 1)) { _daiAmount = saiTub.tab(cdpId); } _ensureApproval(dai, address(saiTub)); _ensureApproval(mkr, address(saiTub)); uint govFeeAmount = _calcGovernanceFee(cdpId, _daiAmount); _handleGovFee(govFeeAmount, payFeeInDai); require(dai.transferFrom(msg.sender, address(this), _daiAmount)); saiTub.wipe(cdpId, _daiAmount); emit DaiRepaid(msg.sender, cdpId, _daiAmount); } }
3,900,974
./partial_match/1/0xaCCaaDc4F8448F5f6C6aAf1c639Ec4B8bD1A8aF4/sources/contracts/extensions/NFT/components/ERC721FU.sol
Underflow of the sender's balance is impossible because we check for ownership above and the recipient's balance can't realistically overflow.
function transferFrom( address from, address to, uint256 id ) public virtual { require(from == _ownerOf[id], 'WRONG_FROM'); require(to != address(0), 'INVALID_RECIPIENT'); require( msg.sender == from || isApprovedForAll[from][msg.sender] || msg.sender == getApproved[id], 'NOT_AUTHORIZED' ); unchecked { _balanceOf[from]--; _balanceOf[to]++; } _ownerOf[id] = to; delete getApproved[id]; emit Transfer(from, to, id); }
2,702,241
pragma solidity ^0.4.24; import "../common/Active.sol"; import "../common/SafeMathLib.sol"; import "../common/Manageable.sol"; import "../token/IERC20Token.sol"; import "../common/EtherHolder.sol"; import "./IProductStorage.sol"; import "./IEscrow.sol"; import "./IFeePolicy.sol"; import "./IPurchaseHandler.sol"; import "./IDiscountPolicy.sol"; import "./IBancorConverter.sol"; import "./IEtherPriceProvider.sol"; import "./IRevokedStorage.sol"; /**@dev This contact accepts payments for products and transfers ether to all the parties */ contract ProductPayment is EtherHolder, Active { using SafeMathLib for uint256; // //Events //emitted during purchase process. Id is 0-based index of purchase in the engine.purchases array event ProductBought( address indexed buyer, address indexed vendor, uint256 indexed productId, uint256 purchaseId, string clientId, uint256 price, uint256 paidUnits, uint256 discount ); //emitted in revoke function event PurchaseRevoked(address indexed vendor, uint256 indexed productId, uint256 purchaseId); //emitted in resolve function event DisputeResolved( address indexed escrow, uint256 indexed productId, uint256 indexed purchaseId, uint8 refundPct ); //emitted in complain function event ComplainMade( address indexed vendor, address indexed customer, uint256 indexed productId, uint256 purchaseId ); event DeliverConfirmed(address indexed customer, uint256 indexed productId, uint256 purchaseId); // // Storage data IProductStorage public productStorage; IEscrow public escrowProvider; IFeePolicy public feePolicy; IDiscountPolicy public discountPolicy; IRevokedStorage public revokedStorage; //contract that stores ether/usd exchange rate IEtherPriceProvider public etherPriceProvider; //token that can be used as payment tool IERC20Token public token; // Bancor converter to convert BCS to ETH. IBancorConverter public converter; // escrow payment hold time in seconds address[] public convertPath; // // Methods constructor( IProductStorage _productStorage, IEscrow _escrowProvider, IFeePolicy _feePolicy, IDiscountPolicy _discountPolicy, IRevokedStorage _revokedStorage, IERC20Token _token, IEtherPriceProvider _etherPriceProvider ) public { setParams(_productStorage, _escrowProvider, _feePolicy, _discountPolicy, _revokedStorage, _token, _etherPriceProvider); } //allows to receive direct ether transfers function() public payable {} /**@dev Sets convert path for changing BCS to ETH through Bancor */ function setConvertParams(IBancorConverter _converter, address[] _convertPath) public ownerOnly { converter = _converter; convertPath = _convertPath; } /**@dev Changes parameters */ function setParams( IProductStorage _productStorage, IEscrow _escrowProvider, IFeePolicy _feePolicy, IDiscountPolicy _discountPolicy, IRevokedStorage _revokedStorage, IERC20Token _token, IEtherPriceProvider _etherPriceProvider ) public ownerOnly { productStorage = _productStorage; escrowProvider = _escrowProvider; feePolicy = _feePolicy; discountPolicy = _discountPolicy; revokedStorage = _revokedStorage; token = _token; etherPriceProvider = _etherPriceProvider; } function getUnitsToBuy(uint256 productId, uint256 units, bool acceptLessUnits) public view returns(uint256) { (uint256 price, uint256 maxUnits, uint256 soldUnits) = productStorage.getProductData(productId); //if product is limited and it's not enough to buy, check acceptLessUnits flag if (maxUnits > 0 && soldUnits.safeAdd(units) > maxUnits) { if (acceptLessUnits) { return maxUnits.safeSub(soldUnits); } else { return 0; //set to 0 so it will fail later } } else { return units; } } /**@dev Returns true if vendor profit can be withdrawn */ function canWithdrawPending(uint256 productId, uint256 purchaseId) public view returns(bool) { IProductStorage.PurchaseState state = productStorage.getPurchase(productId, purchaseId); (address customer, uint256 fee, uint256 profit, uint256 timestamp) = productStorage.getEscrowData(productId, purchaseId); return state == IProductStorage.PurchaseState.Pending || (state == IProductStorage.PurchaseState.Paid && esrowHoldTimeElapsed(productId, purchaseId)); // return state == IProductStorage.PurchaseState.Pending // || (state == IProductStorage.PurchaseState.Paid && esrowHoldTimeElapsed(productId, purchaseId)); } /**@dev Returns true if escrow time elapsed */ function esrowHoldTimeElapsed(uint256 productId, uint256 purchaseId) public view returns (bool) { (address customer, uint256 fee, uint256 profit, uint256 timestamp) = productStorage.getEscrowData(productId, purchaseId); return timestamp + escrowProvider.getProductEscrowHoldTime(productId) <= now; } /**@dev Buys product. Send ether with this function in amount equal to desirable product units * current price. */ function buyWithEth( uint256 productId, uint256 units, string clientId, bool acceptLessUnits, uint256 currentPrice ) public payable { buy(msg.value, productId, units, clientId, acceptLessUnits, currentPrice); } /**@dev Buys product using BCS tokens as a payment. 1st parameter is the amount of tokens that will be converted via bancor. This can be calculated off-chain. Tokens should be approved for spending by this contract */ function buyWithTokens( uint256 tokens, uint256 productId, uint256 units, string clientId, bool acceptLessUnits, uint256 currentPrice ) public { //store bcsConverter, access via extensions IBancorQuickConverter quickConverter = converter.extensions().quickConverter(); token.transferFrom(msg.sender, quickConverter, tokens); uint256 ethAmount = quickConverter.convertFor(convertPath, tokens, 1, this); //use received ether for payment buy(ethAmount, productId, units, clientId, acceptLessUnits, currentPrice); } /**@dev Make a complain on purchase, only customer can call this method */ function complain(uint256 productId, uint256 purchaseId) public activeOnly { (address customer, uint256 fee, uint256 profit, uint256 timestamp) = productStorage.getEscrowData(productId, purchaseId); uint256 escrowHoldTime = escrowProvider.getProductEscrowHoldTime(productId); //check purchase current state, valid customer and time limits require( productStorage.getPurchase(productId, purchaseId) == IProductStorage.PurchaseState.Paid && customer == msg.sender && timestamp + escrowHoldTime > now ); //change purchase status productStorage.changePurchase(productId, purchaseId, IProductStorage.PurchaseState.Complain); emit ComplainMade(productStorage.getProductOwner(productId), customer, productId, purchaseId); } /**@dev Confirms that purchase was delivered. Customer calls this to release escrow-locked funds to vendor */ function confirmDeliver(uint256 productId, uint256 purchaseId) public activeOnly { //check status is Paid require(productStorage.getPurchase(productId, purchaseId) == IProductStorage.PurchaseState.Paid); //check if msg.sender is valid customer (address customer, uint256 fee, uint256 profit, uint256 timestamp) = productStorage.getEscrowData(productId, purchaseId); require(msg.sender == customer); //change purchase state to Pending productStorage.changePurchase(productId, purchaseId, IProductStorage.PurchaseState.Pending); emit DeliverConfirmed(msg.sender, productId, purchaseId); } /**@dev Allows vendor to revoke purchase is it wasn't complained yet * Ether in amount of escrow fee should be attached */ function revoke(uint256 productId, uint256 purchaseId) public payable activeOnly { //check if its valid vendor require(msg.sender == productStorage.getProductOwner(productId)); //check state is Paid and hold time not elapsed require( productStorage.getPurchase(productId, purchaseId) == IProductStorage.PurchaseState.Paid && !esrowHoldTimeElapsed(productId, purchaseId) ); require(msg.value == revokedStorage.escrowFee(productId, purchaseId)); //change state productStorage.changePurchase(productId, purchaseId, IProductStorage.PurchaseState.Finished); revokedStorage.setRevokedFlag(productId, purchaseId, true); //return payment to customer (address customer, uint256 fee, uint256 profit, uint256 timestamp) = productStorage.getEscrowData(productId, purchaseId); customer.transfer(fee.safeAdd(profit).safeAdd(msg.value)); emit PurchaseRevoked(msg.sender, productId, purchaseId); } /**@dev Resolves a complain on specific purchase. If cancelPayment is true, payment returns to customer; otherwise - to the vendor refundPct - a percentage of merchant's profit to be sent to customer */ function resolve(uint256 productId, uint256 purchaseId, uint8 refundPct) public activeOnly { require(refundPct >= 0 && refundPct <= 100); //check escrow validity - product escrow or default escrow require( msg.sender == escrowProvider.getProductEscrow(productId) || msg.sender == escrowProvider.defaultEscrow() ); require(productStorage.getPurchase(productId, purchaseId) == IProductStorage.PurchaseState.Complain); (address customer, uint256 fee, uint256 profit, uint256 timestamp) = productStorage.getEscrowData(productId, purchaseId); if(refundPct > 0) { uint256 refundProfit = profit * refundPct / 100.0; uint256 refundFee = fee * refundPct / 100.0; profit = profit.safeSub(refundProfit); fee = fee.safeSub(refundFee); productStorage.setEscrowData(productId, purchaseId, customer, fee, profit, timestamp); customer.transfer(refundFee.safeAdd(refundProfit)); } productStorage.changePurchase( productId, purchaseId, refundPct < 100 ? IProductStorage.PurchaseState.Pending : IProductStorage.PurchaseState.Finished ); emit DisputeResolved(msg.sender, productId, purchaseId, refundPct); } /**@dev withdraws multiple pending payments */ function withdrawPendingPayments(uint256[] productIds, uint256[] purchaseIds) public activeOnly { require(productIds.length == purchaseIds.length); address customer; uint256 fee; uint256 profit; uint256 timestamp; uint256 totalProfit = 0; uint256 totalFee = 0; for(uint256 i = 0; i < productIds.length; ++i) { (customer, fee, profit, timestamp) = productStorage.getEscrowData(productIds[i], purchaseIds[i]); require(msg.sender == productStorage.getProductOwner(productIds[i])); require(canWithdrawPending(productIds[i], purchaseIds[i])); productStorage.changePurchase(productIds[i], purchaseIds[i], IProductStorage.PurchaseState.Finished); totalFee = totalFee.safeAdd(fee); totalProfit = totalProfit.safeAdd(profit); } productStorage.getVendorWallet(msg.sender).transfer(totalProfit); feePolicy.sendFee.value(totalFee)(msg.sender); } function buy( uint256 ethAmount, uint256 productId, uint256 units, string clientId, bool acceptLessUnits, uint256 currentPrice ) internal activeOnly { require(productId < productStorage.getTotalProducts()); require(!productStorage.banned(productId)); uint256 price = productStorage.getProductPrice(productId); //check for active flag and valid price require(productStorage.isProductActive(productId) && currentPrice == price); uint256 unitsToBuy = getUnitsToBuy(productId, units, acceptLessUnits); //check if there is enough units to buy require(unitsToBuy > 0); uint256 totalPrice = unitsToBuy.safeMult(price); //check fiat price usage if(productStorage.isFiatPriceUsed(productId)) { totalPrice = totalPrice.safeMult(etherPriceProvider.rate()); price = totalPrice / unitsToBuy; } uint256 cashback = discountPolicy.requestCustomerDiscount(msg.sender, totalPrice); //if there is not enough ether to pay even with discount, safeSub will throw exception uint256 etherToReturn = ethAmount.safeSub(totalPrice); uint256 purchaseId = productStorage.addPurchase(productId, msg.sender, price, unitsToBuy, clientId); processPurchase(productId, purchaseId, totalPrice); //transfer excess to customer if (etherToReturn > 0) { msg.sender.transfer(etherToReturn); } emit ProductBought( msg.sender, productStorage.getProductOwner(productId), productId, purchaseId, clientId, price, unitsToBuy, cashback ); } /**@dev Sends ether payment to all the parties */ function processPurchase(uint256 productId, uint256 purchaseId, uint256 etherToPay) internal { address owner = productStorage.getProductOwner(productId); (uint256 baseFee, uint256 escrowFee) = feePolicy.calculateFeeAmount(owner, productId, etherToPay); uint256 profit = etherToPay.safeSub(baseFee + escrowFee); if (productStorage.isEscrowUsed(productId)) { productStorage.setEscrowData(productId, purchaseId, msg.sender, baseFee, profit, now); productStorage.changePurchase(productId, purchaseId, IProductStorage.PurchaseState.Paid); //send escrow fee anyway escrowProvider.getProductEscrow(productId).transfer(escrowFee); revokedStorage.saveEscrowFee(productId, purchaseId, escrowFee); } else { feePolicy.sendFee.value(baseFee)(owner); productStorage.getVendorWallet(owner).transfer(profit); } } }
Returns true if vendor profit can be withdrawn / return state == IProductStorage.PurchaseState.Pending || (state == IProductStorage.PurchaseState.Paid && esrowHoldTimeElapsed(productId, purchaseId));
function canWithdrawPending(uint256 productId, uint256 purchaseId) public view returns(bool) { IProductStorage.PurchaseState state = productStorage.getPurchase(productId, purchaseId); (address customer, uint256 fee, uint256 profit, uint256 timestamp) = productStorage.getEscrowData(productId, purchaseId); return state == IProductStorage.PurchaseState.Pending || (state == IProductStorage.PurchaseState.Paid && esrowHoldTimeElapsed(productId, purchaseId)); }
12,636,918
pragma solidity ^0.4.24; // submited by @dev-xu // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol // @title SafeMath: overflow/underflow checks // @notice Math operations with safety checks that throw on error library SafeMath { // @notice 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; } // @notice 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; } // @notice 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; } // @notice 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; } // @notice Returns fractional amount function getFractionalAmount(uint256 _amount, uint256 _percentage) internal pure returns (uint256) { return div(mul(_amount, _percentage), 100); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface ERC20 { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address _who) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface MinterInterface { function cloneToken(string _uri, address _erc20Address) external returns (address asset); function mintAssetTokens(address _assetAddress, address _receiver, uint256 _amount) external returns (bool); function changeTokenController(address _assetAddress, address _newController) external returns (bool); } interface CrowdsaleReserveInterface { function issueETH(address _receiver, uint256 _amount) external returns (bool); function receiveETH(address _payer) external payable returns (bool); function refundETHAsset(address _asset, uint256 _amount) external returns (bool); function issueERC20(address _receiver, uint256 _amount, address _tokenAddress) external returns (bool); function requestERC20(address _payer, uint256 _amount, address _tokenAddress) external returns (bool); function approveERC20(address _receiver, uint256 _amount, address _tokenAddress) external returns (bool); function refundERC20Asset(address _asset, uint256 _amount, address _tokenAddress) external returns (bool); } interface Events { function transaction(string _message, address _from, address _to, uint _amount, address _token) external; } interface DB { function addressStorage(bytes32 _key) external view returns (address); function uintStorage(bytes32 _key) external view returns (uint); function setUint(bytes32 _key, uint _value) external; function deleteUint(bytes32 _key) external; function setBool(bytes32 _key, bool _value) external; function boolStorage(bytes32 _key) external view returns (bool); } // @title An asset crowdsale contract, which accepts Ether for funding. // @author Kyle Dewhurst & Peter Phillips, MyBit Foundation // @notice Starts a new crowdsale and returns asset dividend tokens for Wei received. // @dev The AssetManager contract CrowdsaleETH { using SafeMath for uint256; DB private database; Events private events; MinterInterface private minter; CrowdsaleReserveInterface private reserve; // @notice Constructor: Initiates the database // @param: The address for the database contract constructor(address _database, address _events) public { database = DB(_database); events = Events(_events); minter = MinterInterface(database.addressStorage(keccak256(abi.encodePacked("contract", "Minter")))); reserve = CrowdsaleReserveInterface(database.addressStorage(keccak256(abi.encodePacked("contract", "CrowdsaleReserve")))); } // @notice Investors can send Ether here to fund asset, receiving an equivalent number of asset-tokens. // @param (bytes32) _assetAddress = The address of the asset which completed the crowdsale function buyAssetOrderETH(address _assetAddress) external payable requiresEther validAsset(_assetAddress) beforeDeadline(_assetAddress) notFinalized(_assetAddress) returns (bool) { uint fundingRemaining = database.uintStorage(keccak256(abi.encodePacked("crowdsale.remaining", _assetAddress))); uint amount; //The number of tokens that will be minted if (msg.value < fundingRemaining) { amount = msg.value.mul(100).div(uint(100).add(database.uintStorage(keccak256(abi.encodePacked("platform.fee"))))); database.setUint(keccak256(abi.encodePacked("crowdsale.remaining", _assetAddress)), fundingRemaining.sub(msg.value)); //Mint tokens equal to the msg.value require(minter.mintAssetTokens(_assetAddress, msg.sender, amount), "Investor minting failed"); reserve.receiveETH.value(msg.value)(msg.sender); } else { amount = fundingRemaining.mul(100).div(uint(100).add(database.uintStorage(keccak256(abi.encodePacked("platform.fee"))))); //Funding complete, finalize crowdsale database.setBool(keccak256(abi.encodePacked("crowdsale.finalized", _assetAddress)), true); database.deleteUint(keccak256(abi.encodePacked("crowdsale.remaining", _assetAddress))); //Since investor paid equal to or over the funding remaining, just mint for tokensRemaining require(minter.mintAssetTokens(_assetAddress, msg.sender, amount), "Investor minting failed"); reserve.receiveETH.value(fundingRemaining)(msg.sender); //Return leftover WEI after cost of tokens calculated and subtracted from msg.value to msg.sender msg.sender.transfer(msg.value.sub(fundingRemaining)); } events.transaction('Asset purchased', address(this), msg.sender, amount, _assetAddress); return true; } // @notice This is called once funding has succeeded. Sends Ether to a distribution contract where receiver & assetManager can withdraw // @dev The contract manager needs to know the address PlatformDistribution contract // @param (bytes32) _assetAddress = The address of the asset which completed the crowdsale function payoutETH(address _assetAddress) external whenNotPaused finalized(_assetAddress) notPaid(_assetAddress) returns (bool) { //Set paid to true database.setBool(keccak256(abi.encodePacked("crowdsale.paid", _assetAddress)), true); //Setup token //Mint tokens for the asset manager and platform + finish minting address platformAssetsWallet = database.addressStorage(keccak256(abi.encodePacked("platform.wallet.assets"))); require(platformAssetsWallet != address(0), "Platform assets wallet not set"); require(minter.mintAssetTokens(_assetAddress, database.addressStorage(keccak256(abi.encodePacked("contract", "AssetManagerFunds"))), database.uintStorage(keccak256(abi.encodePacked("asset.managerTokens", _assetAddress)))), "Manager minting failed"); require(minter.mintAssetTokens(_assetAddress, platformAssetsWallet, database.uintStorage(keccak256(abi.encodePacked("asset.platformTokens", _assetAddress)))), "Platform minting failed"); //Get the addresses for the receiver and platform address receiver = database.addressStorage(keccak256(abi.encodePacked("asset.manager", _assetAddress))); address platformFundsWallet = database.addressStorage(keccak256(abi.encodePacked("platform.wallet.funds"))); require(receiver != address(0) && platformFundsWallet != address(0), "Receiver or platform wallet not set"); //Calculate amounts for platform and receiver uint amount = database.uintStorage(keccak256(abi.encodePacked("crowdsale.goal", _assetAddress))); uint platformFee = amount.getFractionalAmount(database.uintStorage(keccak256(abi.encodePacked("platform.fee")))); //Transfer funds to receiver and platform require(reserve.issueETH(platformFundsWallet, platformFee), 'Platform funds not paid'); require(reserve.issueETH(receiver, amount), 'Asset manager funds not paid'); //Delete crowdsale start time database.deleteUint(keccak256(abi.encodePacked("crowdsale.start", _assetAddress))); //Increase asset count for manager address manager = database.addressStorage(keccak256(abi.encodePacked("asset.manager", _assetAddress))); database.setUint(keccak256(abi.encodePacked("manager.assets", manager)), database.uintStorage(keccak256(abi.encodePacked("manager.assets", manager))).add(1)); //Emit event events.transaction('Asset payout', _assetAddress, receiver, amount, address(0)); return true; } function cancel(address _assetAddress) external whenNotPaused validAsset(_assetAddress) beforeDeadline(_assetAddress) notFinalized(_assetAddress) returns (bool){ require(msg.sender == database.addressStorage(keccak256(abi.encodePacked("asset.manager", _assetAddress)))); database.setUint(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress)), 1); refund(_assetAddress); } // @notice Contributors can retrieve their funds here if crowdsale has paased deadline and not reached its goal // @param (bytes32) _assetAddress = The address of the asset which completed the crowdsale function refund(address _assetAddress) public whenNotPaused validAsset(_assetAddress) afterDeadline(_assetAddress) notFinalized(_assetAddress) returns (bool) { require(database.uintStorage(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress))) != 0); database.deleteUint(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress))); ERC20 assetToken = ERC20(_assetAddress); uint refundValue = assetToken.totalSupply().mul(uint(100).add(database.uintStorage(keccak256(abi.encodePacked("platform.fee"))))).div(100); //total supply plus platform fees reserve.refundETHAsset(_assetAddress, refundValue); return true; } // @notice platform owners can recover tokens here function recoverTokens(address _erc20Token) onlyOwner external { ERC20 thisToken = ERC20(_erc20Token); uint contractBalance = thisToken.balanceOf(address(this)); thisToken.transfer(msg.sender, contractBalance); } // @notice platform owners can destroy contract here function destroy() onlyOwner external { events.transaction('CrowdsaleETH destroyed', address(this), msg.sender, address(this).balance, address(0)); selfdestruct(msg.sender); } //------------------------------------------------------------------------------------------------------------------ // Modifiers //------------------------------------------------------------------------------------------------------------------ // @notice Requires that Ether is sent with the transaction modifier requiresEther() { require(msg.value > 0); _; } // @notice Sender must be a registered owner modifier onlyOwner { require(database.boolStorage(keccak256(abi.encodePacked("owner", msg.sender))), "Not owner"); _; } // @notice function won't run if owners have paused this contract modifier whenNotPaused { require(!database.boolStorage(keccak256(abi.encodePacked("paused", address(this)))), "Contract paused"); _; } // @notice reverts if the asset does not have a token address set in the database modifier validAsset(address _assetAddress) { require(database.addressStorage(keccak256(abi.encodePacked("asset.manager", _assetAddress))) != address(0), "Invalid asset"); _; } // @notice reverts if the funding deadline has not passed modifier beforeDeadline(address _assetAddress) { require(now < database.uintStorage(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress))), "Before deadline"); _; } // @notice reverts if the funding deadline has already past or crowsale has not started modifier betweenDeadlines(address _assetAddress) { require(now <= database.uintStorage(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress))), "Past deadline"); require(now >= database.uintStorage(keccak256(abi.encodePacked("crowdsale.start", _assetAddress))), "Before start time"); _; } // @notice reverts if the funding deadline has already past modifier afterDeadline(address _assetAddress) { require(now > database.uintStorage(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress))), "Before deadline"); _; } // @notice returns true if crowdsale is finshed modifier finalized(address _assetAddress) { require( database.boolStorage(keccak256(abi.encodePacked("crowdsale.finalized", _assetAddress))), "Crowdsale not finalized"); _; } // @notice returns true if crowdsale is not finshed modifier notFinalized(address _assetAddress) { require( !database.boolStorage(keccak256(abi.encodePacked("crowdsale.finalized", _assetAddress))), "Crowdsale finalized"); _; } // @notice returns true if crowdsale has not paid out modifier notPaid(address _assetAddress) { require( !database.boolStorage(keccak256(abi.encodePacked("crowdsale.paid", _assetAddress))), "Crowdsale had paid out"); _; } }
Contributors can retrieve their funds here if crowdsale has paased deadline and not reached its goal (bytes32) _assetAddress = The address of the asset which completed the crowdsale
function refund(address _assetAddress) public whenNotPaused validAsset(_assetAddress) afterDeadline(_assetAddress) notFinalized(_assetAddress) returns (bool) { require(database.uintStorage(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress))) != 0); database.deleteUint(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress))); ERC20 assetToken = ERC20(_assetAddress); reserve.refundETHAsset(_assetAddress, refundValue); return true; }
1,114,709
pragma solidity >0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract IUniswapExchange { // Address of ERC20 token sold on this exchange function tokenAddress() external view returns (address token); // Address of Uniswap Factory function factoryAddress() external view returns (address factory); // Provide Liquidity function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256); function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256); // Get Prices function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold); // Trade ETH to ERC20 function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought); function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns (uint256 eth_sold); function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256 eth_sold); // Trade ERC20 to ETH function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256 eth_bought); function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_tokens, uint256 deadline, address recipient) external returns (uint256 eth_bought); function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256 tokens_sold); function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256 tokens_sold); // Trade ERC20 to ERC20 function tokenToTokenSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256 tokens_bought); function tokenToTokenTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_bought); function tokenToTokenSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256 tokens_sold); function tokenToTokenTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_sold); // Trade ERC20 to Custom Pool function tokenToExchangeSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256 tokens_bought); function tokenToExchangeTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_bought); function tokenToExchangeSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256 tokens_sold); function tokenToExchangeTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_sold); // ERC20 comaptibility for liquidity tokens bytes32 public name; bytes32 public symbol; uint256 public decimals; function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function allowance(address _owner, address _spender) external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function totalSupply() public view returns (uint256); // Never use function setup(address token_addr) external; } contract DCAcontract { IERC20 dai; address payable public creator; uint public fee_numerator; uint public fee_denominator; uint public gas_consumption; uint public streamsCount = 0; mapping(uint => address) public all_users; mapping(address => Stream) public streams; struct Stream { uint _id; uint parcel; // parcel in DAI uint interval; // interval in seconds uint startTime; uint lastSwap; uint isactive; uint created; uint dai_swapped; uint eth_received; } uint public relayersCount = 0; mapping(uint => address) public relayers; mapping(address => uint) public relayers_existance; // at creation, define who is the contract creator // the creator does not have specific powers, but will receive 50% of the fees collected by the relayers // this will allow the creator to sustain development and marketing of the frontend app to the users constructor(address payable _creator) public { dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); creator = _creator; fee_numerator = 2; fee_denominator = 1000; gas_consumption = 200000; SafeERC20.safeApprove(dai, 0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667, uint(-1)); } // allow the user to activate the dca stream // by default, a stream is set to active (isactive =1) when it is originally created function activate(uint _parcel, uint _interval) external { Stream storage s = streams[msg.sender]; if (s.created == 1) { s.parcel = _parcel; s.interval = _interval; } else { // then create the stream streams[msg.sender] = Stream(streamsCount, _parcel, _interval, block.timestamp, 0, 1, 1, 0, 0); all_users[streamsCount] = msg.sender; streamsCount ++; } } // allow the user to stop the dca stream function stop() external { Stream storage s = streams[msg.sender]; require(s.created == 1); s.isactive = 0; } // allow the user to re-start the dca stream function start() external { Stream storage s = streams[msg.sender]; require(s.created == 1); s.isactive = 1; } // allow the user to edit the individual parcel amount that is regularly purchased function editParcel(uint _parcel) external { Stream storage s = streams[msg.sender]; require(s.created == 1); s.parcel = _parcel; } // allow the user to edit the interval between purchases function editInterval(uint _interval) external { Stream storage s = streams[msg.sender]; require(s.created == 1); s.interval = _interval; } // allow an address to register as a relayer function registerAsRelayer() external{ // this function adds the msg.sender to the list of relayers // this is a FIFO list which will assign to each relayer a "time window" of 240 seconds to execute the DCA transaction. // the reason for this architecture is to allow everyone to be a relayer, but at the same time discourage gas bidding competition // which would ultimately damage the end user (who is paying for the gas) // first require that this relayers is not already in the list require(relayers_existance[msg.sender] != 1); relayers[relayersCount] = msg.sender; relayersCount ++; relayers_existance[msg.sender] = 1; } // allow a relayer to execute the transaction for a user and convert his DAI parcel into ETH function convertParcel(address payable _user) external{ Stream storage s = streams[_user]; uint256 gasPrice = tx.gasprice; uint256 eth_bought = IUniswapExchange(0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667).getTokenToEthInputPrice(s.parcel); // the contract execution requires several conditions: // a) that a stream was created for the user in the past (s.created == 1) // b) that the stream is active (s.isactive == 1) // c) that enough time has passed since the last swap (ready_since>=0) // d) that the estimated gas cost is below 3% of the returned amount from Uniswap; otherwise don't let transaction take place // e) that the current time window is open for this relayer // // starting from the top relayer in the list, each relayer will have a "time windows" of 240 seconds assigned to make the transaction // if that relayer does not respond, the time window will open for the second in the list, and so on // the first relayer that sends the transaction will move up in the list by one position. // this will allow anyone to be a relayer, while discouraging bidding with a high gas price which would ultimately damage the end user address relayer_allowed = 0x0000000000000000000000000000000000000000; uint relayer_allowed_index = 0; uint multiple = 0; if (s.lastSwap == 0){ multiple = (now - s.startTime) / (240 * relayersCount); relayer_allowed_index = ((now - s.startTime) - multiple * (240 * relayersCount)) / 240; relayer_allowed = relayers[relayer_allowed_index]; } else { multiple = (now - s.lastSwap - s.interval) / (240 * relayersCount); relayer_allowed_index = ((now - s.lastSwap - s.interval) - multiple * (240 * relayersCount)) / 240; relayer_allowed = relayers[relayer_allowed_index]; } require(s.created == 1 && s.isactive == 1 && now > s.lastSwap + s.interval && gasPrice * gas_consumption < eth_bought * 3 / 100 && relayer_allowed == msg.sender); // if all the conditions are satisfied, proceed with the swap // first move the parcel of DAI from the owner wallet to this contract, then return the ETH obtained to the contract dai.transferFrom(_user, address(this), s.parcel); uint256 ether_returned = IUniswapExchange(0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667).tokenToEthSwapInput(s.parcel, 1, now+120); // now distribute the ether_returned between the owner, the relayer and the creator // in particular: // a) the owner gets the ETH received from uniswap, net of the gas cost and the fee // b) the relayer gets 50% of the fee, plus a reimbursement for the gas cost // c) the creator gets 50% of the fee _user.transfer(ether_returned * (fee_denominator - fee_numerator)/fee_denominator - gas_consumption * gasPrice); // to the user msg.sender.transfer(gas_consumption * gasPrice + (ether_returned * fee_numerator / 2) / fee_denominator); // to the relayer creator.transfer((ether_returned * fee_numerator / 2) / fee_denominator); // to the creator // record in the contract the amount of DAI swapped and ETH received // also, update the timestamp of the last swap s.dai_swapped = s.dai_swapped + s.parcel; s.eth_received = s.eth_received + ether_returned - gas_consumption * gasPrice - (ether_returned * fee_numerator) / fee_denominator; s.lastSwap = block.timestamp; // finally, readjust the FIFO list of relayers and reward the relayer that made the transaction by moving up one notch if (relayer_allowed_index != 0){ address relayer_before = relayers[relayer_allowed_index - 1]; relayers[relayer_allowed_index - 1] = msg.sender; relayers[relayer_allowed_index] = relayer_before; } } // check that is the right time to trigger a swap for a certain user // NOTE: this function needs to return 0 for the transaction to be possible function check_time(address payable _user) public view returns(uint){ Stream storage s = streams[_user]; if (s.created == 0) { // if the user was never created return uint(-1); } else if (now < s.lastSwap + s.interval){ // if the user was created, but it's not yet time to make a swap, return the remaining time in seconds return s.lastSwap + s.interval - now; } else { // if the timing is good to make the swap, return 0 return 0; } } // check that the address has a sufficient DAI balance and allowance to make the swap & the stream is active // NOTE: this function needs to return 1 for the transaction to be possible function check_balance(address payable _user) public view returns(uint){ Stream storage s = streams[_user]; if (s.created == 0) { // if the user was never created return uint(-1); } else if (dai.balanceOf(_user) > s.parcel && dai.allowance(_user, address(this)) > s.parcel && s.isactive == 1) { // if the balance is enough and we have enough allowance to make the swap, return 1 return 1; } else { // if not, return 0 return 0; } } // check that the gas price that we are planning to use doesn't exceed 3% of the ethereum received // NOTE: this function needs to return 1 for the transaction to be possible function check_gas_price(address payable _user, uint _gasPrice) public view returns(uint){ Stream storage s = streams[_user]; uint256 eth_bought = IUniswapExchange(0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667).getTokenToEthInputPrice(s.parcel); if (_gasPrice * gas_consumption < eth_bought * 3 / 100){ // the gas price that the relayer plans to adopt is ok return 1; } else { // the gas price that the relayer plans to adopt is too high return 0; } } // check what relayer is currently allowed to execute the transaction // NOTE: this function needs to return your address for you to be allowed as a relayer to execute the transaction and obtain the fee function check_allowed_relayer(address payable _user) public view returns(address){ Stream storage s = streams[_user]; if (now < s.lastSwap + s.interval){ return 0x0000000000000000000000000000000000000000; } else if (s.lastSwap == 0){ uint multiple = (now - s.startTime) / (240 * relayersCount); uint relayer_allowed_index = ((now - s.startTime) - multiple * (240 * relayersCount)) / 240; return relayers[relayer_allowed_index]; } else { uint multiple = (now - s.lastSwap - s.interval) / (240 * relayersCount); uint relayer_allowed_index = ((now - s.lastSwap - s.interval) - multiple * (240 * relayersCount)) / 240; return relayers[relayer_allowed_index]; } } // scan through the all_users list and obtain the address of each user function scanUsers(uint _index) public view returns(address){ return all_users[_index]; } // Include fallback so the contract can receive ETH from exchange function () external payable {} }
check that the gas price that we are planning to use doesn't exceed 3% of the ethereum received NOTE: this function needs to return 1 for the transaction to be possible the gas price that the relayer plans to adopt is ok the gas price that the relayer plans to adopt is too high
function check_gas_price(address payable _user, uint _gasPrice) public view returns(uint){ Stream storage s = streams[_user]; uint256 eth_bought = IUniswapExchange(0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667).getTokenToEthInputPrice(s.parcel); if (_gasPrice * gas_consumption < eth_bought * 3 / 100){ return 1; return 0; } }
7,286,326
./partial_match/1/0x8Eb7937526a7727210F0b8c385b692bbA3aFbaF3/sources/StakingV02.sol
IMPORTANT 1. version needed for upgradable versions _activate is using this to check if this is a new version and if this version is higher than the last activated version
{ function version() public virtual override pure returns(Version) pragma solidity ^0.8.19; import {Version, toVersion, toVersionPart} from "IVersionType.sol"; import {IVersionable} from "IVersionable.sol"; import {Versionable} from "Versionable.sol"; import {VersionedOwnable} from "VersionedOwnable.sol"; import {NftId} from "IChainNft.sol"; import {StakingV01} from "StakingV01.sol"; { return toVersion( toVersionPart(1), toVersionPart(0), toVersionPart(1)); } function activate(address implementation, address activatedBy) external virtual override (IVersionable, VersionedOwnable) { _activate(implementation, activatedBy); _version = version(); } function claimRewards(NftId stakeId) external virtual override onlyStakeOwner(stakeId) { address user = msg.sender; StakeInfo storage info = _info[stakeId]; _updateRewards(info); _claimRewards(user, info); } }
3,605,848
./partial_match/1/0xC5B0B727B5447442ffafeB6c254F745691a5eEfD/sources/Platform.sol
Deploy the platform.
function deploy(address _gaugeController) external returns (Platform platform) { platform = new Platform{ salt: address(_gaugeController).fillLast12Bytes() }(_gaugeController, address(this)); FeeManager feeManager = new FeeManager{ salt: address(_gaugeController).fillLast12Bytes() }(feeCollector); feeManagerPerGaugeController[_gaugeController] = address(feeManager); emit PlatformDeployed(platform, _gaugeController, feeManager); }
2,664,397
./full_match/80001/0x8B08174c8EdEF49fB218Ac26f5768E16cDDA73F2/sources/contracts/Deps/hats-protocol/Hats.sol
Set a mutable hat to immutable Sets the second bit of hat.config to 0 _hatId The id of the Hat to make immutable
function makeHatImmutable(uint256 _hatId) external { _checkAdmin(_hatId); Hat storage hat = _hats[_hatId]; if (!_isMutable(hat)) { revert Immutable(); } hat.config &= ~uint96(1 << 94); emit HatMutabilityChanged(_hatId); }
5,576,614
./full_match/1/0x3b871aa1b9Af565A30466c9fa4B90e651891E4ee/sources/contracts/Strategy.sol
@inheritdoc IStrategy
function mintByRevenue(uint256 _baseIn) external override onlyRevenue returns (uint256 _fTokenMinted, uint256 _xTokenMinted) { ITreasury _treasury = ITreasury(treasury); IERC20Upgradeable baseToken = IERC20Upgradeable(_treasury.baseToken()); uint256 balance = baseToken.balanceOf(address(this)); require(balance > _baseIn, "baseIn exceeds balance"); return _allocate(_baseIn, revenue); }
3,131,353
./full_match/5/0xD8C733bC6bd838AF10087457B5261e2b11bA00BA/sources/contracts/StakingContract.sol
Withdraw chosen deposit Brings out the stakers deposit info with the corresponding depositId Update staker balance for corresponding deposit and withdraw
function withdrawPosition(uint256 _depositId) public virtual ifNotPaused { StakeVault storage staker = checkDeposit[msg.sender][_depositId]; uint256 depositAmount = staker.depositAmount; uint256 lockedUntil = staker.startTime + staker.daysLocked; uint256 _amount = depositAmount; if ((depositAmount > 1) && (block.timestamp >= lockedUntil)) { claim(_depositId, msg.sender); currentId[msg.sender]++; balanceTotal[msg.sender] -= _amount; totalStaked -= _amount; staker.depositAmount = 0; emit UnStake(msg.sender, _amount); bool success = audxContract.transfer(msg.sender, _amount); require(success, "Failed to withdraw!"); } }
1,931,266
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol'; import {Pausable} from '@openzeppelin/contracts/security/Pausable.sol'; import {ReentrancyGuard} from '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import {MerkleProof} from '@openzeppelin/contracts/utils/cryptography/MerkleProof.sol'; import {IERC20, SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import {IStakeFor} from './IStakeFor.sol'; /** * @title ListingRewardsDistributor * @notice It distributes X2Y2 tokens with rolling Merkle airdrops. */ contract ListingRewardDistributor is Pausable, ReentrancyGuard, Ownable { using SafeERC20 for IERC20; uint256 public constant BUFFER_ADMIN_WITHDRAW = 3 days; IERC20 public immutable x2y2Token; IStakeFor public stakingPool; // Current reward round (users can only claim pending rewards for the current round) uint256 public currentRewardRound; // Last paused timestamp uint256 public lastPausedTimestamp; // Max amount per user in current tree uint256 public maximumAmountPerUserInCurrentTree; // Total amount claimed by user (in X2Y2) mapping(address => uint256) public amountClaimedByUser; // Merkle root for a reward round mapping(uint256 => bytes32) public merkleRootOfRewardRound; // Checks whether a merkle root was used mapping(bytes32 => bool) public merkleRootUsed; // Keeps track on whether user has claimed at a given reward round mapping(uint256 => mapping(address => bool)) public hasUserClaimedForRewardRound; event RewardsClaim(address indexed user, uint256 indexed rewardRound, uint256 amount); event UpdateListingRewards(uint256 indexed rewardRound); event TokenWithdrawnOwner(uint256 amount); event StakingPoolUpdate(address newPool); /** * @notice Constructor * @param _x2y2Token address of the X2Y2 token */ constructor(IERC20 _x2y2Token, IStakeFor _stakingPool) { x2y2Token = _x2y2Token; stakingPool = _stakingPool; _pause(); } function updateStakingPool(IStakeFor _stakingPool) external onlyOwner { stakingPool = _stakingPool; emit StakingPoolUpdate(address(_stakingPool)); } /** * @notice Claim pending rewards * @param amount amount to claim * @param staking direct staking * @param merkleProof array containing the merkle proof */ function claim( uint256 amount, bool staking, bytes32[] calldata merkleProof ) external whenNotPaused nonReentrant { // Verify the reward round is not claimed already require( !hasUserClaimedForRewardRound[currentRewardRound][msg.sender], 'Rewards: Already claimed' ); (bool claimStatus, uint256 adjustedAmount) = _canClaim(msg.sender, amount, merkleProof); require(claimStatus, 'Rewards: Invalid proof'); require(maximumAmountPerUserInCurrentTree >= amount, 'Rewards: Amount higher than max'); // Set mapping for user and round as true hasUserClaimedForRewardRound[currentRewardRound][msg.sender] = true; // Adjust amount claimed amountClaimedByUser[msg.sender] += adjustedAmount; // Stake/transfer adjusted amount if (staking) { require(address(stakingPool) != address(0), 'Cannot stake to address(0)'); x2y2Token.approve(address(stakingPool), amount); stakingPool.depositFor(msg.sender, adjustedAmount); } else { x2y2Token.safeTransfer(msg.sender, adjustedAmount); } emit RewardsClaim(msg.sender, currentRewardRound, adjustedAmount); } /** * @notice Update trading rewards with a new merkle root * @dev It automatically increments the currentRewardRound * @param merkleRoot root of the computed merkle tree */ function updateListingRewards(bytes32 merkleRoot, uint256 newMaximumAmountPerUser) external onlyOwner { require(!merkleRootUsed[merkleRoot], 'Owner: Merkle root already used'); currentRewardRound++; merkleRootOfRewardRound[currentRewardRound] = merkleRoot; merkleRootUsed[merkleRoot] = true; maximumAmountPerUserInCurrentTree = newMaximumAmountPerUser; emit UpdateListingRewards(currentRewardRound); } /** * @notice Pause distribution */ function pauseDistribution() external onlyOwner whenNotPaused { lastPausedTimestamp = block.timestamp; _pause(); } /** * @notice Unpause distribution */ function unpauseDistribution() external onlyOwner whenPaused { _unpause(); } /** * @notice Transfer X2Y2 tokens back to owner * @dev It is for emergency purposes * @param amount amount to withdraw */ function withdrawTokenRewards(uint256 amount) external onlyOwner whenPaused { require( block.timestamp > (lastPausedTimestamp + BUFFER_ADMIN_WITHDRAW), 'Owner: Too early to withdraw' ); x2y2Token.safeTransfer(msg.sender, amount); emit TokenWithdrawnOwner(amount); } /** * @notice Check whether it is possible to claim and how much based on previous distribution * @param user address of the user * @param amount amount to claim * @param merkleProof array with the merkle proof */ function canClaim( address user, uint256 amount, bytes32[] calldata merkleProof ) external view returns (bool, uint256) { return _canClaim(user, amount, merkleProof); } /** * @notice Check whether it is possible to claim and how much based on previous distribution * @param user address of the user * @param amount amount to claim * @param merkleProof array with the merkle proof */ function _canClaim( address user, uint256 amount, bytes32[] calldata merkleProof ) internal view returns (bool, uint256) { // Compute the node and verify the merkle proof bytes32 node = keccak256(abi.encodePacked(user, amount)); bool canUserClaim = MerkleProof.verify( merkleProof, merkleRootOfRewardRound[currentRewardRound], node ); if ((!canUserClaim) || (hasUserClaimedForRewardRound[currentRewardRound][user])) { return (false, 0); } else { return (true, amount - amountClaimedByUser[user]); } } } // 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 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IStakeFor { function depositFor(address user, uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) 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 // 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); } } } }
Transfer X2Y2 tokens back to owner It is for emergency purposes amount amount to withdraw/
function withdrawTokenRewards(uint256 amount) external onlyOwner whenPaused { require( block.timestamp > (lastPausedTimestamp + BUFFER_ADMIN_WITHDRAW), 'Owner: Too early to withdraw' ); x2y2Token.safeTransfer(msg.sender, amount); emit TokenWithdrawnOwner(amount); }
328,446
./partial_match/1/0x031AA05Da8bf778dFC36D8D25cA68CBB2fC447c6/sources/contracts/BlurExchange.sol
Transfer amount in ETH or WETH paymentToken address of token to pay in from token sender to token recipient amount amount to transfer/
function _transferTo( address paymentToken, address from, address to, uint256 amount ) internal { if (amount == 0) { return; } if (paymentToken == address(0)) { require(to != address(0), "Transfer to zero address"); require(success, "ETH transfer failed"); executionDelegate.transferERC20(WETH, from, to, amount); revert("Invalid payment token"); } }
4,340,352
./full_match/4/0x9ce71Fd97d5cc7f47a00428A2e8f2E24E5416f27/sources/NFTYFactory.sol
Returning Trending NFTs for a specific contract address _addressOfClonedContract Address of the cloned contract return Trending NFT IDs array/
function getTrendingNFT(address _addressOfClonedContract) public view returns (uint256[] memory) { return NFTYContract(_addressOfClonedContract).getTrendingNFT(); }
12,388,638
./full_match/80001/0xdb47243cE1544B188205669f168F80277E61a6b3/sources/contracts/Contract.sol
Function to vote for a proposal (yes or no)
function vote(uint256 proposalId, bool choice) public { require(proposalId > 0 && proposalId <= proposalCount, "Invalid proposal ID."); require(!hasVoted[msg.sender], "You have already voted."); if (choice) { proposals[proposalId].yesVotes++; proposals[proposalId].noVotes++; } hasVoted[msg.sender] = true; }
5,640,658
//SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./ItemERC721.sol"; contract SillySushi is ItemERC721 { constructor( address _openSeaProxyRegistryAddress, uint256 _maxSupply, uint256 _maxPresaleSupply, string memory _name, string memory _symbol, string memory _uri, uint256 _publicSalePrice, uint256 _presalePrice, uint256 _maxItemsPerWallet, uint256 _maxItemsPerTxn ) ItemERC721( _openSeaProxyRegistryAddress, _maxSupply, _maxPresaleSupply, _name, _symbol, _uri, _publicSalePrice, _presalePrice, _maxItemsPerWallet, _maxItemsPerTxn ){} } //SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/interfaces/IERC20.sol"; import "@openzeppelin/contracts/interfaces/IERC165.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract ItemERC721 is ERC721, Ownable, ReentrancyGuard { using Counters for Counters.Counter; using Strings for uint256; Counters.Counter private tokenCounter; string private baseURI; address private openSeaProxyRegistryAddress; bool private isOpenSeaProxyActive = true; uint256 public MAX_ITEMS_PER_WALLET; uint256 public maxSupply; uint256 public PUBLIC_SALE_PRICE; bool public isPublicSaleActive; uint256 public MAX_ITEMS_PER_TXN; uint256 public PRESALE_PRICE; uint256 public maxPresaleSupply; bytes32 public presaleMerkleRoot; bool public isPresaleActive; mapping(address => uint256) public perWalletMintCounts; // ============ ACCESS CONTROL/SANITY MODIFIERS ============ modifier publicSaleActive() { require(isPublicSaleActive, "Public sale closed"); _; } modifier presaleActive() { require(isPresaleActive, "Presale closed"); _; } modifier maxItemsPerTxn(uint256 numberOfTokens) { require( numberOfTokens <= MAX_ITEMS_PER_TXN, "Minting too many per transaction" ); _; } modifier canMintItems(uint256 numberOfTokens) { require( tokenCounter.current() + numberOfTokens <= maxSupply, "Out of supply" ); _; } modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) { require( price * numberOfTokens == msg.value, "Incorrect ETH value sent" ); _; } modifier isValidMerkleProof(bytes32[] calldata merkleProof, bytes32 root) { require( MerkleProof.verify( merkleProof, root, keccak256(abi.encodePacked(msg.sender)) ), "Address does not exist in list" ); _; } // ========== CONSTRUCTOR ================= constructor( address _openSeaProxyRegistryAddress, uint256 _maxSupply, uint256 _maxPresaleSupply, string memory _name, string memory _symbol, string memory _uri, uint256 _publicSalePrice, uint256 _presalePrice, uint256 _maxItemsPerWallet, uint256 _maxItemsPerTxn ) ERC721(_name, _symbol) { openSeaProxyRegistryAddress = _openSeaProxyRegistryAddress; maxSupply = _maxSupply; maxPresaleSupply = _maxPresaleSupply; baseURI = _uri; PUBLIC_SALE_PRICE = _publicSalePrice; PRESALE_PRICE = _presalePrice; MAX_ITEMS_PER_WALLET = _maxItemsPerWallet; MAX_ITEMS_PER_TXN = _maxItemsPerTxn; } // ============ PUBLIC FUNCTIONS FOR MINTING ============ function mint(uint256 numberOfTokens) external payable nonReentrant isCorrectPayment(PUBLIC_SALE_PRICE, numberOfTokens) publicSaleActive canMintItems(numberOfTokens) maxItemsPerTxn(numberOfTokens) { for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(msg.sender, nextTokenId()); } } function airdrop(address[] calldata addresses) external nonReentrant onlyOwner canMintItems(addresses.length) { uint256 numToGift = addresses.length; for (uint256 i = 0; i < numToGift; i++) { _safeMint(addresses[i], nextTokenId()); } } function mintPresale( uint8 numberOfTokens, bytes32[] calldata merkleProof ) external payable nonReentrant presaleActive canMintItems(numberOfTokens) isCorrectPayment(PRESALE_PRICE, numberOfTokens) isValidMerkleProof(merkleProof, presaleMerkleRoot) { uint256 numAlreadyMinted = perWalletMintCounts[msg.sender]; require( numAlreadyMinted + numberOfTokens <= MAX_ITEMS_PER_WALLET, "Max items to mint exceeded" ); perWalletMintCounts[msg.sender] = numAlreadyMinted + numberOfTokens; for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(msg.sender, nextTokenId()); } } // ============ PUBLIC READ-ONLY FUNCTIONS ============ function getLastTokenId() external view returns (uint256) { return tokenCounter.current(); } function totalSupply() external view returns (uint256) { return maxSupply; } // ============ OWNER-ONLY ADMIN FUNCTIONS ============ function setBaseURI(string memory _uri) external onlyOwner { baseURI = _uri; } function _baseURI() internal view override virtual returns (string memory) { return baseURI; } // function to disable gasless listings for security in case // opensea ever shuts down or is compromised function setIsOpenSeaProxyActive(bool _isOpenSeaProxyActive) external onlyOwner { isOpenSeaProxyActive = _isOpenSeaProxyActive; } function setIsPublicSaleActive(bool _isPublicSaleActive) external onlyOwner { isPublicSaleActive = _isPublicSaleActive; } function setIsPresaleActive(bool _isPresaleActive) external onlyOwner { isPresaleActive = _isPresaleActive; } function setPresaleMerkleRoot(bytes32 merkleRoot) external onlyOwner { presaleMerkleRoot = merkleRoot; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function withdrawTokens(IERC20 token) public onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } function currentTokenId() public view returns (uint256) { return tokenCounter.current(); } // ============ SUPPORTING FUNCTIONS ============ function nextTokenId() private returns (uint256) { tokenCounter.increment(); return tokenCounter.current(); } // ============ FUNCTION OVERRIDES ============ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev Override isApprovedForAll to allowlist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Get a reference to OpenSea's proxy registry contract by instantiating // the contract using the already existing address. ProxyRegistry proxyRegistry = ProxyRegistry( openSeaProxyRegistryAddress ); if ( isOpenSeaProxyActive && address(proxyRegistry.proxies(owner)) == operator ) { return true; } return super.isApprovedForAll(owner, operator); } } // These contract definitions are used to create a reference to the OpenSea // ProxyRegistry contract by using the registry's address (see isApprovedForAll). contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (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); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; import "../token/ERC20/IERC20.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; // 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 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // 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/math/SafeMath.sol) 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 generally not needed starting with Solidity 0.8, since 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. 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; } } } // 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/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 (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts 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/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) 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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @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); }
Initializes the contract setting the deployer as the initial owner./
function _beforeTokenTransfer( address from, address to, uint256 tokenId function _afterTokenTransfer( address from, address to, uint256 tokenId } pragma solidity ^0.8.0; import "../token/ERC20/IERC20.sol"; pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; pragma solidity ^0.8.0; import "../utils/Context.sol"; constructor() { _transferOwnership(_msgSender()); }
13,587,974
./partial_match/1/0x6b6A24EFEe75EdACd1E47a8ea63cE1981F0013E0/sources/IdentityRegistry.sol
See {IIdentityRegistry-batchRegisterIdentity}./
function batchRegisterIdentity(address[] calldata _userAddresses, IIdentity[] calldata _identities, uint16[] calldata _countries) external override { for (uint256 i = 0; i < _userAddresses.length; i++) { registerIdentity(_userAddresses[i], _identities[i], _countries[i]); } }
9,212,918
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.5.6; pragma experimental ABIEncoderV2; import "../common/Exponential.sol"; import "../common/upgradeable/Initializable.sol"; import "./VDON.sol"; import "./VDONNonInterestStakingInterface.sol"; import "../lending/IERC20.sol"; /** * @title Donkey's VDON Staking Contract for governance * @notice VDON Staking Contract for governance * @author Donkey */ contract VDONNonInterestStaking is Initializable, VDONNonInterestStakingInterface, Exponential { function initialize( address DONAddress_, address VDONAddress_ ) public initializer { admin = msg.sender; DONAddress = DONAddress_; VDONAddress = VDONAddress_; _notEntered = true; } struct MintLocalVars { uint DONBalance; uint actualMintAmount; bool claimResult; address payable account; } function mint(uint productInfoId, uint mintAmount) external nonReentrant returns (uint) { require(mintAmount > 0, "E101"); MintLocalVars memory vars; vars.account = msg.sender; vars.DONBalance = IERC20(DONAddress).balanceOf(vars.account); require(vars.DONBalance >= mintAmount, "E104"); ProductInfo storage productInfo = getProductInfoById[productInfoId]; require(productInfo.isActivate, "E109"); vars.actualMintAmount = _doTransferIn(vars.account, mintAmount, DONAddress); // totalPrincipalAmount = totalPrincipalAmount + actualMintAmount productInfo.totalPrincipalAmount = add_(productInfo.totalPrincipalAmount, vars.actualMintAmount); _createProductWith(productInfoId, vars.account, vars.actualMintAmount); VDON(VDONAddress).mint(vars.account, mul_(productInfo.VDONExchangeRate, vars.actualMintAmount)); emit Mint(vars.account, vars.actualMintAmount); return vars.actualMintAmount; } struct RedeemLocalVars { uint productInfoId; uint accountPrincipal; uint DONRedeemAmount; address payable account; } // redeem principal with interest after lockupTerm function redeem(uint redeemProductId) external nonReentrant { RedeemLocalVars memory vars; vars.account = msg.sender; require(productOf[vars.account][redeemProductId].principal > 0, "E106"); require(productOf[vars.account][redeemProductId].releaseTime <= block.timestamp, "E107"); vars.productInfoId = productOf[vars.account][redeemProductId].productInfoId; vars.accountPrincipal = productOf[vars.account][redeemProductId].principal; ProductInfo storage productInfo = getProductInfoById[vars.productInfoId]; vars.DONRedeemAmount = _doTransferOut(vars.account, vars.accountPrincipal, DONAddress); productInfo.totalPrincipalAmount = sub_(productInfo.totalPrincipalAmount, vars.accountPrincipal); VDON(VDONAddress).burn(vars.account, mul_(productInfo.VDONExchangeRate, vars.accountPrincipal)); _deleteProductFrom(vars.account, redeemProductId); emit Redeem(vars.account, vars.DONRedeemAmount); } function redeemAdmin(address payable minter, uint redeemProductId) external nonReentrant { require(msg.sender == admin); RedeemLocalVars memory vars; vars.account = minter; require(productOf[vars.account][redeemProductId].principal > 0, "E106"); vars.productInfoId = productOf[vars.account][redeemProductId].productInfoId; vars.accountPrincipal = productOf[vars.account][redeemProductId].principal; ProductInfo storage productInfo = getProductInfoById[vars.productInfoId]; vars.DONRedeemAmount = _doTransferOut(vars.account, vars.accountPrincipal, DONAddress); productInfo.totalPrincipalAmount = sub_(productInfo.totalPrincipalAmount, vars.accountPrincipal); VDON(VDONAddress).burn(vars.account, mul_(productInfo.VDONExchangeRate, vars.accountPrincipal)); _deleteProductFrom(vars.account, redeemProductId); emit Redeem(vars.account, vars.DONRedeemAmount); } function createProductInfo( bool isActivate_, uint lockupTerm_, uint VDONExchangeRate_ ) external returns (ProductInfo memory) { require(msg.sender == admin); ProductInfo storage productInfo = getProductInfoById[freshProductInfoId]; productInfo.lockupTerm = lockupTerm_; productInfo.VDONExchangeRate = VDONExchangeRate_; productInfo.isActivate = isActivate_; getProductInfoById[freshProductInfoId] = productInfo; freshProductInfoId += 1; return productInfo; } function updateProductInfo( bool isActivate_, uint productInfoId, uint newLockupTerm, uint newVDONExchangeRate ) external returns (ProductInfo memory) { require(msg.sender == admin, "E1"); require(newLockupTerm > 0 && newVDONExchangeRate > 0); ProductInfo storage productInfo = getProductInfoById[productInfoId]; productInfo.lockupTerm = newLockupTerm; productInfo.VDONExchangeRate = newVDONExchangeRate; productInfo.isActivate = isActivate_; return productInfo; } function setAdmin(address newAdmin) external { require(admin == msg.sender, "E1"); address oldAdmin = admin; admin = newAdmin; emit UpdateAdmin(oldAdmin, newAdmin); } function enteredProductOf(address account) external view returns (ProductView[] memory) { uint[] memory productIdList = allProductsIdOf[account]; uint len = productIdList.length; ProductView[] memory stakingProductViewList = new ProductView[](len); for (uint i = 0; i < len; i += 1){ uint productId = productIdList[i]; ProductView memory stakingProductView; EnteredProduct memory product = productOf[account][productId]; ProductInfo memory productInfo = getProductInfoById[product.productInfoId]; stakingProductView.startTime = product.releaseTime - productInfo.lockupTerm; stakingProductView.releaseTime = product.releaseTime; stakingProductView.principal = product.principal; stakingProductView.lockupTerm = productInfo.lockupTerm; stakingProductView.vDONExchangeRate = productInfo.VDONExchangeRate; stakingProductView.productInfoId = product.productInfoId; stakingProductView.productId = productId; stakingProductViewList[i] = stakingProductView; } return stakingProductViewList; } function productInfoList() external view returns(ProductInfoView[] memory) { ProductInfoView[] memory productInfoViewList = new ProductInfoView[](freshProductInfoId); for(uint i = 0; i < freshProductInfoId; i += 1){ ProductInfo memory productInfo = getProductInfoById[i]; productInfoViewList[i].isActivate = productInfo.isActivate; productInfoViewList[i].lockupTerm = productInfo.lockupTerm; productInfoViewList[i].VDONExchangeRate = productInfo.VDONExchangeRate; productInfoViewList[i].totalPrincipalAmount = productInfo.totalPrincipalAmount; productInfoViewList[i].productInfoId = i; } return productInfoViewList; } function _createProductWith(uint productInfoId, address account, uint principal) internal { ProductInfo memory productInfo = getProductInfoById[productInfoId]; allProductsIdOf[account].push(freshProductId); productOf[account][freshProductId].productInfoId = productInfoId; productOf[account][freshProductId].releaseTime = add_(block.timestamp, productInfo.lockupTerm); productOf[account][freshProductId].principal = principal; freshProductId += 1; } function _deleteProductFrom(address account, uint targetProductId) internal { uint len = allProductsIdOf[account].length; require(len > 0, "E112"); uint idx = len; for (uint i = 0; i < len; i += 1) { if (targetProductId == allProductsIdOf[account][i]) { idx = i; break; } } // handle invalid idx value require(idx < len, "E113"); allProductsIdOf[account][idx] = allProductsIdOf[account][len - 1]; delete allProductsIdOf[account][len - 1]; allProductsIdOf[account].length--; delete productOf[account][targetProductId]; } // reference : https://github.com/compound-finance/compound-protocol/blob/master/contracts/CErc20.sol function _doTransferIn(address sender, uint amount, address tokenAddress) internal returns (uint) { IERC20 token = IERC20(tokenAddress); uint balanceBeforeTransfer = IERC20(tokenAddress).balanceOf(address(this)); token.transferFrom(sender, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "E79"); uint balanceAfterTransfer = IERC20(DONAddress).balanceOf(address(this)); require(balanceAfterTransfer >= balanceBeforeTransfer , "E80"); return balanceAfterTransfer - balanceBeforeTransfer; } // reference : https://github.com/compound-finance/compound-protocol/blob/master/contracts/CErc20.sol function _doTransferOut(address payable recipient, uint amount, address tokenAddress) internal returns (uint) { IERC20 token = IERC20(tokenAddress); token.transfer(recipient, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "E81"); return amount; } // reference : https://github.com/compound-finance/compound-protocol/blob/master/contracts/CToken.sol modifier nonReentrant() { require(_notEntered, "E67"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } }
reference : https:github.com/compound-finance/compound-protocol/blob/master/contracts/CErc20.sol
function _doTransferIn(address sender, uint amount, address tokenAddress) internal returns (uint) { IERC20 token = IERC20(tokenAddress); uint balanceBeforeTransfer = IERC20(tokenAddress).balanceOf(address(this)); token.transferFrom(sender, address(this), amount); bool success; assembly { switch returndatasize() } returndatacopy(0, 0, 32) } revert(0, 0)
7,327,547
./partial_match/42/0xb0D299d01bBD2fb20A52E315c768C88C44256d92/sources/ProofOfHumanity.sol
Challenge the submission's request. Accepts enough ETH to cover the deposit, reimburses the rest. _submissionID The address of the submission which request to challenge. _reason The reason to challenge the request. Left empty for removal requests. _duplicateID The address of a supposed duplicate submission. Ignored if the reason is not Duplicate. _evidence A link to evidence using its URI. Ignored if not provided./ solium-disable indentation /
function challengeRequest(address _submissionID, Reason _reason, address _duplicateID, string calldata _evidence) external payable { Submission storage submission = submissions[_submissionID]; if (submission.status == Status.PendingRegistration) require(_reason != Reason.None, "Reason must be specified"); else if (submission.status == Status.PendingRemoval) require(_reason == Reason.None, "Reason must be left empty"); else revert("Wrong status"); Request storage request = submission.requests[submission.requests.length - 1]; require(now - request.challengePeriodStart <= challengePeriodDuration, "Time to challenge has passed"); Challenge storage challenge = request.challenges[request.lastChallengeID]; { Reason currentReason = request.currentReason; if (_reason == Reason.Duplicate) { require(submissions[_duplicateID].status > Status.None || submissions[_duplicateID].registered, "Wrong duplicate status"); require(_submissionID != _duplicateID, "Can't be a duplicate of itself"); require(currentReason == Reason.Duplicate || currentReason == Reason.None, "Another reason is active"); require(!request.challengeDuplicates[_duplicateID], "Duplicate address already used"); request.challengeDuplicates[_duplicateID] = true; challenge.duplicateSubmissionIndex = submissions[_duplicateID].index; } else require(!request.disputed, "The request is disputed"); if (currentReason != _reason) { require((reasonBit & ~request.usedReasons) == reasonBit, "The reason has already been used"); request.currentReason = _reason; } } Round storage round = challenge.rounds[0]; ArbitratorData storage arbitratorData = arbitratorDataList[request.arbitratorDataID]; uint arbitrationCost = arbitratorData.arbitrator.arbitrationCost(arbitratorData.arbitratorExtraData); contribute(round, Party.Challenger, msg.sender, msg.value, arbitrationCost); require(round.paidFees[uint(Party.Challenger)] >= arbitrationCost, "You must fully fund your side"); round.feeRewards = round.feeRewards.subCap(arbitrationCost); challenge.disputeID = arbitratorData.arbitrator.createDispute.value(arbitrationCost)(RULING_OPTIONS, arbitratorData.arbitratorExtraData); challenge.challenger = msg.sender; DisputeData storage disputeData = arbitratorDisputeIDToDisputeData[address(arbitratorData.arbitrator)][challenge.disputeID]; disputeData.challengeID = uint96(request.lastChallengeID); disputeData.submissionID = _submissionID; request.disputed = true; request.nbParallelDisputes++; challenge.lastRoundID++; emit SubmissionChallenged(_submissionID, submission.requests.length - 1, disputeData.challengeID); request.lastChallengeID++; emit Dispute( arbitratorData.arbitrator, challenge.disputeID, submission.status == Status.PendingRegistration ? 2 * arbitratorData.metaEvidenceUpdates : 2 * arbitratorData.metaEvidenceUpdates + 1, submission.requests.length - 1 + uint(_submissionID) ); if (bytes(_evidence).length > 0) emit Evidence(arbitratorData.arbitrator, submission.requests.length - 1 + uint(_submissionID), msg.sender, _evidence); }
3,440,470
./full_match/1/0xB70Bf3D8B6f2022bE33ddbce8762A816571a1806/sources/contracts/Market.sol
This function is used to get auction details of an item itemId The item id whose auction details are to be retrievedreturn AuctionDetails of the itemId
function fetchAuctionItemsDetails(uint256 itemId) external view returns (Auction memory) { return idToAuctionItem[itemId]; }
16,399,609
pragma solidity ^0.4.18; import "../Models.sol"; contract NodeRegistry { // State mapping (bytes32 => Models.Node) public nodes; mapping (address => bytes32[]) public nodesPerAccount; bytes32[] public nodesIndex; // Functions /* * @dev allows to register a new Node, returning a bytes32 nonce for the Node, if it doesn't exist already, in which case it will error out. * @param bytes8[] _networks - List of networks this Node supports (BTC, ETH, etc.). * @param string _endpoint - The endpoint information in multi addr format. */ function register(bytes8[] _networks, string _endpoint) public returns(bytes32) {} /* * @dev Verify existence of a given Node nonce * @param bytes32 _nodeNonce - Nonce to verify against. */ function isNode(bytes32 _nodeNonce) public view returns(bool) {} /* * @dev Verify ownership of a given Node. * @param address _possibleOwner - The possible owner of the given node we want to verify * @param bytes32 _nodeNonce - The nonce of the Node we want to verify */ function isOwner(address _possibleOwner, bytes32 _nodeNonce) public view returns(bool) {} /* * @dev Returns the owner of the node * @param bytes32 _nodeNonce */ function getNodeOwner(bytes32 _nodeNonce) public view returns(address) {} /* * @dev Returns a paginated list of the nodes owned by the account * @param address _owner * @param uint256 _page */ function getOwnerNodes(address _owner, uint256 _page) public view returns (bytes32[]) {} /* * @dev Returns the Node information given the nonce * @param bytes32 _nodeNonce */ function getNode(bytes32 _nodeNonce) public view returns (bytes32, address, bytes8[], string) {} /* * @dev Returns the length of the nodesIndex array */ function getNodesIndexLength() public view returns (uint256) {} }
allows to register a new Node, returning a bytes32 nonce for the Node, if it doesn't exist already, in which case it will error out. bytes8[] _networks - List of networks this Node supports (BTC, ETH, etc.). string _endpoint - The endpoint information in multi addr format./
function register(bytes8[] _networks, string _endpoint) public returns(bytes32) {}
13,051,802
./full_match/3/0x0A5207e8090bA1C81b59F07fc5555D384Cb68ddd/sources/browser/DonorgMain.sol
set patient details to the chain
function setPatient(string memory Dname,string memory dob,string memory sex,uint256 ph,string memory bg,string memory dorg1,string memory dorg2,string memory dorg3) public { Recieve[rQ] = Details(rQ,Dname,dob,sex,bg,dorg1,dorg2,dorg3); Patient[ph]= Details(rQ,Dname,dob,sex,bg,dorg1,dorg2,dorg3); rQ++; }
8,084,389
pragma solidity ^0.8.0; import "../token/FeiTimedMinter.sol"; import "../oracle/collateralization/ICollateralizationOracleWrapper.sol"; /// @title CollateralizationOracleKeeper /// @notice a FEI timed minter which only rewards when updating the collateralization oracle contract CollateralizationOracleKeeper is FeiTimedMinter { ICollateralizationOracleWrapper public collateralizationOracleWrapper; /** @notice constructor for CollateralizationOracleKeeper @param _core the Core address to reference @param _incentive the incentive amount for calling mint paid in FEI @param _collateralizationOracleWrapper the collateralizationOracleWrapper to incentivize updates only sets the target to this address and mint amount to 0, relying exclusively on the incentive payment to caller */ constructor( address _core, uint256 _incentive, ICollateralizationOracleWrapper _collateralizationOracleWrapper ) FeiTimedMinter(_core, address(this), _incentive, MIN_MINT_FREQUENCY, 0) { collateralizationOracleWrapper = _collateralizationOracleWrapper; } function _afterMint() internal override { collateralizationOracleWrapper.updateIfOutdated(); } } pragma solidity ^0.8.0; import "../refs/CoreRef.sol"; import "../utils/Timed.sol"; import "../utils/Incentivized.sol"; import "../utils/RateLimitedMinter.sol"; import "./IFeiTimedMinter.sol"; /// @title FeiTimedMinter /// @notice a contract which mints FEI to a target address on a timed cadence contract FeiTimedMinter is IFeiTimedMinter, CoreRef, Timed, Incentivized, RateLimitedMinter { /// @notice most frequent that mints can happen uint256 public constant override MIN_MINT_FREQUENCY = 1 hours; // Min 1 hour per mint /// @notice least frequent that mints can happen uint256 public constant override MAX_MINT_FREQUENCY = 30 days; // Max 1 month per mint uint256 private _mintAmount; /// @notice the target receiving minted FEI address public override target; /** @notice constructor for FeiTimedMinter @param _core the Core address to reference @param _target the target for minted FEI @param _incentive the incentive amount for calling mint paid in FEI @param _frequency the frequency minting happens @param _initialMintAmount the initial FEI amount to mint */ constructor( address _core, address _target, uint256 _incentive, uint256 _frequency, uint256 _initialMintAmount ) CoreRef(_core) Timed(_frequency) Incentivized(_incentive) RateLimitedMinter((_initialMintAmount + _incentive) / _frequency, (_initialMintAmount + _incentive), true) { _initTimed(); _setTarget(_target); _setMintAmount(_initialMintAmount); } /// @notice triggers a minting of FEI /// @dev timed and incentivized function mint() public virtual override whenNotPaused afterTime { /// Reset the timer _initTimed(); uint256 amount = mintAmount(); // incentivizing before minting so if there is a partial mint it goes to target not caller _incentivize(); if (amount != 0) { // Calls the overriden RateLimitedMinter _mintFei which includes the rate limiting logic _mintFei(target, amount); emit FeiMinting(msg.sender, amount); } // After mint called whether a "mint" happens or not to allow incentivized target hooks _afterMint(); } function mintAmount() public view virtual override returns (uint256) { return _mintAmount; } /// @notice set the new FEI target function setTarget(address newTarget) external override onlyGovernor { _setTarget(newTarget); } /// @notice set the mint frequency function setFrequency(uint256 newFrequency) external override onlyGovernorOrAdmin { require(newFrequency >= MIN_MINT_FREQUENCY, "FeiTimedMinter: frequency low"); require(newFrequency <= MAX_MINT_FREQUENCY, "FeiTimedMinter: frequency high"); _setDuration(newFrequency); } function setMintAmount(uint256 newMintAmount) external override onlyGovernorOrAdmin { _setMintAmount(newMintAmount); } function _setTarget(address newTarget) internal { require(newTarget != address(0), "FeiTimedMinter: zero address"); address oldTarget = target; target = newTarget; emit TargetUpdate(oldTarget, newTarget); } function _setMintAmount(uint256 newMintAmount) internal { uint256 oldMintAmount = _mintAmount; _mintAmount = newMintAmount; emit MintAmountUpdate(oldMintAmount, newMintAmount); } function _mintFei(address to, uint256 amountIn) internal override(CoreRef, RateLimitedMinter) { RateLimitedMinter._mintFei(to, amountIn); } function _afterMint() internal virtual {} } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./ICoreRef.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title A Reference to Core /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core abstract contract CoreRef is ICoreRef, Pausable { ICore private _core; /// @notice a role used with a subset of governor permissions for this contract only bytes32 public override CONTRACT_ADMIN_ROLE; /// @notice boolean to check whether or not the contract has been initialized. /// cannot be initialized twice. bool private _initialized; constructor(address coreAddress) { _initialize(coreAddress); } /// @notice CoreRef constructor /// @param coreAddress Fei Core to reference function _initialize(address coreAddress) internal { require(!_initialized, "CoreRef: already initialized"); _initialized = true; _core = ICore(coreAddress); _setContractAdminRole(_core.GOVERN_ROLE()); } modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require( _core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller" ); _; } modifier onlyGovernorOrAdmin() { require( _core.isGovernor(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not a governor or contract admin" ); _; } modifier onlyGovernor() { require( _core.isGovernor(msg.sender), "CoreRef: Caller is not a governor" ); _; } modifier onlyGuardianOrGovernor() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender), "CoreRef: Caller is not a guardian or governor" ); _; } modifier onlyFei() { require(msg.sender == address(fei()), "CoreRef: Caller is not FEI"); _; } /// @notice set new Core reference address /// @param newCore the new core address function setCore(address newCore) external override onlyGovernor { require(newCore != address(0), "CoreRef: zero address"); address oldCore = address(_core); _core = ICore(newCore); emit CoreUpdate(oldCore, newCore); } /// @notice sets a new admin role for this contract function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor { _setContractAdminRole(newContractAdminRole); } /// @notice returns whether a given address has the admin role for this contract function isContractAdmin(address _admin) public view override returns (bool) { return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin); } /// @notice set pausable methods to paused function pause() public override onlyGuardianOrGovernor { _pause(); } /// @notice set pausable methods to unpaused function unpause() public override onlyGuardianOrGovernor { _unpause(); } /// @notice address of the Core contract referenced /// @return ICore implementation address function core() public view override returns (ICore) { return _core; } /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function fei() public view override returns (IFei) { return _core.fei(); } /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function tribe() public view override returns (IERC20) { return _core.tribe(); } /// @notice fei balance of contract /// @return fei amount held function feiBalance() public view override returns (uint256) { return fei().balanceOf(address(this)); } /// @notice tribe balance of contract /// @return tribe amount held function tribeBalance() public view override returns (uint256) { return tribe().balanceOf(address(this)); } function _burnFeiHeld() internal { fei().burn(feiBalance()); } function _mintFei(address to, uint256 amount) internal virtual { if (amount != 0) { fei().mint(to, amount); } } function _setContractAdminRole(bytes32 newContractAdminRole) internal { bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE; CONTRACT_ADMIN_ROLE = newContractAdminRole; emit ContractAdminRoleUpdate(oldContractAdminRole, newContractAdminRole); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../core/ICore.sol"; /// @title CoreRef interface /// @author Fei Protocol interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed oldCore, address indexed newCore); event ContractAdminRoleUpdate(bytes32 indexed oldContractAdminRole, bytes32 indexed newContractAdminRole); // ----------- Governor only state changing api ----------- function setCore(address newCore) external; function setContractAdminRole(bytes32 newContractAdminRole) external; // ----------- Governor or Guardian only state changing api ----------- function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function fei() external view returns (IFei); function tribe() external view returns (IERC20); function feiBalance() external view returns (uint256); function tribeBalance() external view returns (uint256); function CONTRACT_ADMIN_ROLE() external view returns (bytes32); function isContractAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IPermissions.sol"; import "../token/IFei.sol"; /// @title Core Interface /// @author Fei Protocol interface ICore is IPermissions { // ----------- Events ----------- event FeiUpdate(address indexed _fei); event TribeUpdate(address indexed _tribe); event GenesisGroupUpdate(address indexed _genesisGroup); event TribeAllocation(address indexed _to, uint256 _amount); event GenesisPeriodComplete(uint256 _timestamp); // ----------- Governor only state changing api ----------- function init() external; // ----------- Governor only state changing api ----------- function setFei(address token) external; function setTribe(address token) external; function allocateTribe(address to, uint256 amount) external; // ----------- Getters ----------- function fei() external view returns (IFei); function tribe() external view returns (IERC20); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; /// @title Permissions interface /// @author Fei Protocol interface IPermissions is IAccessControl { // ----------- Governor only state changing api ----------- function createRole(bytes32 role, bytes32 adminRole) external; function grantMinter(address minter) external; function grantBurner(address burner) external; function grantPCVController(address pcvController) external; function grantGovernor(address governor) external; function grantGuardian(address guardian) external; function revokeMinter(address minter) external; function revokeBurner(address burner) external; function revokePCVController(address pcvController) external; function revokeGovernor(address governor) external; function revokeGuardian(address guardian) external; // ----------- Revoker only state changing api ----------- function revokeOverride(bytes32 role, address account) external; // ----------- Getters ----------- function isBurner(address _address) external view returns (bool); function isMinter(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isGuardian(address _address) external view returns (bool); function isPCVController(address _address) external view returns (bool); function GUARDIAN_ROLE() external view returns (bytes32); function GOVERN_ROLE() external view returns (bytes32); function BURNER_ROLE() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function PCV_CONTROLLER_ROLE() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title FEI stablecoin interface /// @author Fei Protocol interface IFei is IERC20 { // ----------- Events ----------- event Minting( address indexed _to, address indexed _minter, uint256 _amount ); event Burning( address indexed _to, address indexed _burner, uint256 _amount ); event IncentiveContractUpdate( address indexed _incentivized, address indexed _incentiveContract ); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Burner only state changing api ----------- function burnFrom(address account, uint256 amount) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; // ----------- Governor only state changing api ----------- function setIncentiveContract(address account, address incentive) external; // ----------- Getters ----------- function incentiveContract(address account) external view returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title an abstract contract for timed events /// @author Fei Protocol abstract contract Timed { /// @notice the start timestamp of the timed period uint256 public startTime; /// @notice the duration of the timed period uint256 public duration; event DurationUpdate(uint256 oldDuration, uint256 newDuration); event TimerReset(uint256 startTime); constructor(uint256 _duration) { _setDuration(_duration); } modifier duringTime() { require(isTimeStarted(), "Timed: time not started"); require(!isTimeEnded(), "Timed: time ended"); _; } modifier afterTime() { require(isTimeEnded(), "Timed: time not ended"); _; } /// @notice return true if time period has ended function isTimeEnded() public view returns (bool) { return remainingTime() == 0; } /// @notice number of seconds remaining until time is up /// @return remaining function remainingTime() public view returns (uint256) { return duration - timeSinceStart(); // duration always >= timeSinceStart which is on [0,d] } /// @notice number of seconds since contract was initialized /// @return timestamp /// @dev will be less than or equal to duration function timeSinceStart() public view returns (uint256) { if (!isTimeStarted()) { return 0; // uninitialized } uint256 _duration = duration; uint256 timePassed = block.timestamp - startTime; // block timestamp always >= startTime return timePassed > _duration ? _duration : timePassed; } function isTimeStarted() public view returns (bool) { return startTime != 0; } function _initTimed() internal { startTime = block.timestamp; emit TimerReset(block.timestamp); } function _setDuration(uint256 newDuration) internal { require(newDuration != 0, "Timed: zero duration"); uint256 oldDuration = duration; duration = newDuration; emit DurationUpdate(oldDuration, newDuration); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../refs/CoreRef.sol"; /// @title abstract contract for incentivizing keepers /// @author Fei Protocol abstract contract Incentivized is CoreRef { /// @notice FEI incentive for calling keeper functions uint256 public incentiveAmount; event IncentiveUpdate(uint256 oldIncentiveAmount, uint256 newIncentiveAmount); constructor(uint256 _incentiveAmount) { incentiveAmount = _incentiveAmount; emit IncentiveUpdate(0, _incentiveAmount); } /// @notice set the incentiveAmount function setIncentiveAmount(uint256 newIncentiveAmount) public onlyGovernor { uint256 oldIncentiveAmount = incentiveAmount; incentiveAmount = newIncentiveAmount; emit IncentiveUpdate(oldIncentiveAmount, newIncentiveAmount); } /// @notice incentivize a call with incentiveAmount FEI rewards /// @dev no-op if the contract does not have Minter role function _incentivize() internal ifMinterSelf { _mintFei(msg.sender, incentiveAmount); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./RateLimited.sol"; /// @title abstract contract for putting a rate limit on how fast a contract can mint FEI /// @author Fei Protocol abstract contract RateLimitedMinter is RateLimited { uint256 private constant MAX_FEI_LIMIT_PER_SECOND = 10_000e18; // 10000 FEI/s or ~860m FEI/day constructor( uint256 _feiLimitPerSecond, uint256 _mintingBufferCap, bool _doPartialMint ) RateLimited(MAX_FEI_LIMIT_PER_SECOND, _feiLimitPerSecond, _mintingBufferCap, _doPartialMint) {} /// @notice override the FEI minting behavior to enforce a rate limit function _mintFei(address to, uint256 amount) internal virtual override { uint256 mintAmount = _depleteBuffer(amount); super._mintFei(to, mintAmount); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../refs/CoreRef.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; /// @title abstract contract for putting a rate limit on how fast a contract can perform an action e.g. Minting /// @author Fei Protocol abstract contract RateLimited is CoreRef { /// @notice maximum rate limit per second governance can set for this contract uint256 public immutable MAX_RATE_LIMIT_PER_SECOND; /// @notice the rate per second for this contract uint256 public rateLimitPerSecond; /// @notice the last time the buffer was used by the contract uint256 public lastBufferUsedTime; /// @notice the cap of the buffer that can be used at once uint256 public bufferCap; /// @notice a flag for whether to allow partial actions to complete if the buffer is less than amount bool public doPartialAction; /// @notice the buffer at the timestamp of lastBufferUsedTime uint256 private _bufferStored; event BufferCapUpdate(uint256 oldBufferCap, uint256 newBufferCap); event RateLimitPerSecondUpdate(uint256 oldRateLimitPerSecond, uint256 newRateLimitPerSecond); constructor(uint256 _maxRateLimitPerSecond, uint256 _rateLimitPerSecond, uint256 _bufferCap, bool _doPartialAction) { lastBufferUsedTime = block.timestamp; _bufferStored = _bufferCap; _setBufferCap(_bufferCap); require(_rateLimitPerSecond <= _maxRateLimitPerSecond, "RateLimited: rateLimitPerSecond too high"); _setRateLimitPerSecond(_rateLimitPerSecond); MAX_RATE_LIMIT_PER_SECOND = _maxRateLimitPerSecond; doPartialAction = _doPartialAction; } /// @notice set the rate limit per second function setRateLimitPerSecond(uint256 newRateLimitPerSecond) external onlyGovernorOrAdmin { require(newRateLimitPerSecond <= MAX_RATE_LIMIT_PER_SECOND, "RateLimited: rateLimitPerSecond too high"); _setRateLimitPerSecond(newRateLimitPerSecond); } /// @notice set the buffer cap function setbufferCap(uint256 newBufferCap) external onlyGovernorOrAdmin { _setBufferCap(newBufferCap); } /// @notice the amount of action used before hitting limit /// @dev replenishes at rateLimitPerSecond per second up to bufferCap function buffer() public view returns(uint256) { uint256 elapsed = block.timestamp - lastBufferUsedTime; return Math.min(_bufferStored + (rateLimitPerSecond * elapsed), bufferCap); } /** @notice the method that enforces the rate limit. Decreases buffer by "amount". If buffer is <= amount either 1. Does a partial mint by the amount remaining in the buffer or 2. Reverts Depending on whether doPartialAction is true or false */ function _depleteBuffer(uint256 amount) internal returns(uint256) { uint256 newBuffer = buffer(); uint256 usedAmount = amount; if (doPartialAction && usedAmount > newBuffer) { usedAmount = newBuffer; } require(newBuffer != 0, "RateLimited: no rate limit buffer"); require(usedAmount <= newBuffer, "RateLimited: rate limit hit"); _bufferStored = newBuffer - usedAmount; lastBufferUsedTime = block.timestamp; return usedAmount; } function _setRateLimitPerSecond(uint256 newRateLimitPerSecond) internal { // Reset the stored buffer and last buffer used time using the prior RateLimitPerSecond _bufferStored = buffer(); lastBufferUsedTime = block.timestamp; uint256 oldRateLimitPerSecond = rateLimitPerSecond; rateLimitPerSecond = newRateLimitPerSecond; emit RateLimitPerSecondUpdate(oldRateLimitPerSecond, newRateLimitPerSecond); } function _setBufferCap(uint256 newBufferCap) internal { uint256 oldBufferCap = bufferCap; bufferCap = newBufferCap; // Cap the existing stored buffer if (_bufferStored > newBufferCap) { _bufferStored = newBufferCap; } emit BufferCapUpdate(oldBufferCap, newBufferCap); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title a Fei Timed Minter /// @author Fei Protocol interface IFeiTimedMinter { // ----------- Events ----------- event FeiMinting(address indexed caller, uint256 feiAmount); event TargetUpdate(address oldTarget, address newTarget); event MintAmountUpdate(uint256 oldMintAmount, uint256 newMintAmount); // ----------- State changing api ----------- function mint() external; // ----------- Governor only state changing api ----------- function setTarget(address newTarget) external; // ----------- Governor or Admin only state changing api ----------- function setFrequency(uint256 newFrequency) external; function setMintAmount(uint256 newMintAmount) external; // ----------- Getters ----------- function mintAmount() external view returns(uint256); function MIN_MINT_FREQUENCY() external view returns(uint256); function MAX_MINT_FREQUENCY() external view returns(uint256); function target() external view returns(address); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./ICollateralizationOracle.sol"; /// @title Collateralization ratio oracle interface for Fei Protocol /// @author Fei Protocol interface ICollateralizationOracleWrapper is ICollateralizationOracle { // ----------- Events ------------------------------------------------------ event CachedValueUpdate( address from, uint256 indexed protocolControlledValue, uint256 indexed userCirculatingFei, int256 indexed protocolEquity ); event CollateralizationOracleUpdate( address from, address indexed oldOracleAddress, address indexed newOracleAddress ); event DeviationThresholdUpdate( address from, uint256 indexed oldThreshold, uint256 indexed newThreshold ); event ReadPauseOverrideUpdate( bool readPauseOverride ); // ----------- Public state changing api ----------- function updateIfOutdated() external; // ----------- Governor only state changing api ----------- function setValidityDuration(uint256 _validityDuration) external; function setReadPauseOverride(bool newReadPauseOverride) external; function setDeviationThresholdBasisPoints(uint256 _newDeviationThresholdBasisPoints) external; function setCollateralizationOracle(address _newCollateralizationOracle) external; function setCache( uint256 protocolControlledValue, uint256 userCirculatingFei, int256 protocolEquity ) external; // ----------- Getters ----------- function cachedProtocolControlledValue() external view returns (uint256); function cachedUserCirculatingFei() external view returns (uint256); function cachedProtocolEquity() external view returns (int256); function deviationThresholdBasisPoints() external view returns (uint256); function collateralizationOracle() external view returns(address); function isOutdatedOrExceededDeviationThreshold() external view returns (bool); function pcvStatsCurrent() external view returns ( uint256 protocolControlledValue, uint256 userCirculatingFei, int256 protocolEquity, bool validityStatus ); function isExceededDeviationThreshold() external view returns (bool); function readPauseOverride() external view returns(bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../IOracle.sol"; /// @title Collateralization ratio oracle interface for Fei Protocol /// @author Fei Protocol interface ICollateralizationOracle is IOracle { // ----------- Getters ----------- // returns the PCV value, User-circulating FEI, and Protocol Equity, as well // as a validity status. function pcvStats() external view returns ( uint256 protocolControlledValue, uint256 userCirculatingFei, int256 protocolEquity, bool validityStatus ); // true if Protocol Equity > 0 function isOvercollateralized() external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../external/Decimal.sol"; /// @title generic oracle interface for Fei Protocol /// @author Fei Protocol interface IOracle { // ----------- Events ----------- event Update(uint256 _peg); // ----------- State changing API ----------- function update() external; // ----------- Getters ----------- function read() external view returns (Decimal.D256 memory, bool); function isOutdated() external view returns (bool); } /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.4; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 private constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE), reason) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value, reason) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: 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 "./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; /** * @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: 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 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. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT 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. 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; } } }
Collateralization ratio oracle interface for Fei Protocol Fei Protocol ----------- Events ------------------------------------------------------ ----------- Public state changing api ----------- ----------- Governor only state changing api ----------- ----------- Getters -----------
interface ICollateralizationOracleWrapper is ICollateralizationOracle { event CachedValueUpdate( address from, uint256 indexed protocolControlledValue, uint256 indexed userCirculatingFei, int256 indexed protocolEquity ); event CollateralizationOracleUpdate( address from, address indexed oldOracleAddress, address indexed newOracleAddress ); event DeviationThresholdUpdate( address from, uint256 indexed oldThreshold, uint256 indexed newThreshold ); event ReadPauseOverrideUpdate( bool readPauseOverride ); function updateIfOutdated() external; function setValidityDuration(uint256 _validityDuration) external; function setReadPauseOverride(bool newReadPauseOverride) external; function setDeviationThresholdBasisPoints(uint256 _newDeviationThresholdBasisPoints) external; function setCollateralizationOracle(address _newCollateralizationOracle) external; function setCache( uint256 protocolControlledValue, uint256 userCirculatingFei, int256 protocolEquity ) external; function cachedProtocolControlledValue() external view returns (uint256); function cachedUserCirculatingFei() external view returns (uint256); function cachedProtocolEquity() external view returns (int256); function deviationThresholdBasisPoints() external view returns (uint256); function collateralizationOracle() external view returns(address); function isOutdatedOrExceededDeviationThreshold() external view returns (bool); function pcvStatsCurrent() external view returns ( uint256 protocolControlledValue, uint256 userCirculatingFei, int256 protocolEquity, bool validityStatus ); function isExceededDeviationThreshold() external view returns (bool); function readPauseOverride() external view returns(bool); pragma solidity ^0.8.4; }
936,201
./full_match/8453/0xF90FF0F7c8Db52bF1bF869F74226eAD125EFa745/sources/contracts/base/Controller.sol
Only smart contracts will be affected by the whitelist.
function addToWhitelist(address _target) public onlyGovernance { addressWhitelist[_target] = true; emit AddedAddressToWhitelist(_target); }
11,545,401
./partial_match/42/0xcb9A85F1B0f19f778804B75712264d75D6ACBA3F/sources/MasterChef2.sol
Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public{ uint256 recentlyRewardBlock = lastRewardBlock; if(recentlyRewardBlock >= block.number){ return; } uint256[] memory validRankPoolIndex = rankPoolIndex; uint256 maxCount = maxRankNumber; uint256 validRankPoolCount = validRankPoolIndex.length < maxCount? validRankPoolIndex.length: maxCount; if(validRankPoolCount == 0){ return; } recentlyRewardBlock = recentlyRewardBlock.add(1); uint256 totalReward = getRewardToken(recentlyRewardBlock, block.number); uint256 eachPoolReward = totalReward.div(validRankPoolCount); totalReward = eachPoolReward.mul(validRankPoolCount); sashimi.mint(address(this), totalReward); lastRewardBlock = block.number; for(uint256 i = 0; i < validRankPoolCount; i ++){ uint256 existedDividend = poolInfo[validRankPoolIndex[i]].accumulativeDividend; poolInfo[validRankPoolIndex[i]].accumulativeDividend = existedDividend.add(eachPoolReward); } }
3,368,094
/** RMONEY - the next big meme token (exclusively run by the community) ================== COMMUNITY: https://t.me/RMONEYx ================== This s a stealth fairlaunch project which will be run by the community. Sometimes life can throw you curveballs. Sometimes things seem impossible. Sometimes life can get you down. But just one look at RMONEY and not only will it have you smiling, you will believe in the impossible. Some features of RMONEY: - 2% fee auto add to the liquidity pool with each and every transaction - 2% fee auto distribute to all holders wit each and every transaction - 40% burn of all total tokens before going live on UNISWAP. - All liquidity LPs sent to burnt address - Ownership will be renounced shortly after launch RMONEY will start with 1.5 ETH in liquidity so no whales will be present. As more holders buy, you can then increase your buy orders. 100,000,000,000,000,000 total supply with 40% burnt before launch Welcome to RMONEY. */ pragma solidity ^0.6.12; // SPDX-License-Identifier: Unlicensed interface IERC20 { 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. */ 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; } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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; address private _previousOwner; uint256 private _lockTime; 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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(now > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract RMONEY is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 100000000000 * 10**6 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "RMONEY | t.me/RMONEYx"; string private _symbol = "RMONEY \xF0\x9F\x92\x8E"; uint8 private _decimals = 9; uint256 public _taxFee = 2; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 2; uint256 private _previousLiquidityFee = _liquidityFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 500000000 * 10**6 * 10**9; uint256 private numTokensSellToAddToLiquidity = 50000000 * 10**6 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () public { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } 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; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { 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 _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
SPDX-License-Identifier: Unlicensed
interface IERC20 { function totalSupply() 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); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); RMONEY - the next big meme token (exclusively run by the community) }
12,105,379
/** *Submitted for verification at Etherscan.io on 2019-12-06 */ // File: ../../mosaic-contracts/contracts/lib/RLP.sol pragma solidity ^0.5.0; /** * @title RLPReader * * RLPReader is used to read and parse RLP encoded data in memory. * * @author Andreas Olofsson ([email protected]) */ library RLP { /** Constants */ uint constant DATA_SHORT_START = 0x80; uint constant DATA_LONG_START = 0xB8; uint constant LIST_SHORT_START = 0xC0; uint constant LIST_LONG_START = 0xF8; uint constant DATA_LONG_OFFSET = 0xB7; uint constant LIST_LONG_OFFSET = 0xF7; /** Storage */ struct RLPItem { uint _unsafe_memPtr; // Pointer to the RLP-encoded bytes. uint _unsafe_length; // Number of bytes. This is the full length of the string. } struct Iterator { RLPItem _unsafe_item; // Item that's being iterated over. uint _unsafe_nextPtr; // Position of the next item in the list. } /* Internal Functions */ /** Iterator */ function next( Iterator memory self ) internal pure returns (RLPItem memory subItem_) { require(hasNext(self)); uint ptr = self._unsafe_nextPtr; uint itemLength = _itemLength(ptr); subItem_._unsafe_memPtr = ptr; subItem_._unsafe_length = itemLength; self._unsafe_nextPtr = ptr + itemLength; } function next( Iterator memory self, bool strict ) internal pure returns (RLPItem memory subItem_) { subItem_ = next(self); require(!(strict && !_validate(subItem_))); } function hasNext(Iterator memory self) internal pure returns (bool) { RLPItem memory item = self._unsafe_item; return self._unsafe_nextPtr < item._unsafe_memPtr + item._unsafe_length; } /** RLPItem */ /** * @dev Creates an RLPItem from an array of RLP encoded bytes. * * @param self The RLP encoded bytes. * * @return An RLPItem. */ function toRLPItem( bytes memory self ) internal pure returns (RLPItem memory) { uint len = self.length; if (len == 0) { return RLPItem(0, 0); } uint memPtr; /* solium-disable-next-line */ assembly { memPtr := add(self, 0x20) } return RLPItem(memPtr, len); } /** * @dev Creates an RLPItem from an array of RLP encoded bytes. * * @param self The RLP encoded bytes. * @param strict Will throw if the data is not RLP encoded. * * @return An RLPItem. */ function toRLPItem( bytes memory self, bool strict ) internal pure returns (RLPItem memory) { RLPItem memory item = toRLPItem(self); if(strict) { uint len = self.length; require(_payloadOffset(item) <= len); require(_itemLength(item._unsafe_memPtr) == len); require(_validate(item)); } return item; } /** * @dev Check if the RLP item is null. * * @param self The RLP item. * * @return 'true' if the item is null. */ function isNull(RLPItem memory self) internal pure returns (bool ret) { return self._unsafe_length == 0; } /** * @dev Check if the RLP item is a list. * * @param self The RLP item. * * @return 'true' if the item is a list. */ function isList(RLPItem memory self) internal pure returns (bool ret) { if (self._unsafe_length == 0) { return false; } uint memPtr = self._unsafe_memPtr; /* solium-disable-next-line */ assembly { ret := iszero(lt(byte(0, mload(memPtr)), 0xC0)) } } /** * @dev Check if the RLP item is data. * * @param self The RLP item. * * @return 'true' if the item is data. */ function isData(RLPItem memory self) internal pure returns (bool ret) { if (self._unsafe_length == 0) { return false; } uint memPtr = self._unsafe_memPtr; /* solium-disable-next-line */ assembly { ret := lt(byte(0, mload(memPtr)), 0xC0) } } /** * @dev Check if the RLP item is empty (string or list). * * @param self The RLP item. * * @return 'true' if the item is null. */ function isEmpty(RLPItem memory self) internal pure returns (bool ret) { if(isNull(self)) { return false; } uint b0; uint memPtr = self._unsafe_memPtr; /* solium-disable-next-line */ assembly { b0 := byte(0, mload(memPtr)) } return (b0 == DATA_SHORT_START || b0 == LIST_SHORT_START); } /** * @dev Get the number of items in an RLP encoded list. * * @param self The RLP item. * * @return The number of items. */ function items(RLPItem memory self) internal pure returns (uint) { if (!isList(self)) { return 0; } uint b0; uint memPtr = self._unsafe_memPtr; /* solium-disable-next-line */ assembly { b0 := byte(0, mload(memPtr)) } uint pos = memPtr + _payloadOffset(self); uint last = memPtr + self._unsafe_length - 1; uint itms; while(pos <= last) { pos += _itemLength(pos); itms++; } return itms; } /** * @dev Create an iterator. * * @param self The RLP item. * * @return An 'Iterator' over the item. */ function iterator( RLPItem memory self ) internal pure returns (Iterator memory it_) { require (isList(self)); uint ptr = self._unsafe_memPtr + _payloadOffset(self); it_._unsafe_item = self; it_._unsafe_nextPtr = ptr; } /** * @dev Return the RLP encoded bytes. * * @param self The RLPItem. * * @return The bytes. */ function toBytes( RLPItem memory self ) internal pure returns (bytes memory bts_) { uint len = self._unsafe_length; if (len == 0) { return bts_; } bts_ = new bytes(len); _copyToBytes(self._unsafe_memPtr, bts_, len); } /** * @dev Decode an RLPItem into bytes. This will not work if the RLPItem is a list. * * @param self The RLPItem. * * @return The decoded string. */ function toData( RLPItem memory self ) internal pure returns (bytes memory bts_) { require(isData(self)); uint rStartPos; uint len; (rStartPos, len) = _decode(self); bts_ = new bytes(len); _copyToBytes(rStartPos, bts_, len); } /** * @dev Get the list of sub-items from an RLP encoded list. * Warning: This is inefficient, as it requires that the list is read twice. * * @param self The RLP item. * * @return Array of RLPItems. */ function toList( RLPItem memory self ) internal pure returns (RLPItem[] memory list_) { require(isList(self)); uint numItems = items(self); list_ = new RLPItem[](numItems); Iterator memory it = iterator(self); uint idx = 0; while(hasNext(it)) { list_[idx] = next(it); idx++; } } /** * @dev Decode an RLPItem into an ascii string. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return The decoded string. */ function toAscii( RLPItem memory self ) internal pure returns (string memory str_) { require(isData(self)); uint rStartPos; uint len; (rStartPos, len) = _decode(self); bytes memory bts = new bytes(len); _copyToBytes(rStartPos, bts, len); str_ = string(bts); } /** * @dev Decode an RLPItem into a uint. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return The decoded string. */ function toUint(RLPItem memory self) internal pure returns (uint data_) { require(isData(self)); uint rStartPos; uint len; (rStartPos, len) = _decode(self); if (len > 32 || len == 0) { revert(); } /* solium-disable-next-line */ assembly { data_ := div(mload(rStartPos), exp(256, sub(32, len))) } } /** * @dev Decode an RLPItem into a boolean. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return The decoded string. */ function toBool(RLPItem memory self) internal pure returns (bool data) { require(isData(self)); uint rStartPos; uint len; (rStartPos, len) = _decode(self); require(len == 1); uint temp; /* solium-disable-next-line */ assembly { temp := byte(0, mload(rStartPos)) } require (temp <= 1); return temp == 1 ? true : false; } /** * @dev Decode an RLPItem into a byte. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return The decoded string. */ function toByte(RLPItem memory self) internal pure returns (byte data) { require(isData(self)); uint rStartPos; uint len; (rStartPos, len) = _decode(self); require(len == 1); uint temp; /* solium-disable-next-line */ assembly { temp := byte(0, mload(rStartPos)) } return byte(uint8(temp)); } /** * @dev Decode an RLPItem into an int. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return The decoded string. */ function toInt(RLPItem memory self) internal pure returns (int data) { return int(toUint(self)); } /** * @dev Decode an RLPItem into a bytes32. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return The decoded string. */ function toBytes32( RLPItem memory self ) internal pure returns (bytes32 data) { return bytes32(toUint(self)); } /** * @dev Decode an RLPItem into an address. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return The decoded string. */ function toAddress( RLPItem memory self ) internal pure returns (address data) { require(isData(self)); uint rStartPos; uint len; (rStartPos, len) = _decode(self); require (len == 20); /* solium-disable-next-line */ assembly { data := div(mload(rStartPos), exp(256, 12)) } } /** * @dev Decode an RLPItem into an address. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return Get the payload offset. */ function _payloadOffset(RLPItem memory self) private pure returns (uint) { if(self._unsafe_length == 0) return 0; uint b0; uint memPtr = self._unsafe_memPtr; /* solium-disable-next-line */ assembly { b0 := byte(0, mload(memPtr)) } if(b0 < DATA_SHORT_START) return 0; if(b0 < DATA_LONG_START || (b0 >= LIST_SHORT_START && b0 < LIST_LONG_START)) return 1; if(b0 < LIST_SHORT_START) return b0 - DATA_LONG_OFFSET + 1; return b0 - LIST_LONG_OFFSET + 1; } /** * @dev Decode an RLPItem into an address. This will not work if the * RLPItem is a list. * * @param memPtr Memory pointer. * * @return Get the full length of an RLP item. */ function _itemLength(uint memPtr) private pure returns (uint len) { uint b0; /* solium-disable-next-line */ assembly { b0 := byte(0, mload(memPtr)) } if (b0 < DATA_SHORT_START) { len = 1; } else if (b0 < DATA_LONG_START) { len = b0 - DATA_SHORT_START + 1; } else if (b0 < LIST_SHORT_START) { /* solium-disable-next-line */ assembly { let bLen := sub(b0, 0xB7) // bytes length (DATA_LONG_OFFSET) let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length len := add(1, add(bLen, dLen)) // total length } } else if (b0 < LIST_LONG_START) { len = b0 - LIST_SHORT_START + 1; } else { /* solium-disable-next-line */ assembly { let bLen := sub(b0, 0xF7) // bytes length (LIST_LONG_OFFSET) let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length len := add(1, add(bLen, dLen)) // total length } } } /** * @dev Decode an RLPItem into an address. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return Get the full length of an RLP item. */ function _decode( RLPItem memory self ) private pure returns (uint memPtr_, uint len_) { require(isData(self)); uint b0; uint start = self._unsafe_memPtr; /* solium-disable-next-line */ assembly { b0 := byte(0, mload(start)) } if (b0 < DATA_SHORT_START) { memPtr_ = start; len_ = 1; return (memPtr_, len_); } if (b0 < DATA_LONG_START) { len_ = self._unsafe_length - 1; memPtr_ = start + 1; } else { uint bLen; /* solium-disable-next-line */ assembly { bLen := sub(b0, 0xB7) // DATA_LONG_OFFSET } len_ = self._unsafe_length - 1 - bLen; memPtr_ = start + bLen + 1; } } /** * @dev Assumes that enough memory has been allocated to store in target. * Gets the full length of an RLP item. * * @param btsPtr Bytes pointer. * @param tgt Last item to be allocated. * @param btsLen Bytes length. */ function _copyToBytes( uint btsPtr, bytes memory tgt, uint btsLen ) private pure { // Exploiting the fact that 'tgt' was the last thing to be allocated, // we can write entire words, and just overwrite any excess. /* solium-disable-next-line */ assembly { let i := 0 // Start at arr + 0x20 let stopOffset := add(btsLen, 31) let rOffset := btsPtr let wOffset := add(tgt, 32) for {} lt(i, stopOffset) { i := add(i, 32) } { mstore(add(wOffset, i), mload(add(rOffset, i))) } } } /** * @dev Check that an RLP item is valid. * * @param self The RLPItem. */ function _validate(RLPItem memory self) private pure returns (bool ret) { // Check that RLP is well-formed. uint b0; uint b1; uint memPtr = self._unsafe_memPtr; /* solium-disable-next-line */ assembly { b0 := byte(0, mload(memPtr)) b1 := byte(1, mload(memPtr)) } if(b0 == DATA_SHORT_START + 1 && b1 < DATA_SHORT_START) return false; return true; } } // File: ../../mosaic-contracts/contracts/lib/MerklePatriciaProof.sol pragma solidity ^0.5.0; /** * @title MerklePatriciaVerifier * @author Sam Mayo ([email protected]) * * @dev Library for verifing merkle patricia proofs. */ library MerklePatriciaProof { /** * @dev Verifies a merkle patricia proof. * @param value The terminating value in the trie. * @param encodedPath The path in the trie leading to value. * @param rlpParentNodes The rlp encoded stack of nodes. * @param root The root hash of the trie. * @return The boolean validity of the proof. */ function verify( bytes32 value, bytes calldata encodedPath, bytes calldata rlpParentNodes, bytes32 root ) external pure returns (bool) { RLP.RLPItem memory item = RLP.toRLPItem(rlpParentNodes); RLP.RLPItem[] memory parentNodes = RLP.toList(item); bytes memory currentNode; RLP.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint pathPtr = 0; bytes memory path = _getNibbleArray2(encodedPath); if(path.length == 0) {return false;} for (uint i=0; i<parentNodes.length; i++) { if(pathPtr > path.length) {return false;} currentNode = RLP.toBytes(parentNodes[i]); if(nodeKey != keccak256(abi.encodePacked(currentNode))) {return false;} currentNodeList = RLP.toList(parentNodes[i]); if(currentNodeList.length == 17) { if(pathPtr == path.length) { if(keccak256(abi.encodePacked(RLP.toBytes(currentNodeList[16]))) == value) { return true; } else { return false; } } uint8 nextPathNibble = uint8(path[pathPtr]); if(nextPathNibble > 16) {return false;} nodeKey = RLP.toBytes32(currentNodeList[nextPathNibble]); pathPtr += 1; } else if(currentNodeList.length == 2) { // Count of matching node key nibbles in path starting from pathPtr. uint traverseLength = _nibblesToTraverse(RLP.toData(currentNodeList[0]), path, pathPtr); if(pathPtr + traverseLength == path.length) { //leaf node if(keccak256(abi.encodePacked(RLP.toData(currentNodeList[1]))) == value) { return true; } else { return false; } } else if (traverseLength == 0) { // error: couldn't traverse path return false; } else { // extension node pathPtr += traverseLength; nodeKey = RLP.toBytes32(currentNodeList[1]); } } else { return false; } } } function verifyDebug( bytes32 value, bytes memory not_encodedPath, bytes memory rlpParentNodes, bytes32 root ) public pure returns (bool res_, uint loc_, bytes memory path_debug_) { RLP.RLPItem memory item = RLP.toRLPItem(rlpParentNodes); RLP.RLPItem[] memory parentNodes = RLP.toList(item); bytes memory currentNode; RLP.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint pathPtr = 0; bytes memory path = _getNibbleArray2(not_encodedPath); path_debug_ = path; if(path.length == 0) { loc_ = 0; res_ = false; return (res_, loc_, path_debug_); } for (uint i=0; i<parentNodes.length; i++) { if(pathPtr > path.length) { loc_ = 1; res_ = false; return (res_, loc_, path_debug_); } currentNode = RLP.toBytes(parentNodes[i]); if(nodeKey != keccak256(abi.encodePacked(currentNode))) { res_ = false; loc_ = 100 + i; return (res_, loc_, path_debug_); } currentNodeList = RLP.toList(parentNodes[i]); loc_ = currentNodeList.length; if(currentNodeList.length == 17) { if(pathPtr == path.length) { if(keccak256(abi.encodePacked(RLP.toBytes(currentNodeList[16]))) == value) { res_ = true; return (res_, loc_, path_debug_); } else { loc_ = 3; return (res_, loc_, path_debug_); } } uint8 nextPathNibble = uint8(path[pathPtr]); if(nextPathNibble > 16) { loc_ = 4; return (res_, loc_, path_debug_); } nodeKey = RLP.toBytes32(currentNodeList[nextPathNibble]); pathPtr += 1; } else if(currentNodeList.length == 2) { pathPtr += _nibblesToTraverse(RLP.toData(currentNodeList[0]), path, pathPtr); if(pathPtr == path.length) {//leaf node if(keccak256(abi.encodePacked(RLP.toData(currentNodeList[1]))) == value) { res_ = true; return (res_, loc_, path_debug_); } else { loc_ = 5; return (res_, loc_, path_debug_); } } //extension node if(_nibblesToTraverse(RLP.toData(currentNodeList[0]), path, pathPtr) == 0) { loc_ = 6; res_ = (keccak256(abi.encodePacked()) == value); return (res_, loc_, path_debug_); } nodeKey = RLP.toBytes32(currentNodeList[1]); } else { loc_ = 7; return (res_, loc_, path_debug_); } } loc_ = 8; } function _nibblesToTraverse( bytes memory encodedPartialPath, bytes memory path, uint pathPtr ) private pure returns (uint len_) { // encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath // and slicedPath have elements that are each one hex character (1 nibble) bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length); // pathPtr counts nibbles in path // partialPath.length is a number of nibbles for(uint i=pathPtr; i<pathPtr+partialPath.length; i++) { byte pathNibble = path[i]; slicedPath[i-pathPtr] = pathNibble; } if(keccak256(abi.encodePacked(partialPath)) == keccak256(abi.encodePacked(slicedPath))) { len_ = partialPath.length; } else { len_ = 0; } } // bytes b must be hp encoded function _getNibbleArray( bytes memory b ) private pure returns (bytes memory nibbles_) { if(b.length>0) { uint8 offset; uint8 hpNibble = uint8(_getNthNibbleOfBytes(0,b)); if(hpNibble == 1 || hpNibble == 3) { nibbles_ = new bytes(b.length*2-1); byte oddNibble = _getNthNibbleOfBytes(1,b); nibbles_[0] = oddNibble; offset = 1; } else { nibbles_ = new bytes(b.length*2-2); offset = 0; } for(uint i=offset; i<nibbles_.length; i++) { nibbles_[i] = _getNthNibbleOfBytes(i-offset+2,b); } } } // normal byte array, no encoding used function _getNibbleArray2( bytes memory b ) private pure returns (bytes memory nibbles_) { nibbles_ = new bytes(b.length*2); for (uint i = 0; i < nibbles_.length; i++) { nibbles_[i] = _getNthNibbleOfBytes(i, b); } } function _getNthNibbleOfBytes( uint n, bytes memory str ) private pure returns (byte) { return byte(n%2==0 ? uint8(str[n/2])/0x10 : uint8(str[n/2])%0x10); } } // File: ../../mosaic-contracts/contracts/lib/SafeMath.sol pragma solidity ^0.5.0; // Copyright 2019 OpenST Ltd. // // 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. // // ---------------------------------------------------------------------------- // // http://www.simpletoken.org/ // // Based on the SafeMath library by the OpenZeppelin team. // Copyright (c) 2018 Smart Contract Solutions, Inc. // https://github.com/OpenZeppelin/zeppelin-solidity // The MIT License. // ---------------------------------------------------------------------------- /** * @title SafeMath library. * * @notice Based on the SafeMath library by the OpenZeppelin team. * * @dev Math operations with safety checks that revert on error. */ library SafeMath { /* Internal Functions */ /** * @notice Multiplies two numbers, reverts on overflow. * * @param a Unsigned integer multiplicand. * @param b Unsigned integer multiplier. * * @return uint256 Product. */ 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, "Overflow when multiplying." ); return c; } /** * @notice Integer division of two numbers truncating the quotient, reverts * on division by zero. * * @param a Unsigned integer dividend. * @param b Unsigned integer divisor. * * @return uint256 Quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0. require( b > 0, "Cannot do attempted division by less than or equal to zero." ); uint256 c = a / b; // There is no case in which the following doesn't hold: // assert(a == b * c + a % b); return c; } /** * @notice Subtracts two numbers, reverts on underflow (i.e. if subtrahend * is greater than minuend). * * @param a Unsigned integer minuend. * @param b Unsigned integer subtrahend. * * @return uint256 Difference. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require( b <= a, "Underflow when subtracting." ); uint256 c = a - b; return c; } /** * @notice Adds two numbers, reverts on overflow. * * @param a Unsigned integer augend. * @param b Unsigned integer addend. * * @return uint256 Sum. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require( c >= a, "Overflow when adding." ); return c; } /** * @notice Divides two numbers and returns the remainder (unsigned integer * modulo), reverts when dividing by zero. * * @param a Unsigned integer dividend. * @param b Unsigned integer divisor. * * @return uint256 Remainder. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require( b != 0, "Cannot do attempted division by zero (in `mod()`)." ); return a % b; } } // File: ../../mosaic-contracts/contracts/lib/BytesLib.sol pragma solidity ^0.5.0; library BytesLib { function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory bytes_) { /* solium-disable-next-line */ assembly { // Get a location of some free memory and store it in bytes_ as // Solidity does for memory variables. bytes_ := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for bytes_. let length := mload(_preBytes) mstore(bytes_, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(bytes_, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the bytes_ memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of bytes_ // and store it as the new length in the first 32 bytes of the // bytes_ memory. length := mload(_postBytes) mstore(bytes_, add(length, mload(bytes_))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of bytes_ to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } } // Pad a bytes array to 32 bytes function leftPad( bytes memory _bytes ) internal pure returns (bytes memory padded_) { bytes memory padding = new bytes(32 - _bytes.length); padded_ = concat(padding, _bytes); } /** * @notice Convert bytes32 to bytes * * @param _inBytes32 bytes32 value * * @return bytes value */ function bytes32ToBytes(bytes32 _inBytes32) internal pure returns (bytes memory bytes_) { bytes_ = new bytes(32); /* solium-disable-next-line */ assembly { mstore(add(32, bytes_), _inBytes32) } } } // File: ../../mosaic-contracts/contracts/lib/MessageBus.sol pragma solidity ^0.5.0; // Copyright 2019 OpenST Ltd. // // 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. // // ---------------------------------------------------------------------------- // // http://www.simpletoken.org/ // // ---------------------------------------------------------------------------- library MessageBus { /* Usings */ using SafeMath for uint256; /* Enums */ /** Status of the message state machine. */ enum MessageStatus { Undeclared, Declared, Progressed, DeclaredRevocation, Revoked } /** Status of the message state machine. */ enum MessageBoxType { Outbox, Inbox } /* Structs */ /** MessageBox stores the inbox and outbox mapping. */ struct MessageBox { /** Maps message hash to the MessageStatus. */ mapping(bytes32 => MessageStatus) outbox; /** Maps message hash to the MessageStatus. */ mapping(bytes32 => MessageStatus) inbox; } /** A Message is sent between gateways. */ struct Message { /** Intent hash of specific request type. */ bytes32 intentHash; /** Nonce of the sender. */ uint256 nonce; /** Gas price that sender will pay for reward. */ uint256 gasPrice; /** Gas limit that sender will pay. */ uint256 gasLimit; /** Address of the message sender. */ address sender; /** Hash lock provided by the facilitator. */ bytes32 hashLock; /** * The amount of the gas consumed, this is used for reward * calculation. */ uint256 gasConsumed; } /* Constants */ bytes32 public constant MESSAGE_TYPEHASH = keccak256( abi.encode( "Message(bytes32 intentHash,uint256 nonce,uint256 gasPrice,uint256 gasLimit,address sender,bytes32 hashLock)" ) ); /** * Position of outbox in struct MessageBox. * This is used to generate storage merkel proof. */ uint8 public constant OUTBOX_OFFSET = 0; /** * Position of inbox in struct MessageBox. * This is used to generate storage merkel proof. */ uint8 public constant INBOX_OFFSET = 1; /* External Functions */ /** * @notice Declare a new message. This will update the outbox status to * `Declared` for the given message hash. * * @param _messageBox Message Box. * @param _message Message object. * * @return messageHash_ Message hash */ function declareMessage( MessageBox storage _messageBox, Message storage _message ) public //inject PUBLIC FUNC TO EXTERNAL returns (bytes32 messageHash_) { messageHash_ = messageDigest(_message); require( _messageBox.outbox[messageHash_] == MessageStatus.Undeclared, "Message on source must be Undeclared." ); // Update the outbox message status to `Declared`. _messageBox.outbox[messageHash_] = MessageStatus.Declared; } /** * @notice Confirm a new message that is declared in outbox on the source * chain. Merkle proof will be performed to verify the declared * status in source chains outbox. This will update the inbox * status to `Declared` for the given message hash. * * @param _messageBox Message Box. * @param _message Message object. * @param _rlpParentNodes RLP encoded parent node data to prove in * messageBox outbox. * @param _messageBoxOffset position of the messageBox. * @param _storageRoot Storage root for proof. * * @return messageHash_ Message hash. */ function confirmMessage( MessageBox storage _messageBox, Message storage _message, bytes calldata _rlpParentNodes, uint8 _messageBoxOffset, bytes32 _storageRoot ) external returns (bytes32 messageHash_) { messageHash_ = messageDigest(_message); require( _messageBox.inbox[messageHash_] == MessageStatus.Undeclared, "Message on target must be Undeclared." ); // Get the storage path to verify proof. bytes memory path = BytesLib.bytes32ToBytes( storageVariablePathForStruct( _messageBoxOffset, OUTBOX_OFFSET, messageHash_ ) ); // Verify the merkle proof. require( MerklePatriciaProof.verify( keccak256(abi.encodePacked(MessageStatus.Declared)), path, _rlpParentNodes, _storageRoot ), "Merkle proof verification failed." ); // Update the message box inbox status to `Declared`. _messageBox.inbox[messageHash_] = MessageStatus.Declared; } /** * @notice Update the outbox message hash status to `Progressed`. * * @param _messageBox Message Box. * @param _message Message object. * @param _unlockSecret Unlock secret for the hash lock provided while * declaration. * * @return messageHash_ Message hash. */ function progressOutbox( MessageBox storage _messageBox, Message storage _message, bytes32 _unlockSecret ) public //inject PUBLIC FUNC TO EXTERNAL returns (bytes32 messageHash_) { require( _message.hashLock == keccak256(abi.encode(_unlockSecret)), "Invalid unlock secret." ); messageHash_ = messageDigest(_message); require( _messageBox.outbox[messageHash_] == MessageStatus.Declared, "Message on source must be Declared." ); // Update the outbox message status to `Progressed`. _messageBox.outbox[messageHash_] = MessageStatus.Progressed; } /** * @notice Update the status for the outbox for a given message hash to * `Progressed`. Merkle proof is used to verify status of inbox in * source chain. This is an alternative approach to hashlocks. * * @dev The messsage status for the message hash in the inbox should be * either `Declared` or `Progresses`. Either of this status will be * verified with the merkle proof. * * @param _messageBox Message Box. * @param _message Message object. * @param _rlpParentNodes RLP encoded parent node data to prove in * messageBox inbox. * @param _messageBoxOffset Position of the messageBox. * @param _storageRoot Storage root for proof. * @param _messageStatus Message status of message hash in the inbox of * source chain. * * @return messageHash_ Message hash. */ function progressOutboxWithProof( MessageBox storage _messageBox, Message storage _message, bytes calldata _rlpParentNodes, uint8 _messageBoxOffset, bytes32 _storageRoot, MessageStatus _messageStatus ) external returns (bytes32 messageHash_) { messageHash_ = messageDigest(_message); if(_messageBox.outbox[messageHash_] == MessageStatus.Declared) { /* * The inbox message status of target must be either `Declared` or * `Progressed` when outbox message status at source is `Declared`. */ require( _messageStatus == MessageStatus.Declared || _messageStatus == MessageStatus.Progressed, "Message on target must be Declared or Progressed." ); } else if (_messageBox.outbox[messageHash_] == MessageStatus.DeclaredRevocation) { /* * The inbox message status of target must be either `Progressed` * when outbox message status at source is `DeclaredRevocation`. */ require( _messageStatus == MessageStatus.Progressed, "Message on target must be Progressed." ); } else { revert("Status of message on source must be Declared or DeclareRevocation."); } bytes memory storagePath = BytesLib.bytes32ToBytes( storageVariablePathForStruct( _messageBoxOffset, INBOX_OFFSET, messageHash_ ) ); // Verify the merkle proof. require( MerklePatriciaProof.verify( keccak256(abi.encodePacked(_messageStatus)), storagePath, _rlpParentNodes, _storageRoot), "Merkle proof verification failed." ); _messageBox.outbox[messageHash_] = MessageStatus.Progressed; } /** * @notice Update the status for the inbox for a given message hash to * `Progressed` * * @param _messageBox Message Box. * @param _message Message object. * @param _unlockSecret Unlock secret for the hash lock provided while * declaration. * * @return messageHash_ Message hash. */ function progressInbox( MessageBox storage _messageBox, Message storage _message, bytes32 _unlockSecret ) public //inject PUBLIC FUNC TO EXTERNAL returns (bytes32 messageHash_) { require( _message.hashLock == keccak256(abi.encode(_unlockSecret)), "Invalid unlock secret." ); messageHash_ = messageDigest(_message); require( _messageBox.inbox[messageHash_] == MessageStatus.Declared, "Message on target status must be Declared." ); _messageBox.inbox[messageHash_] = MessageStatus.Progressed; } /** * @notice Update the status for the inbox for a given message hash to * `Progressed`. Merkle proof is used to verify status of outbox in * source chain. This is an alternative approach to hashlocks. * * @dev The messsage status for the message hash in the outbox should be * either `Declared` or `Progresses`. Either of this status will be * verified in the merkle proof. * * @param _messageBox Message Box. * @param _message Message object. * @param _rlpParentNodes RLP encoded parent node data to prove in * messageBox outbox. * @param _messageBoxOffset Position of the messageBox. * @param _storageRoot Storage root for proof. * @param _messageStatus Message status of message hash in the outbox of * source chain. * * @return messageHash_ Message hash. */ function progressInboxWithProof( MessageBox storage _messageBox, Message storage _message, bytes calldata _rlpParentNodes, uint8 _messageBoxOffset, bytes32 _storageRoot, MessageStatus _messageStatus ) external returns (bytes32 messageHash_) { // Outbox message status must be either `Declared` or `Progressed`. require( _messageStatus == MessageStatus.Declared || _messageStatus == MessageStatus.Progressed, "Message on source must be Declared or Progressed." ); messageHash_ = messageDigest(_message); require( _messageBox.inbox[messageHash_] == MessageStatus.Declared, "Message on target must be Declared." ); // The outbox is at location OUTBOX_OFFSET of the MessageBox struct. bytes memory path = BytesLib.bytes32ToBytes( storageVariablePathForStruct( _messageBoxOffset, OUTBOX_OFFSET, messageHash_ ) ); // Perform the merkle proof. require( MerklePatriciaProof.verify( keccak256(abi.encodePacked(_messageStatus)), path, _rlpParentNodes, _storageRoot ), "Merkle proof verification failed." ); _messageBox.inbox[messageHash_] = MessageStatus.Progressed; } /** * @notice Declare a new revocation message. This will update the outbox * status to `DeclaredRevocation` for the given message hash. * * @dev In order to declare revocation the existing message status for the * given message hash should be `Declared`. * * @param _messageBox Message Box. * @param _message Message object. * * @return messageHash_ Message hash. */ function declareRevocationMessage( MessageBox storage _messageBox, Message storage _message ) public //inject PUBLIC FUNC TO EXTERNAL returns (bytes32 messageHash_) { messageHash_ = messageDigest(_message); require( _messageBox.outbox[messageHash_] == MessageStatus.Declared, "Message on source must be Declared." ); _messageBox.outbox[messageHash_] = MessageStatus.DeclaredRevocation; } /** * @notice Confirm a revocation message that is declared in the outbox of * source chain. This will update the outbox status to * `Revoked` for the given message hash. * * @dev In order to declare revocation the existing message status for the * given message hash should be `Declared`. * * @param _messageBox Message Box. * @param _message Message object. * @param _rlpParentNodes RLP encoded parent node data to prove in * messageBox outbox. * @param _messageBoxOffset Position of the messageBox. * @param _storageRoot Storage root for proof. * * @return messageHash_ Message hash. */ function confirmRevocation( MessageBox storage _messageBox, Message storage _message, bytes calldata _rlpParentNodes, uint8 _messageBoxOffset, bytes32 _storageRoot ) external returns (bytes32 messageHash_) { messageHash_ = messageDigest(_message); require( _messageBox.inbox[messageHash_] == MessageStatus.Declared, "Message on target must be Declared." ); // Get the path. bytes memory path = BytesLib.bytes32ToBytes( storageVariablePathForStruct( _messageBoxOffset, OUTBOX_OFFSET, messageHash_ ) ); // Perform the merkle proof. require( MerklePatriciaProof.verify( keccak256(abi.encodePacked(MessageStatus.DeclaredRevocation)), path, _rlpParentNodes, _storageRoot ), "Merkle proof verification failed." ); _messageBox.inbox[messageHash_] = MessageStatus.Revoked; } /** * @notice Update the status for the outbox for a given message hash to * `Revoked`. Merkle proof is used to verify status of inbox in * source chain. * * @dev The messsage status in the inbox should be * either `DeclaredRevocation` or `Revoked`. Either of this status * will be verified in the merkle proof. * * @param _messageBox Message Box. * @param _message Message object. * @param _messageBoxOffset Position of the messageBox. * @param _rlpParentNodes RLP encoded parent node data to prove in * messageBox inbox. * @param _storageRoot Storage root for proof. * @param _messageStatus Message status of message hash in the inbox of * source chain. * * @return messageHash_ Message hash. */ function progressOutboxRevocation( MessageBox storage _messageBox, Message storage _message, uint8 _messageBoxOffset, bytes calldata _rlpParentNodes, bytes32 _storageRoot, MessageStatus _messageStatus ) external returns (bytes32 messageHash_) { require( _messageStatus == MessageStatus.Revoked, "Message on target status must be Revoked." ); messageHash_ = messageDigest(_message); require( _messageBox.outbox[messageHash_] == MessageStatus.DeclaredRevocation, "Message status on source must be DeclaredRevocation." ); // The inbox is at location INBOX_OFFSET of the MessageBox struct. bytes memory path = BytesLib.bytes32ToBytes( storageVariablePathForStruct( _messageBoxOffset, INBOX_OFFSET, messageHash_ ) ); // Perform the merkle proof. require( MerklePatriciaProof.verify( keccak256(abi.encodePacked(_messageStatus)), path, _rlpParentNodes, _storageRoot ), "Merkle proof verification failed." ); _messageBox.outbox[messageHash_] = MessageStatus.Revoked; } /** * @notice Returns the type hash of the type "Message". * * @return messageTypehash_ The type hash of the "Message" type. */ function messageTypehash() public pure returns(bytes32 messageTypehash_) { messageTypehash_ = MESSAGE_TYPEHASH; } /* Public Functions */ /** * @notice Generate message hash from the input params * * @param _intentHash Intent hash. * @param _nonce Nonce of the message sender. * @param _gasPrice Gas price. * * @return messageHash_ Message hash. */ function messageDigest( bytes32 _intentHash, uint256 _nonce, uint256 _gasPrice, uint256 _gasLimit, address _sender, bytes32 _hashLock ) public pure returns (bytes32 messageHash_) { messageHash_ = keccak256( abi.encode( MESSAGE_TYPEHASH, _intentHash, _nonce, _gasPrice, _gasLimit, _sender, _hashLock ) ); } /* Private Functions */ /** * @notice Creates a hash from a message struct. * * @param _message The message to hash. * * @return messageHash_ The hash that represents this message. */ function messageDigest( Message storage _message ) private view returns (bytes32 messageHash_) { messageHash_ = messageDigest( _message.intentHash, _message.nonce, _message.gasPrice, _message.gasLimit, _message.sender, _message.hashLock ); } /** * @notice Get the storage path of the variable inside the struct. * * @param _structPosition Position of struct variable. * @param _offset Offset of variable inside the struct. * @param _key Key of variable in case of mapping * * @return storagePath_ Storage path of the variable. */ function storageVariablePathForStruct( uint8 _structPosition, uint8 _offset, bytes32 _key ) private pure returns(bytes32 storagePath_) { if(_offset > 0){ _structPosition = _structPosition + _offset; } bytes memory indexBytes = BytesLib.leftPad( BytesLib.bytes32ToBytes(bytes32(uint256(_structPosition))) ); bytes memory keyBytes = BytesLib.leftPad(BytesLib.bytes32ToBytes(_key)); bytes memory path = BytesLib.concat(keyBytes, indexBytes); storagePath_ = keccak256( abi.encodePacked(keccak256(abi.encodePacked(path))) ); } }
Convert bytes32 to bytes _inBytes32 bytes32 value return bytes value/ solium-disable-next-line /
function bytes32ToBytes(bytes32 _inBytes32) internal pure returns (bytes memory bytes_) { bytes_ = new bytes(32); assembly { mstore(add(32, bytes_), _inBytes32) } }
12,905,925
./partial_match/1/0x7Bbd345846869f2A5950F33C7f0706FB71c84b04/sources/PassKeys.sol
Performs some essential sanity checks and subsequently mints the specified type of passkey to the caller. _keyType The type of PassKey being claimed. _amount The amount of PassKeys to be claimed. _allowedLimit The maximum allowed limit that can be claimed by the caller. _merkleProof The merkle proof data for verifying the claim. Revert if the merkle root is not set. Revert if the amount to claim is zero. Revert if the requested claim amount would cause the caller to exceed their allocated claim limit for a specific passkey.
function _claimKey( uint256 _keyType, uint256 _amount, uint256 _allowedLimit, bytes32[] calldata _merkleProof ) private { if (merkleRoot == bytes32(0)) { revert ClaimNotAllowedYet(); } if (_amount == 0) { revert ZeroAmount(); } !MerkleProof.verify( _merkleProof, merkleRoot, keccak256(abi.encodePacked(_keyType, msg.sender, _allowedLimit)) ) ) { revert ClaimVerificationFailed(); } if (passkeyMintCount[_keyType][msg.sender] + _amount > _allowedLimit) { revert ExceedsAllowedPasskeyMintAmount(); } emit PassKeyMinted(msg.sender, _keyType, _amount); } ERC1155 FUNCTION
2,843,144
pragma solidity ^0.4.24; contract SignatureVerifier { address public owner; constructor() public { owner = msg.sender; } function verifySignature(bytes32 hash, bytes signature, address signer) public pure returns (bool) { address addressFromSig = recoverSigner(hash, signature); return addressFromSig == signer; } /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign(). Inclusive "0x..." */ function recoverSigner(bytes32 hash, bytes sig) public pure returns (address) { require(sig.length == 65, "Require correct length"); bytes32 r; bytes32 s; uint8 v; // Divide the signature in r, s and v variables assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } require(v == 27 || v == 28, "Signature version not match"); return recoverSigner2(hash, v, r, s); } function recoverSigner2(bytes32 h, uint8 v, bytes32 r, bytes32 s) public pure returns (address) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, h)); address addr = ecrecover(prefixedHash, v, r, s); return addr; } function destroy() public returns (bool) { require(owner == msg.sender); selfdestruct(owner); return true; } }
Recover signer address from a message by using their signature hash bytes32 message, the hash is the signed message. What is recovered is the signer address. sig bytes signature, the signature is generated using web3.eth.sign(). Inclusive "0x..."/ Divide the signature in r, s and v variables Version of signature should be 27 or 28, but 0 and 1 are also possible versions
function recoverSigner(bytes32 hash, bytes sig) public pure returns (address) { require(sig.length == 65, "Require correct length"); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } if (v < 27) { v += 27; } require(v == 27 || v == 28, "Signature version not match"); return recoverSigner2(hash, v, r, s); }
7,325,422
./partial_match/3/0xBe80dB03d269fCa42Ca2f6F5a89C36e869d36c83/sources/A3Token.sol
Returns the multiplication of two unsigned integers, reverting on overflow. Counterpart to Solidity's `` operator. Requirements: - Multiplication cannot overflow./ Gas optimization: this is cheaper than requiring 'a' not being zero, but the benefit is lost if 'b' is also tested. See: https:github.com/OpenZeppelin/openzeppelin-contracts/pull/522
function mul(uint256 a, uint256 b) external pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; }
5,099,622
pragma solidity ^0.4.22; import "zeppelin-solidity/contracts/token/ERC20/PausableToken.sol"; import "zeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol"; import "./PreserveBalancesOnTransferToken.sol"; import "./ITokenVotingSupport.sol"; import "../utils/UtilsLib.sol"; /** * @title StdDaoToken * @dev Currently DaoBase works only with StdDaoToken. It does not support working with * plain ERC20 tokens because we need some extra features like mint(), burn() and transferOwnership() * * EVERY token that is used on Thetta should support these operations: * ERC20: * balanceOf() * transfer() * * Non ERC20: * transferOwnership() * mintFor() * burnFor() * startNewVoting() * finishVoting() * getBalanceAtVoting() */ contract StdDaoToken is DetailedERC20, PausableToken, PreserveBalancesOnTransferToken, ITokenVotingSupport { uint256 public cap; bool isBurnable; bool isPausable; address[] public holders; mapping (address => bool) isHolder; modifier isBurnable_() { require (isBurnable); _; } modifier isPausable_() { require (isPausable); _; } event VotingStarted(address indexed _address, uint _votingID); event VotingFinished(address indexed _address, uint _votingID); constructor(string _name, string _symbol, uint8 _decimals, bool _isBurnable, bool _isPausable, uint256 _cap) public DetailedERC20(_name, _symbol, _decimals) { require(_cap > 0); cap = _cap; isBurnable = _isBurnable; isPausable = _isPausable; holders.push(this); } // ITokenVotingSupport implementation // TODO: VULNERABILITY! no onlyOwner! /** * @notice This function should be called only when token not paused * @return index of the new voting * @dev should be called when voting started for conservation balances during this voting */ function startNewVoting() public whenNotPaused returns(uint) { uint idOut = super._startNewEvent(); emit VotingStarted(msg.sender, idOut); return idOut; } // TODO: VULNERABILITY! no onlyOwner! // update balances from conservation after voting finish /** * @notice This function should be called only when token not paused * @param _votingID id of voting * @dev update balances from conservation after voting finish */ function finishVoting(uint _votingID) whenNotPaused public { super._finishEvent(_votingID); emit VotingFinished(msg.sender, _votingID); } /** * @param _votingID id of voting * @param _owner account * @return balance of voting for account _owner */ function getBalanceAtVoting(uint _votingID, address _owner) public view returns (uint256) { return super.getBalanceAtEventStart(_votingID, _owner); } /** * @notice This function should be called only when token not paused * @param _to address * @param _value amount of tokens which will be transfered * @return true */ function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { if(!isHolder[_to]) { holders.push(_to); isHolder[_to] = true; } return super.transfer(_to, _value); } // transfer tokens from _from to _to address /** * @notice This function should be called only when token not paused * @param _from address * @param _to address * @param _value amount of tokens which will be transfered * @return true */ function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { if(!isHolder[_to]) { holders.push(_to); isHolder[_to] = true; } return super.transferFrom(_from, _to, _value); } /** * @return amount of total voters */ function getVotingTotalForQuadraticVoting() public view returns(uint) { uint votersTotal = 0; for(uint k=0; k<holders.length; k++) { votersTotal += UtilsLib.sqrt(this.balanceOf(holders[k])); } return votersTotal; } // MintableToken override // @dev do not call this method. Instead use mintFor() function mint(address _to, uint256 _amount) canMint onlyOwner public returns(bool) { revert(); } /** * @notice This function should be called only by owner * @param _to address * @param _amount amount of tokens which will be minted * @return true */ function mintFor(address _to, uint256 _amount) canMint onlyOwner public returns(bool) { require(totalSupply_.add(_amount) <= cap); if(!isHolder[_to]) { holders.push(_to); isHolder[_to] = true; } return super.mint(_to, _amount); } // BurnableToken override // @dev do not call this method. Instead use burnFor() function burn(uint256 _value) public { revert(); } /** * @notice This function should be called only by owner * @param _who address * @param _value amount of tokens which will be burned */ function burnFor(address _who, uint256 _value) isBurnable_ onlyOwner public { super._burn(_who, _value); } // this is an override of PausableToken method /** * @notice This function should be called only by owner * @dev pause the token */ function pause() isPausable_ onlyOwner public { super.pause(); } // this is an override of PausableToken method /** * @notice This function should be called only by owner * @dev unpause the token */ function unpause() isPausable_ onlyOwner public { super.unpause(); } }
This function should be called only by owner _who address _value amount of tokens which will be burned/
function burnFor(address _who, uint256 _value) isBurnable_ onlyOwner public { super._burn(_who, _value); }
6,412,608
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./interfaces/ILockedCvx.sol"; import "./interfaces/BoringMath.sol"; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; //Distribute various rewards to locked cvx holders // - Rewards added are assigned to the previous epoch (it was the previous epoch lockers who deserve today's rewards) // - As soon as claiming for a token at an epoch is eligibe, no more tokens should be allowed to be added // - To allow multiple txs to add to the same token, rewards added during the current epoch (and assigned to previous) will not // be claimable until the beginning of the next epoch. The "reward assigning phase" must be complete first //example: //Current epoch: 10 //During this week all addReward() calls are assigned to users in epoch 9 //Users who were locked in epoch 9 can claim once epoch 11 begins // -> epoch 10 is the assigning phase for epoch 9, thus we must wait until 10 is complete before claiming 9 contract vlCvxExtraRewardDistribution { using SafeERC20 for IERC20; using BoringMath for uint256; ILockedCvx public immutable cvxlocker; uint256 public constant rewardsDuration = 86400 * 7; mapping(address => mapping(uint256 => uint256)) public rewardData; // token -> epoch -> amount mapping(address => uint256[]) public rewardEpochs; // token -> epochList mapping(address => mapping(address => uint256)) public userClaims; //token -> account -> last claimed epoch index constructor(address _locker) public { cvxlocker = ILockedCvx(_locker); } function rewardEpochsCount(address _token) external view returns(uint256) { return rewardEpochs[_token].length; } function previousEpoch() internal view returns(uint256){ //count - 1 = next //count - 2 = current //count - 3 = prev return cvxlocker.epochCount() - 3; } //add a reward to a specific epoch function addRewardToEpoch(address _token, uint256 _amount, uint256 _epoch) external { //checkpoint locker cvxlocker.checkpointEpoch(); //if adding a reward to a specific epoch, make sure it's //a.) an epoch older than the previous epoch (in which case use addReward) //b.) more recent than the previous reward //this means addRewardToEpoch can only be called *once* for a specific reward for a specific epoch //because they will be claimable immediately and amount shouldnt change after claiming begins // //conversely rewards can be piled up with addReward() because claiming is only available to completed epochs require(_epoch < previousEpoch(), "!prev epoch"); uint256 l = rewardEpochs[_token].length; require(l == 0 || rewardEpochs[_token][l - 1] < _epoch, "old epoch"); _addReward(_token, _amount, _epoch); } //add a reward to the current epoch. can be called multiple times for the same reward token function addReward(address _token, uint256 _amount) external { //checkpoint locker cvxlocker.checkpointEpoch(); //assign to previous epoch uint256 prevEpoch = previousEpoch(); _addReward(_token, _amount, prevEpoch); } function _addReward(address _token, uint256 _amount, uint256 _epoch) internal { //convert to reward per token uint256 supply = cvxlocker.totalSupplyAtEpoch(_epoch); uint256 rPerT = _amount.mul(1e20).div(supply); rewardData[_token][_epoch] = rewardData[_token][_epoch].add(rPerT); //add epoch to list uint256 l = rewardEpochs[_token].length; if (l == 0 || rewardEpochs[_token][l - 1] < _epoch) { rewardEpochs[_token].push(_epoch); } //pull IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); //event emit RewardAdded(_token, _epoch, _amount); } //get claimable rewards for a specific token function claimableRewards(address _account, address _token) external view returns(uint256) { (uint256 rewards,) = _allClaimableRewards(_account, _token); return rewards; } //get claimable rewards for a token at a specific epoch function claimableRewardsAtEpoch(address _account, address _token, uint256 _epoch) external view returns(uint256) { return _claimableRewards(_account, _token, _epoch); } //get all claimable rewards function _allClaimableRewards(address _account, address _token) internal view returns(uint256,uint256) { uint256 epochIndex = userClaims[_token][_account]; uint256 prevEpoch = previousEpoch(); uint256 claimableTokens; for (uint256 i = epochIndex; i < rewardEpochs[_token].length; i++) { //only claimable after rewards are "locked in" if (rewardEpochs[_token][i] < prevEpoch) { claimableTokens = claimableTokens.add(_claimableRewards(_account, _token, rewardEpochs[_token][i])); //return index user claims should be set to epochIndex = i+1; } } return (claimableTokens, epochIndex); } //get claimable rewards for a token at a specific epoch function _claimableRewards(address _account, address _token, uint256 _epoch) internal view returns(uint256) { //get balance and calc share uint256 balance = cvxlocker.balanceAtEpochOf(_epoch, _account); return balance.mul(rewardData[_token][_epoch]).div(1e20); } //claim rewards for a specific token at a specific epoch function getReward(address _account, address _token) public { //get claimable tokens (uint256 claimableTokens, uint256 index) = _allClaimableRewards(_account, _token); if (claimableTokens > 0) { //set claim checkpoint userClaims[_token][_account] = index; //send IERC20(_token).safeTransfer(_account, claimableTokens); //event emit RewardPaid(_account, _token, claimableTokens); } } //get next claimable index. can use this to call setClaimIndex() to reduce gas costs if there //is a large number of epochs between current index and getNextClaimableIndex() function getNextClaimableIndex(address _account, address _token) external view returns(uint256){ uint256 epochIndex = userClaims[_token][_account]; uint256 prevEpoch = previousEpoch(); for (uint256 i = epochIndex; i < rewardEpochs[_token].length; i++) { //only claimable after rewards are "locked in" if (rewardEpochs[_token][i] < prevEpoch) { if(_claimableRewards(_account, _token, rewardEpochs[_token][i]) > 0){ //return index user claims should be set to return i; } } } return 0; } //Because claims cycle through all periods that a specific reward was given //there becomes a situation where, for example, a new user could lock //2 years from now and try to claim a token that was given out every week prior. //This would result in a 2mil gas checkpoint.(about 20k gas * 52 weeks * 2 years) // //allow a user to set their claimed index forward without claiming rewards function setClaimIndex(address _token, uint256 _index) external { require(_index > 0 && _index < rewardEpochs[_token].length, "!past"); require(_index >= userClaims[_token][msg.sender], "already claimed"); //set claim checkpoint. next claim starts from index userClaims[_token][msg.sender] = _index; emit ForcedClaimIndex(msg.sender, _token, _index); } /* ========== EVENTS ========== */ event RewardAdded(address indexed _token, uint256 indexed _epoch, uint256 _reward); event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward); event ForcedClaimIndex(address indexed _user, address indexed _rewardsToken, uint256 _index); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ILockedCvx{ struct LockedBalance { uint112 amount; uint112 boosted; uint32 unlockTime; } function lock(address _account, uint256 _amount, uint256 _spendRatio) external; function processExpiredLocks(bool _relock, uint256 _spendRatio, address _withdrawTo) external; function getReward(address _account, bool _stake) external; function balanceAtEpochOf(uint256 _epoch, address _user) view external returns(uint256 amount); function totalSupplyAtEpoch(uint256 _epoch) view external returns(uint256 supply); function epochCount() external view returns(uint256); function epochs(uint256 _id) external view returns(uint224,uint32); function checkpointEpoch() external; function balanceOf(address _account) external view returns(uint256); function lockedBalanceOf(address _user) external view returns(uint256 amount); function pendingLockOf(address _user) external view returns(uint256 amount); function pendingLockAtEpochOf(uint256 _epoch, address _user) view external returns(uint256 amount); function totalSupply() view external returns(uint256 supply); function lockedBalances( address _user ) view external returns( uint256 total, uint256 unlockable, uint256 locked, LockedBalance[] memory lockData ); function addReward( address _rewardsToken, address _distributor, bool _useBoost ) external; function approveRewardDistributor( address _rewardsToken, address _distributor, bool _approved ) external; function setStakeLimits(uint256 _minimum, uint256 _maximum) external; function setBoost(uint256 _max, uint256 _rate, address _receivingAddress) external; function setKickIncentive(uint256 _rate, uint256 _delay) external; function shutdown() external; function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "BoringMath: division by zero"); return a / b; } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } function to40(uint256 a) internal pure returns (uint40 c) { require(a <= uint40(-1), "BoringMath: uint40 Overflow"); c = uint40(a); } function to112(uint256 a) internal pure returns (uint112 c) { require(a <= uint112(-1), "BoringMath: uint112 Overflow"); c = uint112(a); } function to224(uint256 a) internal pure returns (uint224 c) { require(a <= uint224(-1), "BoringMath: uint224 Overflow"); c = uint224(a); } function to208(uint256 a) internal pure returns (uint208 c) { require(a <= uint208(-1), "BoringMath: uint208 Overflow"); c = uint208(a); } function to216(uint256 a) internal pure returns (uint216 c) { require(a <= uint216(-1), "BoringMath: uint216 Overflow"); c = uint216(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint32 a, uint32 b) internal pure returns (uint32 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint32 a, uint32 b) internal pure returns (uint32) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint112. library BoringMath112 { function add(uint112 a, uint112 b) internal pure returns (uint112 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint112 a, uint112 b) internal pure returns (uint112 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint112 a, uint112 b) internal pure returns (uint112 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint112 a, uint112 b) internal pure returns (uint112) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint224. library BoringMath224 { function add(uint224 a, uint224 b) internal pure returns (uint224 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint224 a, uint224 b) internal pure returns (uint224 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint224 a, uint224 b) internal pure returns (uint224 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint224 a, uint224 b) internal pure returns (uint224) { require(b > 0, "BoringMath: division by zero"); return a / b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } }
Because claims cycle through all periods that a specific reward was giventhere becomes a situation where, for example, a new user could lock2 years from now and try to claim a token that was given out every week prior.This would result in a 2mil gas checkpoint.(about 20k gas 52 weeks 2 years)allow a user to set their claimed index forward without claiming rewardsset claim checkpoint. next claim starts from index
function setClaimIndex(address _token, uint256 _index) external { require(_index > 0 && _index < rewardEpochs[_token].length, "!past"); require(_index >= userClaims[_token][msg.sender], "already claimed"); userClaims[_token][msg.sender] = _index; emit ForcedClaimIndex(msg.sender, _token, _index); } event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward); event ForcedClaimIndex(address indexed _user, address indexed _rewardsToken, uint256 _index);
11,764,964
./full_match/100/0x67Ce8491BaFE98D24B502f9a79772972CBC38989/sources/contracts/EasyAuction.sol
orders should have a minimum bid size in order to limit the gas required to compute the final price of the auction.
function _placeSellOrders( uint256 auctionId, uint96[] memory _minBuyAmounts, uint96[] memory _sellAmounts, bytes32[] memory _prevSellOrders, bytes memory allowListCallData ) internal returns (uint64 userId) { { address allowListManger = auctionAccessManager[auctionId]; if (allowListManger != address(0)) { require( AllowListVerifier(allowListManger).isAllowed( msg.sender, auctionId, allowListCallData ) == AllowListVerifierHelper.MAGICVALUE, "user not allowed to place order" ); } } ( , uint96 buyAmountOfInitialAuctionOrder, uint96 sellAmountOfInitialAuctionOrder ) = auctionData[auctionId].initialAuctionOrder.decodeOrder(); uint256 sumOfSellAmounts = 0; userId = getUserId(msg.sender); uint256 minimumBiddingAmountPerOrder = auctionData[auctionId].minimumBiddingAmountPerOrder; for (uint256 i = 0; i < _minBuyAmounts.length; i++) { require( _minBuyAmounts[i].mul(buyAmountOfInitialAuctionOrder) < sellAmountOfInitialAuctionOrder.mul(_sellAmounts[i]), "limit price not better than mimimal offer" ); require( _sellAmounts[i] > minimumBiddingAmountPerOrder, "order too small" ); if ( sellOrders[auctionId].insert( IterableOrderedOrderSet.encodeOrder( userId, _minBuyAmounts[i], _sellAmounts[i] ), _prevSellOrders[i] ) ) { sumOfSellAmounts = sumOfSellAmounts.add(_sellAmounts[i]); emit NewSellOrder( auctionId, userId, _minBuyAmounts[i], _sellAmounts[i] ); } } auctionData[auctionId].biddingToken.safeTransferFrom( msg.sender, address(this), sumOfSellAmounts }
14,278,131
./full_match/80001/0x127de82890D5298dE64bf7dbdde059e2a665e615/sources/base/ERC721Drop.sol
Checks whether royalty info can be set in the given execution context.
function _canSetRoyaltyInfo() internal view virtual override returns (bool) { return msg.sender == owner() || hasRole(DEFAULT_ADMIN_ROLE, msg.sender); }
839,614
pragma solidity ^0.4.17; import "./ERC721.sol"; import "./Migrations.sol"; contract CopyrightToken { struct Copyright { uint id; string photoURL; uint256 issueDate; address originalOwner; address oldOwner; address newOwner; } Copyright[] copyrights; mapping(uint => address) internal prevTokenOwners; mapping(uint => address) internal tokenOwners; mapping(uint => bool) internal tokenExists; mapping(address => uint) internal copyrightCounts; // How many copyrights _id has mapping(address => mapping(address => uint256)) internal allowed; event GenerateToken(uint _imageId, uint _tokenId, uint256 _issueDate, address _originalOwner); event Transfer(address indexed _from, address indexed _to, uint256 _tokenId, uint _imageId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function mint(uint _imageId, string _photoURL) public returns (uint){ uint _tokenId = copyrights.length; Copyright memory _copyright = Copyright({ id: _tokenId, photoURL: _photoURL, issueDate: uint256(now), originalOwner: msg.sender, oldOwner: address(0), newOwner: msg.sender }); copyrights.push(_copyright); prevTokenOwners[_tokenId] = address(0); tokenOwners[_tokenId] = msg.sender; tokenExists[_tokenId] = true; copyrightCounts[msg.sender] += 1; emit GenerateToken(_imageId, _tokenId, _copyright.issueDate, msg.sender); } function getCopyrightInfo(uint _tokenId) external view returns( uint id, string photoURL, uint256 issueDate, address originalOwner, address oldOwner, address newOwner ) { Copyright storage c = copyrights[_tokenId]; id = c.id; photoURL = c.photoURL; issueDate = c.issueDate; originalOwner = c.originalOwner; oldOwner = prevTokenOwners[_tokenId]; newOwner = tokenOwners[_tokenId]; } /* 1. ERC20 compatible functions : let users perform actions such as sending tokens to others and checking balances of accounts.*/ string public constant name = "CopyrightToken"; string public constant symbol = "CRT"; // Token’s shorthand name function totalSupply() public view returns (uint256) { // Total number of copyrights we made return copyrights.length; } function balanceOf(address _owner) public view returns (uint256) { // How many copyrights _owner has return copyrightCounts[_owner]; } /* 2. Ownership Functions */ function ownerOf(uint256 _tokenId) public view returns (address) { // Who is the owner of this token? return tokenOwners[_tokenId]; } function approve(address _to, uint256 _tokenId) public { // Approves other people has permission to transfer a token require(msg.sender == ownerOf(_tokenId)); require(msg.sender != _to); allowed[msg.sender][_to] = _tokenId; emit Approval(msg.sender, _to, _tokenId); } function takeOwnership(uint256 _tokenId, uint _imageId) public { require(tokenExists[_tokenId]); address oldOwner = ownerOf(_tokenId); address newOwner = msg.sender; require(oldOwner != newOwner); require(allowed[oldOwner][newOwner] == _tokenId); copyrightCounts[oldOwner] -= 1; prevTokenOwners[_tokenId] = oldOwner; tokenOwners[_tokenId] = newOwner; copyrightCounts[newOwner] += 1; emit Transfer(oldOwner, newOwner, _tokenId, _imageId); } function transfer(address _to, uint256 _tokenId, uint _imageId) public { address oldOwner = msg.sender; address newOwner = _to; require(tokenExists[_tokenId]); require(oldOwner == ownerOf(_tokenId)); require(oldOwner != newOwner); require(newOwner != address(0)); copyrightCounts[oldOwner] -= 1; prevTokenOwners[_tokenId] = oldOwner; tokenOwners[_tokenId] = newOwner; copyrightCounts[newOwner] += 1; emit Transfer(oldOwner, newOwner, _tokenId, _imageId); } }
Who is the owner of this token?
function ownerOf(uint256 _tokenId) public view returns (address) {
13,047,896
./partial_match/5/0xdE4c870F36a614E44bd00f987B22F4c4D48718F3/sources/contracts/base/MetawinERC721.sol
[Tx][External][Restricted] Overloaded mint function, mints in sequential order with no second argument to Receiver's address/
function mint(address to) external virtual mintRequirements(0) { super._safeMint(to, totalSupply()); }
16,866,951
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/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 {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/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 IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/interface/IVault.sol pragma solidity ^0.6.2; interface IVault is IERC20 { function balance() external view returns (uint256); function balanceOfToken() external view returns (uint256); function token() external view returns (address); function claimInsurance() external; // NOTE: Only yDelegatedVault implements this function getRatio() external view returns (uint256); function deposit(uint256) external; function withdraw(uint256) external; function earn() external; } // File: contracts/interface/IStakingRewards.sol pragma solidity ^0.6.2; interface IStakingRewards { function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function exit() external; function getReward() external; function getRewardForDuration() external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function lastUpdateTime() external view returns (uint256); function notifyRewardAmount(uint256 reward) external; function periodFinish() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function rewardRate() external view returns (uint256); function rewards(address) external view returns (uint256); function rewardsDistribution() external view returns (address); function rewardsDuration() external view returns (uint256); function rewardsToken() external view returns (address); function stake(uint256 amount) external; function stakeWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function stakingToken() external view returns (address); function totalSupply() external view returns (uint256); function userRewardPerTokenPaid(address) external view returns (uint256); function withdraw(uint256 amount) external; } // File: contracts/interface/UniswapRouterV2.sol pragma solidity ^0.6.2; interface UniswapRouterV2 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } // File: contracts/interface/IController.sol pragma solidity ^0.6.0; interface IController { function vaults(address) external view returns (address); function comAddr() external view returns (address); function devAddr() external view returns (address); function burnAddr() external view returns (address); function want(address) external view returns (address); // NOTE: Only StrategyControllerV2 implements this function balanceOf(address) external view returns (uint256); function withdraw(address, uint256) external; function freeWithdraw(address, uint256) external; function earn(address, uint256) external; } // File: contracts/strategies/StrategyBase.sol pragma solidity ^0.6.7; // Strategy Contract Basics abstract contract StrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Fees 5% in total // - 1.5% devFundFee for development fund // - 2% comFundFee for community fund // - 1.5% used to burn/repurchase btfs uint256 public devFundFee = 150; uint256 public constant devFundMax = 10000; uint256 public comFundFee = 200; uint256 public constant comFundMax = 10000; uint256 public burnFee = 150; uint256 public constant burnMax = 10000; // Withdrawal fee 0.5% uint256 public withdrawalFee = 0; uint256 public constant withdrawalMax = 10000; // Tokens address public token; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public btf; // User accounts address public governance; address public controller; address public strategist; address public timelock; // Dex address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor( address _btf, address _token, address _governance, address _strategist, address _controller, address _timelock ) public { require(_btf != address(0)); require(_token != address(0)); require(_governance != address(0)); require(_strategist != address(0)); require(_controller != address(0)); require(_timelock != address(0)); btf = _btf; token = _token; governance = _governance; strategist = _strategist; controller = _controller; timelock = _timelock; } // **** Modifiers **** // modifier onlyBenevolent { require( msg.sender == tx.origin || msg.sender == governance || msg.sender == strategist ); _; } // **** Views **** // function balanceOfWant() public view returns (uint256) { return IERC20(token).balanceOf(address(this)); } function balanceOfPool() public virtual view returns (uint256); function balanceOf() public view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function getName() external virtual pure returns (string memory); // **** Setters **** // function setBtf(address _btf) public { require(msg.sender == governance, "!governance"); btf = _btf; } function setDevFundFee(uint256 _devFundFee) external { require(msg.sender == timelock, "!timelock"); devFundFee = _devFundFee; } function setComFundFee(uint256 _comFundFee) external { require(msg.sender == timelock, "!timelock"); comFundFee = _comFundFee; } function setBurnFee(uint256 _burnFee) external { require(msg.sender == timelock, "!timelock"); burnFee = _burnFee; } function setWithdrawalFee(uint256 _withdrawalFee) external { require(msg.sender == timelock, "!timelock"); withdrawalFee = _withdrawalFee; } function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) external { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) external { require(msg.sender == timelock, "!timelock"); controller = _controller; } // **** State mutations **** // function deposit() public virtual; // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); require(token != address(_asset), "token"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Contoller only function for withdrawing for free // This is used to swap between vaults function freeWithdraw(uint256 _amount) external { require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(token).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } IERC20(token).safeTransfer(msg.sender, _amount); } // Withdraw partial funds, normally used with a vault withdrawal function withdraw(uint256 _amount) external { require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(token).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } if (withdrawalFee > 0) { uint256 _fee = _amount.mul(withdrawalFee).div(withdrawalMax); IERC20(token).safeTransfer(IController(controller).comAddr(), _fee); _amount = _amount.sub(_fee); } address _vault = IController(controller).vaults(address(token)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(token).safeTransfer(_vault, _amount); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawAll(); balance = IERC20(token).balanceOf(address(this)); address _vault = IController(controller).vaults(address(token)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(token).safeTransfer(_vault, balance); } function _withdrawAll() internal { _withdrawSome(balanceOfPool()); } function _withdrawSome(uint256 _amount) internal virtual returns (uint256); function harvest() public virtual; // **** Emergency functions **** function execute(address _target, bytes memory _data) public payable returns (bytes memory response) { require(msg.sender == timelock, "!timelock"); require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } // **** Internal functions **** function _swapUniswap( address _from, address _to, uint256 _amount ) internal { require(_to != address(0)); // Swap with uniswap IERC20(_from).safeApprove(univ2Router2, 0); IERC20(_from).safeApprove(univ2Router2, _amount); address[] memory path; if (_from == weth || _to == weth) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; } UniswapRouterV2(univ2Router2).swapExactTokensForTokens( _amount, 0, path, address(this), now.add(60) ); } } // File: contracts/interface/Compound.sol pragma solidity ^0.6.0; interface ICToken { function totalSupply() external view returns (uint256); function totalBorrows() external returns (uint256); function borrowIndex() external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function mint(uint256 mintAmount) external returns (uint256); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); } interface ICEther { function mint() external payable; /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 redeemTokens) external returns (uint256); /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint256 redeemAmount) external returns (uint256); /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint256 borrowAmount) external returns (uint256); /** * @notice Sender repays their own borrow * @dev Reverts upon any failure */ function repayBorrow() external payable; /** * @notice Sender repays a borrow belonging to borrower * @dev Reverts upon any failure * @param borrower the account with the debt being payed off */ function repayBorrowBehalf(address borrower) external payable; /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @dev Reverts upon any failure * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower */ function liquidateBorrow(address borrower, address cTokenCollateral) external payable; } interface IComptroller { function compAccrued(address) external view returns (uint256); function compSupplierIndex(address, address) external view returns (uint256); function compBorrowerIndex(address, address) external view returns (uint256); function compSpeeds(address) external view returns (uint256); function compBorrowState(address) external view returns (uint224, uint32); function compSupplyState(address) external view returns (uint224, uint32); /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); // Claim all the COMP accrued by holder in all markets function claimComp(address holder) external; // Claim all the COMP accrued by holder in specific markets function claimComp(address holder, address[] calldata cTokens) external; // Claim all the COMP accrued by specific holders in specific markets for their supplies and/or borrows function claimComp( address[] calldata holders, address[] calldata cTokens, bool borrowers, bool suppliers ) external; function markets(address cTokenAddress) external view returns (bool, uint256); } interface ICompoundLens { function getCompBalanceMetadataExt( address comp, address comptroller, address account ) external returns ( uint256 balance, uint256 votes, address delegate, uint256 allocated ); } // File: contracts/lib/CarefulMath.sol pragma solidity ^0.6.0; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } // File: contracts/lib/Exponential.sol pragma solidity ^0.6.0; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // File: contracts/interface/USDT.sol pragma solidity ^0.6.0; interface USDT { function approve(address guy, uint256 wad) external; function transfer(address _to, uint256 _value) external; } // File: contracts/strategies/compound/StrategyCmpdBase.sol pragma solidity ^0.6.2; abstract contract StrategyCmpdBase is StrategyBase, Exponential { address public constant comptroller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant lens = 0xd513d22422a3062Bd342Ae374b4b9c20E0a9a074; address public constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; address public constant cether = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; // dai/usdc address public want; // cdai/cusdc address public cwant; // Require a 0.05 buffer between // market collateral factor and strategy's collateral factor // when leveraging uint256 colFactorLeverageBuffer = 50; uint256 colFactorLeverageBufferMax = 1000; // Allow a 0.05 buffer // between market collateral factor and strategy's collateral factor // until we have to deleverage // This is so we can hit max leverage and keep accruing interest uint256 colFactorSyncBuffer = 50; uint256 colFactorSyncBufferMax = 1000; // Keeper bots // Maintain leverage within buffer mapping(address => bool) keepers; constructor( address _btf, address _want, address _cwant, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(_btf, _want, _governance, _strategist, _controller, _timelock) { // Enter cDAI Market want = _want; cwant = _cwant; address[] memory ctokens = new address[](1); ctokens[0] = _cwant; IComptroller(comptroller).enterMarkets(ctokens); } // **** Modifiers **** // modifier onlyKeepers { require( keepers[msg.sender] || msg.sender == address(this) || msg.sender == strategist || msg.sender == governance, "!keepers" ); _; } // **** Views **** // function getSuppliedView() public view returns (uint256) { (, uint256 cTokenBal, , uint256 exchangeRate) = ICToken(cwant) .getAccountSnapshot(address(this)); (, uint256 bal) = mulScalarTruncate( Exp({mantissa : exchangeRate}), cTokenBal ); return bal; } function getBorrowedView() public view returns (uint256) { return ICToken(cwant).borrowBalanceStored(address(this)); } function balanceOfPool() public override view returns (uint256) { uint256 supplied = getSuppliedView(); uint256 borrowed = getBorrowedView(); return supplied.sub(borrowed); } // Given an unleveraged supply balance, return the target // leveraged supply balance which is still within the safety buffer function getLeveragedSupplyTarget(uint256 supplyBalance) public view returns (uint256) { uint256 leverage = getMaxLeverage(); return supplyBalance.mul(leverage).div(1e18); } function getSafeLeverageColFactor() public view returns (uint256) { uint256 colFactor = getMarketColFactor(); // Collateral factor within the buffer uint256 safeColFactor = colFactor.sub( colFactorLeverageBuffer.mul(1e18).div(colFactorLeverageBufferMax) ); return safeColFactor; } function getSafeSyncColFactor() public view returns (uint256) { uint256 colFactor = getMarketColFactor(); // Collateral factor within the buffer uint256 safeColFactor = colFactor.sub( colFactorSyncBuffer.mul(1e18).div(colFactorSyncBufferMax) ); return safeColFactor; } function getMarketColFactor() public view returns (uint256) { (, uint256 colFactor) = IComptroller(comptroller).markets(cwant); return colFactor; } // Max leverage we can go up to, w.r.t safe buffer function getMaxLeverage() public view returns (uint256) { uint256 safeLeverageColFactor = getSafeLeverageColFactor(); // Infinite geometric series uint256 leverage = uint256(1e36).div(1e18 - safeLeverageColFactor); return leverage; } // **** Pseudo-view functions (use `callStatic` on these) **** // /* The reason why these exists is because of the nature of the interest accruing supply + borrow balance. The "view" methods are technically snapshots and don't represent the real value. As such there are pseudo view methods where you can retrieve the results by calling `callStatic`. */ function getCompAccrued() public returns (uint256) { (, , , uint256 accrued) = ICompoundLens(lens).getCompBalanceMetadataExt( comp, comptroller, address(this) ); return accrued; } function getHarvestable() external returns (uint256) { return getCompAccrued(); } function getColFactor() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return borrowed.mul(1e18).div(supplied); } function getSuppliedUnleveraged() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return supplied.sub(borrowed); } function getSupplied() public returns (uint256) { return ICToken(cwant).balanceOfUnderlying(address(this)); } function getBorrowed() public returns (uint256) { return ICToken(cwant).borrowBalanceCurrent(address(this)); } function getBorrowable() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); (, uint256 colFactor) = IComptroller(comptroller).markets(cwant); // 99.99% just in case some dust accumulates return supplied.mul(colFactor).div(1e18).sub(borrowed).mul(9999).div( 10000 ); } function getCurrentLeverage() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return supplied.mul(1e18).div(supplied.sub(borrowed)); } // **** Setters **** // function addKeeper(address _keeper) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); keepers[_keeper] = true; } function removeKeeper(address _keeper) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); keepers[_keeper] = false; } function setColFactorLeverageBuffer(uint256 _colFactorLeverageBuffer) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); colFactorLeverageBuffer = _colFactorLeverageBuffer; } function setColFactorSyncBuffer(uint256 _colFactorSyncBuffer) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); colFactorSyncBuffer = _colFactorSyncBuffer; } // **** State mutations **** // // Do a `callStatic` on this. // If it returns true then run it for realz. (i.e. eth_signedTx, not eth_call) function sync() public returns (bool) { uint256 colFactor = getColFactor(); uint256 safeSyncColFactor = getSafeSyncColFactor(); // If we're not safe if (colFactor > safeSyncColFactor) { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 idealSupply = getLeveragedSupplyTarget(unleveragedSupply); deleverageUntil(idealSupply); return true; } return false; } function leverageToMax() public { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 idealSupply = getLeveragedSupplyTarget(unleveragedSupply); leverageUntil(idealSupply); } // Leverages until we're supplying <x> amount // 1. Redeem <x> DAI // 2. Repay <x> DAI function leverageUntil(uint256 _supplyAmount) public onlyKeepers { // 1. Borrow out <X> DAI // 2. Supply <X> DAI uint256 leverage = getMaxLeverage(); uint256 unleveragedSupply = getSuppliedUnleveraged(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= unleveragedSupply.mul(leverage).div(1e18), "!leverage" ); // Since we're only leveraging one asset // Supplied = borrowed uint256 _borrowAndSupply; uint256 supplied = getSupplied(); while (supplied < _supplyAmount) { _borrowAndSupply = getBorrowable(); if (supplied.add(_borrowAndSupply) > _supplyAmount) { _borrowAndSupply = _supplyAmount.sub(supplied); } ICToken(cwant).borrow(_borrowAndSupply); deposit(); supplied = supplied.add(_borrowAndSupply); } } function deleverageToMin() public { uint256 unleveragedSupply = getSuppliedUnleveraged(); deleverageUntil(unleveragedSupply); } // Deleverages until we're supplying <x> amount // 1. Redeem <x> DAI // 2. Repay <x> DAI function deleverageUntil(uint256 _supplyAmount) public onlyKeepers { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, "!deleverage" ); uint256 _redeemAndRepay; do { // Since we're only leveraging on 1 asset // redeemable = borrowable _redeemAndRepay = getBorrowable(); if (supplied.sub(_redeemAndRepay) < _supplyAmount) { _redeemAndRepay = supplied.sub(_supplyAmount); } require( ICToken(cwant).redeemUnderlying(_redeemAndRepay) == 0, "!redeem" ); IERC20(want).safeApprove(cwant, 0); IERC20(want).safeApprove(cwant, _redeemAndRepay); require(ICToken(cwant).repayBorrow(_redeemAndRepay) == 0, "!repay"); supplied = supplied.sub(_redeemAndRepay); } while (supplied > _supplyAmount); } function harvest() public override onlyBenevolent { address[] memory ctokens = new address[](1); ctokens[0] = cwant; IComptroller(comptroller).claimComp(address(this), ctokens); uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > 0) { _swapUniswap(comp, want, _comp); } uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { if (devFundFee > 0) { uint256 _devFundFee = _want.mul(devFundFee).div(devFundMax); if (want == usdt) { USDT(want).transfer(IController(controller).devAddr(), _devFundFee); } else { IERC20(want).transfer(IController(controller).devAddr(), _devFundFee); } } // Burn some btfs first if (burnFee > 0) { uint256 _burnFee = _want.mul(burnFee).div(burnMax); _swapUniswap(want, btf, _burnFee); IERC20(btf).transfer( IController(controller).burnAddr(), IERC20(btf).balanceOf(address(this)) ); } if (comFundFee > 0) { uint256 _comFundFee = _want.mul(comFundFee).div(comFundMax); if (want == usdt) { USDT(want).transfer(IController(controller).comAddr(), _comFundFee); } else { IERC20(want).transfer(IController(controller).comAddr(), _comFundFee); } } deposit(); } } function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(cwant, 0); IERC20(want).safeApprove(cwant, _want); require(ICToken(cwant).mint(_want) == 0, "!deposit"); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 _want = balanceOfWant(); if (_want < _amount) { uint256 _redeem = _amount.sub(_want); // Make sure market can cover liquidity require(ICToken(cwant).getCash() >= _redeem, "!cash-liquidity"); // How much borrowed amount do we need to free? uint256 borrowed = getBorrowed(); uint256 supplied = getSupplied(); uint256 curLeverage = getCurrentLeverage(); uint256 borrowedToBeFree = _redeem.mul(curLeverage).div(1e18); // If the amount we need to free is > borrowed // Just free up all the borrowed amount if (borrowedToBeFree > borrowed) { this.deleverageToMin(); } else { // Otherwise just keep freeing up borrowed amounts until // we hit a safe number to redeem our underlying this.deleverageUntil(supplied.sub(borrowedToBeFree)); } // Redeems underlying require(ICToken(cwant).redeemUnderlying(_redeem) == 0, "!redeem"); } return _amount; } } // File: contracts/strategies/compound/StrategyCmpdDaiV1.sol pragma solidity ^0.6.2; contract StrategyCmpdDaiV1 is StrategyCmpdBase { address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant cdai = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; constructor( address _btf, address _governance, address _strategist, address _controller, address _timelock ) public StrategyCmpdBase(_btf, dai, cdai, _governance, _strategist, _controller, _timelock) { } // **** Views **** // function getName() external override pure returns (string memory) { return "StrategyCmpdDaiV1"; } }
Claim all the COMP accrued by holder in all markets Claim all the COMP accrued by holder in specific markets Claim all the COMP accrued by specific holders in specific markets for their supplies and/or borrows
interface IComptroller { function compAccrued(address) external view returns (uint256); function compSupplierIndex(address, address) external view returns (uint256); function compBorrowerIndex(address, address) external view returns (uint256); function compSpeeds(address) external view returns (uint256); function compBorrowState(address) external view returns (uint224, uint32); function compSupplyState(address) external view returns (uint224, uint32); function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); function claimComp(address holder) external; function claimComp(address holder, address[] calldata cTokens) external; function claimComp( address[] calldata holders, address[] calldata cTokens, bool borrowers, bool suppliers ) external; function markets(address cTokenAddress) external view returns (bool, uint256); } }
397,390
./full_match/43113/0xbEe12093a2eC756F7ef69717CA84a8a3817DB64B/sources/TinyDragonArena.sol
take a copy of the stats at the start of the match so the user can't increase stats to exploit the levelcap while match is running
function enterMatch( uint256 tokenId, uint256 matchId ) external { require( ITinyDragon(TINYDRAGONTOKEN).ownerOf(tokenId) == msg.sender, 'you must own this token' ); require( _activeMatches[matchId], "match must be active" ); _matchDragonStats[matchId][tokenId] = MatchStats( { level: ITinyDragon(TINYDRAGONTOKEN).getStats( tokenId ).level, defense: ITinyDragon(TINYDRAGONTOKEN).getStats( tokenId ).defense, attack: ITinyDragon(TINYDRAGONTOKEN).getStats( tokenId ).attack }); require( _matchDragonStats[matchId][tokenId].level >= _gameMatches[matchId].minLevel, "does not meet min level requirements" ); require( _matchDragonStats[matchId][tokenId].level <= _gameMatches[matchId].maxLevel, "does not meet max level requirements" ); require( _gameMatches[matchId].currentEntriesCount < _gameMatches[matchId].maxPlayers, "match full" ); uint256 totalTransferred = transferAndCalculateBalance( _gameMatches[matchId].token, _gameMatches[matchId].tokenAmount, address(this) ); _gameMatches[matchId].tokenPrizePoolAmount += totalTransferred; _gameMatches[matchId].matchTokenIds[_gameMatches[matchId].currentEntriesCount] = tokenId; _gameMatches[matchId].currentEntriesCount++; addMatchRandom( matchId, getRandomFromRandomLP(RANDOMLP) ); addMatchRandom( matchId, getRandomFromRandomLP(RANDOMLP2) ); addMatchRandom( matchId, getRandomFromRandomLP(RANDOMLP3) ); }
13,157,383
pragma solidity ^0.5.4; import "OathForge.sol"; import "imports/contracts/token/ERC721/ERC721.sol"; import "imports/contracts/token/ERC20/ERC20.sol"; import "imports/contracts/math/SafeMath.sol"; import "imports/contracts/ownership/Ownable.sol"; import "imports/contracts/utils/ReentrancyGuard.sol"; /// @title RiftPact: OathForge Token Fracturizer /// @author GuildCrypt contract RiftPact is ERC20, Ownable, ReentrancyGuard { using SafeMath for uint256; uint256 private _parentTokenId; uint256 private _auctionAllowedAt; address private _currencyAddress; address private _parentToken; uint256 private _minAuctionCompleteWait; uint256 private _minBidDeltaPermille; uint256 private _auctionStartedAt; uint256 private _auctionCompletedAt; uint256 private _minBid = 1; uint256 private _topBid; address private _topBidder; uint256 private _topBidSubmittedAt; mapping(address => bool) private _isBlacklisted; /// @param __parentToken The address of the OathForge contract /// @param __parentTokenId The id of the token on the OathForge contract /// @param __totalSupply The total supply /// @param __currencyAddress The address of the currency contract /// @param __auctionAllowedAt The timestamp at which anyone can start an auction /// @param __minAuctionCompleteWait The minimum amount of time (in seconds) between when a bid is placed and when an auction can be completed /// @param __minBidDeltaPermille The minimum increase (expressed as 1/1000ths of the current bid) that a subsequent bid must be constructor( address __parentToken, uint256 __parentTokenId, uint256 __totalSupply, address __currencyAddress, uint256 __auctionAllowedAt, uint256 __minAuctionCompleteWait, uint256 __minBidDeltaPermille ) public { _parentToken = __parentToken; _parentTokenId = __parentTokenId; _currencyAddress = __currencyAddress; _auctionAllowedAt = __auctionAllowedAt; _minAuctionCompleteWait = __minAuctionCompleteWait; _minBidDeltaPermille = __minBidDeltaPermille; _mint(msg.sender, __totalSupply); } /// @dev Emits when an auction is started event AuctionStarted(); /// @dev Emits when the auction is completed /// @param bid The final bid price of the auction /// @param winner The winner of the auction event AuctionCompleted(address winner, uint256 bid); /// @dev Emits when there is a bid /// @param bid The bid /// @param bidder The address of the bidder event Bid(address bidder, uint256 bid); /// @dev Emits when there is a payout /// @param to The address of the account paying out /// @param balance The balance of `to` prior to the paying out event Payout(address to, uint256 balance); /// @dev Returns the OathForge contract address. **UI should check for phishing.**. function parentToken() external view returns(address) { return _parentToken; } /// @dev Returns the OathForge token id. **Does not imply RiftPact has ownership over token.** function parentTokenId() external view returns(uint256) { return _parentTokenId; } /// @dev Returns the currency contract address. function currencyAddress() external view returns(address) { return _currencyAddress; } /// @dev Returns the minimum amount of time (in seconds) between when a bid is placed and when an auction can be completed. function minAuctionCompleteWait() external view returns(uint256) { return _minAuctionCompleteWait; } /// @dev Returns the minimum increase (expressed as 1/1000ths of the current bid) that a subsequent bid must be function minBidDeltaPermille() external view returns(uint256) { return _minBidDeltaPermille; } /// @dev Returns the timestamp at which anyone can start an auction by calling [`startAuction()`](#startAuction()) function auctionAllowedAt() external view returns(uint256) { return _auctionAllowedAt; } /// @dev Returns the minimum bid in currency function minBid() external view returns(uint256) { return _minBid; } /// @dev Returns the timestamp at which an auction was started or 0 if no auction has been started function auctionStartedAt() external view returns(uint256) { return _auctionStartedAt; } /// @dev Returns the timestamp at which an auction was completed or 0 if no auction has been completed function auctionCompletedAt() external view returns(uint256) { return _auctionCompletedAt; } /// @dev Returns the top bid or 0 if no bids have been placed function topBid() external view returns(uint256) { return _topBid; } /// @dev Returns the top bidder or `address(0)` if no bids have been placed function topBidder() external view returns(address) { return _topBidder; } /// @dev Start an auction function startAuction() external nonReentrant { require(_auctionStartedAt == 0); require( (now >= _auctionAllowedAt) || (OathForge(_parentToken).sunsetInitiatedAt(_parentTokenId) > 0) ); emit AuctionStarted(); _auctionStartedAt = now; } /// @dev Submit a bid. Must have sufficient funds approved in currency contract (bid * totalSupply). /// @param bid Bid in currency function submitBid(uint256 bid) external nonReentrant { require(_auctionStartedAt > 0); require(_auctionCompletedAt == 0); require (bid >= _minBid); emit Bid(msg.sender, bid); uint256 _totalSupply = totalSupply(); if (_topBidder != address(0)) { require(ERC20(_currencyAddress).transfer(_topBidder, _topBid * _totalSupply)); } require(ERC20(_currencyAddress).transferFrom(msg.sender, address(this), bid * _totalSupply)); _topBid = bid; _topBidder = msg.sender; _topBidSubmittedAt = now; uint256 minBidNumerator = bid * _minBidDeltaPermille; uint256 minBidDelta = minBidNumerator / 1000; uint256 minBidRoundUp = 0; if((bid * _minBidDeltaPermille) % 1000 > 0) { minBidRoundUp = 1; } _minBid = bid + minBidDelta + minBidRoundUp; } /// @dev Complete auction function completeAuction() external { require(_auctionCompletedAt == 0); require(_topBid > 0); require((_topBidSubmittedAt + _minAuctionCompleteWait) < now); emit AuctionCompleted(_topBidder, _topBid); _auctionCompletedAt = now; } /// @dev Payout `currency` after auction completed function payout() external nonReentrant { uint256 balance = balanceOf(msg.sender); require(balance > 0); require(_auctionCompletedAt > 0); emit Payout(msg.sender, balance); require(ERC20(_currencyAddress).transfer(msg.sender, balance * _topBid)); _burn(msg.sender, balance); } /// @dev Returns if an address is blacklisted /// @param to The address to check function isBlacklisted(address to) external view returns(bool){ return _isBlacklisted[to]; } /// @dev Set if an address is blacklisted /// @param to The address to change /// @param __isBlacklisted True if the address should be blacklisted, false otherwise function setIsBlacklisted(address to, bool __isBlacklisted) external onlyOwner { _isBlacklisted[to] = __isBlacklisted; } /** * @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(!_isBlacklisted[to]); return super.transfer(to, value); } /** * @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 returns (bool) { require(!_isBlacklisted[to]); return super.transferFrom(from, to, value); } /** * @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) { if (value > 0) { require(!_isBlacklisted[spender]); } return super.approve(spender, value); } /** * @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) { require(!_isBlacklisted[spender]); return super.increaseAllowance(spender, addedValue); } }
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. from address The address which you want to send tokens from to address The address which you want to transfer to value uint256 the amount of tokens to be transferred/
function transferFrom(address from, address to, uint256 value) public returns (bool) { require(!_isBlacklisted[to]); return super.transferFrom(from, to, value); }
5,344,052
./full_match/1/0xD9fC7bAe8ee3F9715860a223Ae9498296Db939c3/sources/contracts/BondedToken.sol
increases the boostedBalance for the given tokenId can be called only by Booster tokenId tokenId to increase its boostedBalance amount the amount
function addBoostedBalance( uint256 tokenId, uint256 amount ) public whenNotPaused onlyRole(BOOSTER_ROLE){ require(_ownerOf(tokenId) != address(0), "ERC721: invalid token ID"); boostedBalance[tokenId] += amount; }
16,526,946
pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../token/ITokenContract.sol"; /** * @dev Supports ERC20 tokens * The escrow smart contract for the open bazaar trades in Ethereum * The smart contract is desgined keeping in mind the current wallet interface of the OB-core * https://github.com/OpenBazaar/wallet-interface/blob/master/wallet.go * Current wallet interface strictly adheres to UTXO(bitcoin) model */ contract Escrow_v1_0 { using SafeMath for uint256; enum Status {FUNDED, RELEASED} enum TransactionType {ETHER, TOKEN} event Executed( bytes32 scriptHash, address[] destinations, uint256[] amounts ); event FundAdded( bytes32 scriptHash, address indexed from, uint256 valueAdded ); event Funded(bytes32 scriptHash, address indexed from, uint256 value); struct Transaction { bytes32 scriptHash;//This is unique indentifier for a transaction uint256 value; uint256 lastModified;//Time at which transaction was last modified Status status; TransactionType transactionType; uint8 threshold; uint32 timeoutHours; address buyer; address seller; address tokenAddress;// Token address in case of token transfer address moderator; mapping(address=>bool) isOwner;//to keep track of owners/signers. mapping(address=>bool) voted;//to keep track of who all voted mapping(address=>bool) beneficiaries;//Benefeciaries of execution } mapping(bytes32 => Transaction) public transactions; uint256 public transactionCount = 0; //Contains mapping between each party and all of his transactions mapping(address => bytes32[])public partyVsTransaction; modifier transactionExists(bytes32 scriptHash) { require( transactions[scriptHash].value != 0, "Transaction does not exists" ); _; } modifier transactionDoesNotExists (bytes32 scriptHash) { require(transactions[scriptHash].value == 0, "Transaction exists"); _; } modifier inFundedState(bytes32 scriptHash) { require( transactions[scriptHash].status == Status.FUNDED, "Transaction is either in dispute or released state" ); _; } modifier nonZeroAddress(address addressToCheck) { require(addressToCheck != address(0), "Zero address passed"); _; } modifier checkTransactionType( bytes32 scriptHash, TransactionType transactionType ) { require( transactions[scriptHash].transactionType == transactionType, "Transaction type does not match" ); _; } modifier onlyBuyer(bytes32 scriptHash) { require( msg.sender == transactions[scriptHash].buyer, "The initiator of the transaction is not buyer" ); _; } /** *@dev Add new transaction in the contract *@param buyer The buyer of the transaction *@param seller The seller of the listing associated with the transaction *@param moderator Moderator for this transaction *@param scriptHash keccak256 hash of the redeem script *@param threshold Minimum number of singatures required to released funds *@param timeoutHours Hours after which seller can release funds into his favour by signing transaction *@param uniqueId bytes20 unique id for the transaction, generated by ETH wallet *Redeem Script format will be following <uniqueId: 20><threshold:1><timeoutHours:4><buyer:20><seller:20><moderator:20><multisigAddress:20> * scripthash-> keccak256(uniqueId, threshold, timeoutHours, buyer, seller, moderator) *Pass amount of the ethers to be put in escrow *Please keep in mind you will have to add moderator fees also in the value */ function addTransaction( address buyer, address seller, address moderator, uint8 threshold, uint32 timeoutHours, bytes32 scriptHash, bytes20 uniqueId ) external payable transactionDoesNotExists(scriptHash) nonZeroAddress(buyer) nonZeroAddress(seller) { _addTransaction( buyer, seller, moderator, threshold, timeoutHours, scriptHash, msg.value, uniqueId, TransactionType.ETHER, address(0) ); emit Funded(scriptHash, msg.sender, msg.value); } /** *@dev Add new transaction in the contract *@param buyer The buyer of the transaction *@param seller The seller of the listing associated with the transaction *@param moderator Moderator for this transaction *@param scriptHash keccak256 hash of the redeem script *@param threshold Minimum number of singatures required to released funds *@param timeoutHours Hours after which seller can release funds into his favour by signing transaction *@param value Amount of tokens to be put in escrow *@param uniqueId bytes20 unique id for the transaction, generated by ETH wallet *@param tokenAddress Address of the token to be used *Redeem Script format will be following <uniqueId: 20><threshold:1><timeoutHours:4><buyer:20><seller:20><moderator:20><multisigAddress:20><tokenAddress:20> * scripthash-> keccak256(uniqueId, threshold, timeoutHours, buyer, seller, moderator, tokenAddress) *approve escrow contract to spend amount of token on your behalf *Please keep in mind you will have to add moderator fees also in the value */ function addTokenTransaction( address buyer, address seller, address moderator, uint8 threshold, uint32 timeoutHours, bytes32 scriptHash, uint256 value, bytes20 uniqueId, address tokenAddress ) external transactionDoesNotExists(scriptHash) nonZeroAddress(buyer) nonZeroAddress(seller) nonZeroAddress(tokenAddress) { _addTransaction( buyer, seller, moderator, threshold, timeoutHours, scriptHash, value, uniqueId, TransactionType.TOKEN, tokenAddress ); ITokenContract token = ITokenContract(tokenAddress); require( token.transferFrom(msg.sender, this, value), "Token transfer failed, maybe you did not approve escrow contract to spend on behalf of buyer" ); emit Funded(scriptHash, msg.sender, value); } /** * @dev Check whether given address was a beneficiary of transaction execution or not * @param scriptHash script hash of the transaction * @param beneficiary Beneficiary address to be checked */ function checkBeneficiary( bytes32 scriptHash, address beneficiary ) external view returns (bool check) { check = transactions[scriptHash].beneficiaries[beneficiary]; } /** * @dev Check whether given party has voted or not * @param scriptHash script hash of the transaction * @param party Address of the party whose vote has to be checked * @return bool vote */ function checkVote( bytes32 scriptHash, address party ) external view returns (bool vote) { vote = transactions[scriptHash].voted[party]; } /** *@dev Allows buyer of the transaction to add more funds(ether) in the transaction. This will help to cater scenarios wherein initially buyer missed to fund transaction as required *@param scriptHash script hash of the transaction * Only buyer of the transaction can invoke this method */ function addFundsToTransaction( bytes32 scriptHash ) external transactionExists(scriptHash) inFundedState(scriptHash) checkTransactionType(scriptHash, TransactionType.ETHER) onlyBuyer(scriptHash) payable { uint256 _value = msg.value; require(_value > 0, "Value must be greater than zero."); transactions[scriptHash].value = transactions[scriptHash].value .add(_value); transactions[scriptHash].lastModified = block.timestamp; emit FundAdded(scriptHash, msg.sender, _value); } /** *@dev Allows buyer of the transaction to add more funds(Tokens) in the transaction. This will help to cater scenarios wherein initially buyer missed to fund transaction as required *@param scriptHash script hash of the transaction */ function addTokensToTransaction( bytes32 scriptHash, uint256 value ) external transactionExists(scriptHash) inFundedState(scriptHash) checkTransactionType(scriptHash, TransactionType.TOKEN) onlyBuyer(scriptHash) { uint256 _value = value; require(_value > 0, "Value must be greater than zero."); ITokenContract token = ITokenContract( transactions[scriptHash].tokenAddress ); require( token.transferFrom(transactions[scriptHash].buyer, this, value), "Token transfer failed, maybe you did not approve escrow contract to spend on behalf of buyer" ); transactions[scriptHash].value = transactions[scriptHash].value .add(_value); transactions[scriptHash].lastModified = block.timestamp; emit FundAdded(scriptHash, msg.sender, _value); } /** *@dev Returns all transaction ids for a party *@param partyAddress Address of the party */ function getAllTransactionsForParty( address partyAddress ) external view returns (bytes32[] scriptHashes) { return partyVsTransaction[partyAddress]; } /** *@dev Allows one of the moderator to collect all the signature to solve dispute and submit it to this method. * If all the required signatures are collected and consensus has been reached than funds will be released to the voted party *@param sigV Array containing V component of all the signatures *@param sigR Array containing R component of all the signatures *@param signS Array containing S component of all the signatures *@param scriptHash script hash of the transaction *@param destinations address of the destination in whose favour dispute resolution is taking place. In case of split payments it will be address of the split payments contract *@param amounts value to send to each destination */ function execute( uint8[] sigV, bytes32[] sigR, bytes32[] sigS, bytes32 scriptHash, address[] destinations, uint256[] amounts ) external transactionExists(scriptHash) inFundedState(scriptHash) { require( destinations.length>0 && destinations.length == amounts.length, "Length of destinations is incorrect." ); verifyTransaction( sigV, sigR, sigS, scriptHash, destinations, amounts ); transactions[scriptHash].status = Status.RELEASED; //Last modified timestamp modified, which will be used by rewards transactions[scriptHash].lastModified = block.timestamp; require( transferFunds(scriptHash, destinations, amounts) == transactions[scriptHash].value, "Total value to be released must be equal to the transaction escrow value" ); emit Executed(scriptHash, destinations, amounts); } /** *@dev Method for calculating script hash. Calculation will depend upon the type of transaction * ETHER Type transaction-: * Script Hash- keccak256(uniqueId, threshold, timeoutHours, buyer, seller, moderator) * TOKEN Type transaction * Script Hash- keccak256(uniqueId, threshold, timeoutHours, buyer, seller, moderator, tokenAddress) * Client can use this method to verify whether it has calculated correct script hash or not */ function calculateRedeemScriptHash( bytes20 uniqueId, uint8 threshold, uint32 timeoutHours, address buyer, address seller, address moderator, address tokenAddress ) public view returns (bytes32 hash) { if (tokenAddress == address(0)) { hash = keccak256( abi.encodePacked( uniqueId, threshold, timeoutHours, buyer, seller, moderator, this ) ); } else { hash = keccak256( abi.encodePacked( uniqueId, threshold, timeoutHours, buyer, seller, moderator, this, tokenAddress ) ); } } /** * @dev This methods checks validity of transaction * 1. Verify Signatures * 2. Check if minimum number of signatures has been acquired * 3. If above condition is false, check if time lock is expired and the execution is signed by seller */ function verifyTransaction( uint8[] sigV, bytes32[] sigR, bytes32[] sigS, bytes32 scriptHash, address[] destinations, uint256[] amounts ) private { address lastRecovered = verifySignatures( sigV, sigR, sigS, scriptHash, destinations, amounts ); bool timeLockExpired = isTimeLockExpired( transactions[scriptHash].timeoutHours, transactions[scriptHash].lastModified ); //if Minimum number of signatures are not gathered and timelock has not expired or transaction was not signed by seller then revert if ( sigV.length < transactions[scriptHash].threshold && (!timeLockExpired || lastRecovered != transactions[scriptHash].seller) ) { revert("sigV.length is under the threshold."); } } /** *@dev Private method to transfer funds to the destination addresses on the basis of transaction type */ function transferFunds( bytes32 scriptHash, address[]destinations, uint256[]amounts ) private returns (uint256 valueTransferred) { Transaction storage t = transactions[scriptHash]; if (t.transactionType == TransactionType.ETHER) { for (uint256 i = 0; i < destinations.length; i++) { require(destinations[i] != address(0) && t.isOwner[destinations[i]], "Not a valid destination"); require(amounts[i] > 0, "Amount to be sent should be greater than 0"); valueTransferred = valueTransferred.add(amounts[i]); t.beneficiaries[destinations[i]] = true;//add receiver as beneficiary destinations[i].transfer(amounts[i]);//shall we use send instead of transfer to stop malicious actors from blocking funds? } } else if (t.transactionType == TransactionType.TOKEN) { ITokenContract token = ITokenContract(t.tokenAddress); for (uint256 j = 0; j<destinations.length; j++) { require(destinations[j] != address(0) && t.isOwner[destinations[j]], "Not a valid destination"); require(amounts[j] > 0, "Amount to be sent should be greater than 0"); valueTransferred = valueTransferred.add(amounts[j]); t.beneficiaries[destinations[j]] = true;//add receiver as beneficiary require(token.transfer(destinations[j], amounts[j]), "Token transfer failed."); } } else { //transaction type is not supported. Ideally this state should never be reached revert("Transation type is not supported."); } } //to check whether the signature are valid or not and if consensus was reached //returns the last address recovered, in case of timeout this must be the sender's address function verifySignatures( uint8[] sigV, bytes32[] sigR, bytes32[] sigS, bytes32 scriptHash, address[] destinations, uint256[]amounts ) private returns (address lastAddress) { require( sigR.length == sigS.length && sigR.length == sigV.length, "R,S,V length mismatch." ); // Follows ERC191 signature scheme: https://github.com/ethereum/EIPs/issues/191 bytes32 txHash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked( byte(0x19), byte(0), this, destinations, amounts, scriptHash ) ) ) ); for (uint i = 0; i < sigR.length; i++) { address recovered = ecrecover( txHash, sigV[i], sigR[i], sigS[i] ); require( transactions[scriptHash].isOwner[recovered], "Invalid signature" ); require( !transactions[scriptHash].voted[recovered], "Same signature sent twice" ); transactions[scriptHash].voted[recovered] = true; lastAddress = recovered; } } function isTimeLockExpired( uint32 timeoutHours, uint256 lastModified ) private view returns (bool expired) { uint256 timeSince = now.sub(lastModified); expired = ( timeoutHours == 0 ? false:timeSince > uint256(timeoutHours).mul(3600) ); } /** * Private method to add transaction to reduce code redundancy */ function _addTransaction( address buyer, address seller, address moderator, uint8 threshold, uint32 timeoutHours, bytes32 scriptHash, uint256 value, bytes20 uniqueId, TransactionType transactionType, address tokenAddress ) private { require(buyer != seller, "Buyer and seller are same"); //value passed should be greater than 0 require(value > 0, "Value passed is 0"); // For now allowing 0 moderator to support 1-2 multisig wallet require( threshold > 0 && threshold <= 3, "Threshold cannot be greater than 3 and must be greater than 0" ); require( threshold == 1 || moderator != address(0), "Either threshold should be 1 otherwise valid moderator address should be passed" ); require( scriptHash == calculateRedeemScriptHash( uniqueId, threshold, timeoutHours, buyer, seller, moderator, tokenAddress ), "Calculated script hash does not match passed script hash." ); transactions[scriptHash] = Transaction({ buyer: buyer, seller: seller, moderator: moderator, value: value, status: Status.FUNDED, lastModified: block.timestamp, scriptHash: scriptHash, threshold: threshold, timeoutHours: timeoutHours, transactionType:transactionType, tokenAddress:tokenAddress }); transactions[scriptHash].isOwner[seller] = true; transactions[scriptHash].isOwner[buyer] = true; //Check if buyer or seller are not passed as moderator require( !transactions[scriptHash].isOwner[moderator], "Either buyer or seller is passed as moderator" ); transactions[scriptHash].isOwner[moderator] = true; transactionCount++; partyVsTransaction[buyer].push(scriptHash); partyVsTransaction[seller].push(scriptHash); } }
Allows buyer of the transaction to add more funds(ether) in the transaction. This will help to cater scenarios wherein initially buyer missed to fund transaction as required scriptHash script hash of the transaction Only buyer of the transaction can invoke this method/
function addFundsToTransaction( bytes32 scriptHash ) external transactionExists(scriptHash) inFundedState(scriptHash) checkTransactionType(scriptHash, TransactionType.ETHER) onlyBuyer(scriptHash) payable { uint256 _value = msg.value; require(_value > 0, "Value must be greater than zero."); transactions[scriptHash].value = transactions[scriptHash].value .add(_value); transactions[scriptHash].lastModified = block.timestamp; emit FundAdded(scriptHash, msg.sender, _value); }
2,478,298
./full_match/1/0x4729F67394030472e853cb61954fe784BFB36c3B/sources/contracts/WeightedPool.sol
Returns the effective BPT supply. This would be the same as `totalSupply` however the Pool owes debt to the Protocol in the form of unminted BPT, which will be minted immediately before the next join or exit. We need to take these into account since, even if they don't yet exist, they will effectively be included in any Pool operation that involves BPT. In the vast majority of cases, this function should be used instead of `totalSupply()`. IMPORTANT NOTE: calling this function within a Vault context (i.e. in the middle of a join or an exit) is potentially unsafe, since the returned value is manipulable. It is up to the caller to ensure safety. This is because this function calculates the invariant, which requires the state of the pool to be in sync with the state of the Vault. That condition may not be true in the middle of a join or an exit. To call this function safely, attempt to trigger the reentrancy guard in the Vault by calling a non-reentrant function before calling `getActualSupply`. That will make the transaction revert in an unsafe context. (See `whenNotInVaultContext` in `WeightedPool`)./
function getActualSupply() external view returns (uint256) { uint256 supply = totalSupply(); (uint256 protocolFeesToBeMinted, ) = _getPreJoinExitProtocolFees( getInvariant(), _getNormalizedWeights(), supply ); return supply.add(protocolFeesToBeMinted); }
17,097,349
pragma solidity ^0.6.0; // "SPDX-License-Identifier: UNLICENSED " // ---------------------------------------------------------------------------- // 'FORMS' token contract // Symbol : FORMS // Name : FORMS // Total supply: 9,311,608 // Decimals : 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; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function totalSupply() public virtual view returns (uint); function balanceOf(address tokenOwner) public virtual view returns (uint256 balance); function allowance(address tokenOwner, address spender) public virtual view returns (uint256 remaining); function transfer(address to, uint256 tokens) public virtual returns (bool success); function approve(address spender, uint256 tokens) public virtual returns (bool success); function transferFrom(address from, address to, uint256 tokens) public virtual returns (bool success); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address payable public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract Token is ERC20Interface, Owned { using SafeMath for uint256; string public symbol = "FORMS"; string public name = "FORMS"; uint256 public decimals = 18; uint256 private _totalSupply = 9311608 * 10 ** (decimals); mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; address constant private TEAM = 0x24B73DC219196a5E373D73b7Cd638017f1f07E2F; address constant private MARKETING_FUNDS = 0x4B63B18b66Fc617B5A3125F0ABB565Dc22d732ba ; address constant private COMMUNITY_REWARD = 0xC071C603238F387E48Ee96826a81D608e304545A; address constant private PRIVATE_SALE_ADD1 = 0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd; address constant private PRIVATE_SALE_ADD2 = 0x8f63Fe51A3677cf02C80c11933De4B5846f2a336; address constant private PRIVATE_SALE_ADD3 = 0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1; address private tokenSaleOpt1; address private tokenSaleOpt2; address private tokenSaleOpt3; struct LOCKING{ uint256 lockedTokens; //DR , //PRC // lockedTokens1 uint256 releasePeriod; uint256 cliff; //DR, PRC // cliff for sale option 1 uint256 lastVisit; uint256 releasePercentage; bool directRelease; //DR uint256 lockedTokens2; uint256 cliff2; } mapping(address => LOCKING) public walletsLocking; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor(address _tokenSaleOpt1, address _tokenSaleOpt2, address _tokenSaleOpt3) public { owner = msg.sender; tokenSaleOpt1 = _tokenSaleOpt1; tokenSaleOpt2 = _tokenSaleOpt2; tokenSaleOpt3 = _tokenSaleOpt3; _tokenAllocation(); _setLocking(); } function _tokenAllocation() private { // send funds to team balances[address(TEAM)] = 1303625 * 10 ** (decimals); // 1303625 emit Transfer(address(0),address(TEAM), 1303625 * 10 ** (decimals)); // send funds to community reward balances[address(COMMUNITY_REWARD)] = 1117393 * 10 ** (decimals); // 1,117,393 emit Transfer(address(0),address(COMMUNITY_REWARD), 1117393 * 10 ** (decimals)); // send funds to marketing funds balances[address(MARKETING_FUNDS)] = 1117393 * 10 ** (decimals); // 1,117,393 emit Transfer(address(0),address(MARKETING_FUNDS), 1117393 * 10 ** (decimals)); // send funds to owner for exchange balances[address(owner)] = 1024277 * 10 ** (decimals); // 1,024,277 emit Transfer(address(0),address(owner), 1024277 * 10 ** (decimals)); // send funds for option 1 token sale balances[address(tokenSaleOpt1)] = 651813 * 10 ** (decimals); // 651,813 emit Transfer(address(0),address(tokenSaleOpt1), 651813 * 10 ** (decimals)); // send funds for option 2 token sale balances[address(tokenSaleOpt2)] = 2048554 * 10 ** (decimals); // 2,048,554 emit Transfer(address(0),address(tokenSaleOpt2), 2048554 * 10 ** (decimals)); // send funds for option 3 token sale balances[address(tokenSaleOpt3)] = 1024277 * 10 ** (decimals); // 1,024,277 emit Transfer(address(0),address(tokenSaleOpt3), 1024277 * 10 ** (decimals)); // Send to private sale addresses balances[address(0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd)] = 529131 * 10 ** (decimals); // 529131 emit Transfer(address(0),address(0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd), 529131 * 10 ** (decimals)); balances[address(0x8f63Fe51A3677cf02C80c11933De4B5846f2a336)] = 242718 * 10 ** (decimals); // 242718 emit Transfer(address(0),address(0x8f63Fe51A3677cf02C80c11933De4B5846f2a336), 242718 * 10 ** (decimals)); balances[address(0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1)] = 252427 * 10 ** (decimals); // 242718 emit Transfer(address(0),address(0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1), 252427 * 10 ** (decimals)); } function _setLocking() private{ //////////////////////////////////TEAM//////////////////////////////////// walletsLocking[TEAM].directRelease = true; walletsLocking[TEAM].lockedTokens = 1303625 * 10 ** (decimals); walletsLocking[TEAM].cliff = block.timestamp.add(365 days); //////////////////////////////////PRIVATE SALE ADDRESS 1//////////////////////////////////// /////////////////////////////0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd//////////////////// walletsLocking[0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd].directRelease = true; walletsLocking[0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd].lockedTokens = 529131 * 10 ** (decimals); walletsLocking[0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd].cliff = block.timestamp.add(180 days); //////////////////////////////////PRIVATE SALE ADDRESS 2//////////////////////////////////// /////////////////////////////0x8f63Fe51A3677cf02C80c11933De4B5846f2a336//////////////////// walletsLocking[0x8f63Fe51A3677cf02C80c11933De4B5846f2a336].directRelease = true; walletsLocking[0x8f63Fe51A3677cf02C80c11933De4B5846f2a336].lockedTokens = 242718 * 10 ** (decimals); walletsLocking[0x8f63Fe51A3677cf02C80c11933De4B5846f2a336].cliff = block.timestamp.add(180 days); //////////////////////////////////PRIVATE SALE ADDRESS 3//////////////////////////////////// /////////////////////////////0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1//////////////////// walletsLocking[0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1].directRelease = true; walletsLocking[0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1].lockedTokens = 252427 * 10 ** (decimals); walletsLocking[0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1].cliff = block.timestamp.add(180 days); //////////////////////////////////COMMUNITY_REWARD//////////////////////////////////// walletsLocking[COMMUNITY_REWARD].directRelease = false; walletsLocking[COMMUNITY_REWARD].lockedTokens = 1117393 * 10 ** (decimals); walletsLocking[COMMUNITY_REWARD].cliff = block.timestamp.add(30 days); walletsLocking[COMMUNITY_REWARD].lastVisit = block.timestamp.add(30 days); walletsLocking[COMMUNITY_REWARD].releasePeriod = 30 days; // 1 month walletsLocking[COMMUNITY_REWARD].releasePercentage = 5586965e16; // 55869.65 //////////////////////////////////MARKETING_FUNDS//////////////////////////////////// walletsLocking[MARKETING_FUNDS].directRelease = false; walletsLocking[MARKETING_FUNDS].lockedTokens = 1117393 * 10 ** (decimals); walletsLocking[MARKETING_FUNDS].cliff = 1599004800; // 2 september 2020 walletsLocking[MARKETING_FUNDS].lastVisit = 1599004800; walletsLocking[MARKETING_FUNDS].releasePeriod = 30 days; // 1 month walletsLocking[MARKETING_FUNDS].releasePercentage = 2234786e17; // 223478.6 } function setTokenLock(uint256 lockedTokens, uint256 cliffTime, address purchaser) public { require(msg.sender == tokenSaleOpt1 || msg.sender == tokenSaleOpt2, "UnAuthorized: Only sale contracts allowed"); //////////////////////////////////SET LOCK TO THE PURCHASER ACCOUNT//////////////////////////////////// if(msg.sender == tokenSaleOpt1){ walletsLocking[purchaser].directRelease = true; walletsLocking[purchaser].lockedTokens += lockedTokens; walletsLocking[purchaser].cliff = cliffTime; } else{ walletsLocking[purchaser].directRelease = true; walletsLocking[purchaser].lockedTokens2 += lockedTokens; walletsLocking[purchaser].cliff2 = cliffTime; } } /** ERC20Interface function's implementation **/ function totalSupply() public override view returns (uint256){ return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint256 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, uint256 tokens) public override returns (bool success) { // prevent transfer to 0x0, use burn instead require(address(to) != address(0), "Transfer to address 0 not allowed"); require(balances[msg.sender] >= tokens, "SENDER: insufficient balance"); if (walletsLocking[msg.sender].lockedTokens > 0 || walletsLocking[msg.sender].lockedTokens2 > 0){ if(walletsLocking[msg.sender].directRelease) directRelease(); else checkTime(); } uint256 lockedTokens = walletsLocking[msg.sender].lockedTokens.add(walletsLocking[msg.sender].lockedTokens2); require(balances[msg.sender].sub(tokens) >= lockedTokens, "Please wait for tokens to be released"); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // ------------------------------------------------------------------------ function approve(address spender, uint256 tokens) public override returns (bool success){ allowed[msg.sender][spender] = tokens; emit 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, uint256 tokens) public override returns (bool success){ require(tokens <= allowed[from][msg.sender]); //check allowance // prevent transfer to 0x0, use burn instead require(address(to) != address(0), "Transfer to address 0 not allowed"); require(balances[msg.sender] >= tokens, "SENDER: insufficient balance"); if (walletsLocking[msg.sender].lockedTokens > 0){ if(walletsLocking[msg.sender].directRelease) directRelease(); else checkTime(); } uint256 lockedTokens = walletsLocking[msg.sender].lockedTokens.add(walletsLocking[msg.sender].lockedTokens2); require(balances[msg.sender].sub(tokens) >= lockedTokens, "Please wait for tokens to be released"); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit 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 override view returns (uint256 remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // @dev Internal function that burns an amount of the token from a given account // @param _amount The amount that will be burnt // @param _account The tokens to burn from // ------------------------------------------------------------------------ function burnTokens(uint256 _amount) public { address _account = msg.sender; require(balances[_account] >= _amount, "insufficient account balance"); _totalSupply = _totalSupply.sub(_amount); balances[address(_account)] = balances[address(_account)].sub(_amount); emit Transfer(address(_account), address(0), _amount); } function directRelease() private{ if(block.timestamp > walletsLocking[msg.sender].cliff){ walletsLocking[msg.sender].lockedTokens = 0; }else if(block.timestamp > walletsLocking[msg.sender].cliff2){ walletsLocking[msg.sender].lockedTokens2 = 0; } } function checkTime() private { // if cliff is applied if(block.timestamp > walletsLocking[msg.sender].cliff){ if(msg.sender == MARKETING_FUNDS && walletsLocking[msg.sender].lastVisit == 1599004800){ walletsLocking[msg.sender].lockedTokens = walletsLocking[msg.sender].lockedTokens.sub(2234786e17); // 20% released } uint256 timeSpanned = (now.sub(walletsLocking[msg.sender].lastVisit)).div(walletsLocking[msg.sender].releasePeriod); // if cliff is passed if (timeSpanned >= 1){ uint256 released = timeSpanned.mul(walletsLocking[msg.sender].releasePercentage); if (released > walletsLocking[msg.sender].lockedTokens){ released = walletsLocking[msg.sender].lockedTokens; } walletsLocking[msg.sender].lastVisit = now; walletsLocking[msg.sender].lockedTokens = walletsLocking[msg.sender].lockedTokens.sub(released); } } } }
------------------------------------------------------------------------ Internal function that burns an amount of the token from a given account _amount The amount that will be burnt _account The tokens to burn from ------------------------------------------------------------------------
function burnTokens(uint256 _amount) public { address _account = msg.sender; require(balances[_account] >= _amount, "insufficient account balance"); _totalSupply = _totalSupply.sub(_amount); balances[address(_account)] = balances[address(_account)].sub(_amount); emit Transfer(address(_account), address(0), _amount); }
1,508,596
/** * Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.3; import "../openzeppelin-solidity/SafeMath.sol"; // supports a single EMA calculated for the inheriting contract contract EMACollector { //using SafeMath for uint256; uint256 public emaValue; // the last ema calculated uint256 public emaPeriods; // averaging periods for EMA calculation uint256 public outlierMultiplier = 2; uint256 public outlierAdder = 5**9 wei; // 5 gwei //uint256 internal emaLastUpdate; //event EMAUpdated(uint256 newEMA); modifier updatesEMA(uint256 value) { _; updateEMA(value); } function updateEMA(uint256 value) internal { /*if (emaLastUpdate == block.timestamp) return;*/ /* Multiplier: 2 / (emaPeriods + 1) EMA: (LastestValue - PreviousEMA) * Multiplier + PreviousEMA */ //require(emaPeriods >= 2, "emaPeriods < 2"); // outliers are ignored if (value > emaValue && value >= SafeMath.add(SafeMath.mul(outlierMultiplier, emaValue), outlierAdder)) return; // calculate new EMA emaValue = SafeMath.sub( SafeMath.add( value / (emaPeriods + 1) * 2, // no overflow emaValue ), emaValue / (emaPeriods + 1) * 2 // no overflow ); //emit EMAUpdated(emaValue); //emaLastUpdate = block.timestamp; } }
require(emaPeriods >= 2, "emaPeriods < 2"); outliers are ignored calculate new EMAemit EMAUpdated(emaValue);emaLastUpdate = block.timestamp;
function updateEMA(uint256 value) internal { return;*/ Multiplier: 2 / (emaPeriods + 1) EMA: (LastestValue - PreviousEMA) * Multiplier + PreviousEMA if (value > emaValue && value >= SafeMath.add(SafeMath.mul(outlierMultiplier, emaValue), outlierAdder)) return; emaValue = SafeMath.sub( SafeMath.add( emaValue ), ); }
12,711,116
pragma solidity ^0.4.23; contract Battleship { mapping(uint=>ShipSingleton) shipSingletons; mapping(address=>PlayerProfile) playerProfiles; OpenGame[] openGames; constructor() public { createShipSingletons(); } struct PlayerProfile { // could have username here ? Session[] sessions; } struct Session { bool open; mapping(uint=>Battlefield) battlefields; mapping(uint=>address) players; address whos_turn; bool in_progress; address winner; } struct Battlefield { uint[10][10] board; mapping(uint=>Ship) ships; uint shipsPlaced; uint shipsSunk; } struct ShipSingleton { string type_; uint length; } struct Ship { uint typeId; string start_row; uint start_column; string end_row; uint end_column; bool sunk; uint hit; } struct OpenGame { address player; uint session; } event Winner( address indexed winner, address host, uint sessionId ); function getOpenGameLength() public view returns (uint) { return openGames.length; } function getOpenGame(uint game) public view returns (address, uint) { return ( openGames[game].player, openGames[game].session ); } function joinGame(address host, uint sessionId, address player_two) public { Session storage session = playerProfiles[host].sessions[sessionId]; session.players[2] = player_two; session.open = false; session.in_progress = true; if (sessionId == 0) { session.whos_turn = session.players[1]; } else if (sessionId % 2 == 0) { session.whos_turn = session.players[2]; } else { session.whos_turn = session.players[1]; } } function createSession(address add) public { uint[10][10] memory board1; uint[10][10] memory board2; Battlefield memory p1_battlefield = Battlefield({board: board1, shipsSunk: 0, shipsPlaced: 0}); Battlefield memory p2_battlefield = Battlefield({board: board2, shipsSunk: 0, shipsPlaced: 0}); Session memory session = Session({ open: true, whos_turn: 0, in_progress: false, winner: 0 }); playerProfiles[add].sessions.push(session); uint sessionLength = playerProfiles[add].sessions.length-1; playerProfiles[add].sessions[sessionLength].battlefields[1] = p1_battlefield; playerProfiles[add].sessions[sessionLength].battlefields[2] = p2_battlefield; playerProfiles[add].sessions[sessionLength].players[1] = add; OpenGame memory openGame = OpenGame({player: add, session: sessionLength}); openGames.push(openGame); } function getSession(address add, uint session) public view returns(bool, address, address, address, bool, address, bool) { return ( playerProfiles[add].sessions[session].open, playerProfiles[add].sessions[session].players[1], playerProfiles[add].sessions[session].players[2], playerProfiles[add].sessions[session].whos_turn, playerProfiles[add].sessions[session].in_progress, playerProfiles[add].sessions[session].winner, playerProfiles[add].sessions[session].shipedPlaced == 5 ); } function getSessionLength(address add) public view returns (uint) { return playerProfiles[add].sessions.length; } // TODO when you get your opponents board, its scrubbed of everything except 0's and 9's function getBoard(address add, uint session, uint player_number) public view returns (uint[10][10]) { return playerProfiles[add].sessions[session].battlefields[player_number].board; } function getShip(address add, uint session, uint player_number, uint shipIndex) public view returns (uint, string, uint, string, uint, bool, uint) { Ship memory ship = playerProfiles[add].sessions[session].battlefields[player_number].ships[shipIndex]; return ( ship.typeId, ship.start_row, ship.start_column, ship.end_row, ship.end_column, ship.sunk, ship.hit ); } function createShipSingletons() private { shipSingletons[1] = ShipSingleton("AirCraftCarrier", 5); shipSingletons[2] = ShipSingleton("Minesweeper", 2); shipSingletons[3] = ShipSingleton("Frigate", 3); shipSingletons[4] = ShipSingleton("Battleship", 4); shipSingletons[5] = ShipSingleton("Submarine", 3); } function fireMissle(address add, uint sessionId, uint board_number, string row, uint column) public { Session storage session = playerProfiles[add].sessions[sessionId]; require(session.in_progress == true, "Game is not in progress"); require(msg.sender == session.whos_turn, "It is not your turn"); if (board_number == 1) { require(session.players[2] == session.whos_turn, "You cannot modify your own board"); } else if (board_number == 2) { require(session.players[1] == session.whos_turn, "You cannot modify your own board"); } Battlefield storage battlefield = session.battlefields[board_number]; require(battlefield.shipsPlaced == 5); // verify square hasnt been bombed uint val = battlefield.board[rowToIndex(row)][column-1]; require(val != 9, "Square already bombed"); battlefield.board[rowToIndex(row)][column-1] = 9; if (1 <= val && val <= 5) { Ship storage ship = battlefield.ships[val]; ship.hit++; if (ship.hit == getShipSingletonLength(val)) { ship.sunk = true; battlefield.shipsSunk++; } if (battlefield.shipsSunk == 5) { // current player wins session.winner = msg.sender; session.in_progress = false; emit Winner(msg.sender, add, sessionId); } } // change whos turn it is if (board_number == 2) { session.whos_turn = session.players[2]; } else if (board_number == 1) { session.whos_turn = session.players[1]; } } function getShipSingletonName(uint id) public view returns (string) { return shipSingletons[id].type_; } function getShipSingletonLength(uint id) public view returns (uint) { return shipSingletons[id].length; } function verifyShipNotDiagnol(uint shipId, uint start_row_index, uint start_column_index, uint end_row_index, uint end_column_index) public view { bool horizontal = start_row_index == end_row_index; bool vertical = start_column_index == end_column_index; require(horizontal || vertical, "Not horizontal or vertical"); // verify the distance between the starting and ending square matches the length of the ship uint ship_length = getShipSingletonLength(shipId); if (horizontal) { require(end_column_index-start_column_index+1 == ship_length, "Ship placement doesn't match ship length"); } else if (vertical) { require(end_row_index-start_row_index+1 == ship_length, "Ship placement doesn't match ship length"); } } function placeShip(address add, uint session, uint player_number, uint shipId, string start_row, uint start_column, string end_row, uint end_column) public { // verify the ship placement isn't diagnol verifyShipNotDiagnol(shipId, rowToIndex(start_row), start_column-1, rowToIndex(end_row), end_column-1); // verify the squares are unoccupied, then write the ship id uint[10][10] storage board = playerProfiles[add].sessions[session].battlefields[player_number].board; Ship memory ship = Ship({ typeId: shipId, start_row: start_row, start_column: start_column, end_row: end_row, end_column: end_column, sunk: false, hit: 0 }); if (rowToIndex(start_row) == rowToIndex(end_row)) { for (uint i = start_column-1; i < end_column-1+1; i++) { require(board[rowToIndex(start_row)][i] == 0, "Square occupied"); playerProfiles[add].sessions[session].battlefields[player_number].ships[shipId] = ship; board[rowToIndex(start_row)][i] = shipId; } } else if (start_column-1 == end_column-1) { for (i = rowToIndex(start_row); i < rowToIndex(end_row)+1; i++) { require(board[i][start_column-1] == 0, "Square Occupied"); playerProfiles[add].sessions[session].battlefields[player_number].ships[shipId] = ship; board[i][start_column-1] = shipId; } } playerProfiles[add].sessions[session].battlefields[player_number].shipsPlaced++; } // pass only lower case function rowToIndex(string row) public pure returns (uint) { bytes memory row_bytes = bytes(row); bytes32 row_hash = keccak256(row_bytes); if (row_hash == keccak256("a")) { return 0; } else if (row_hash == keccak256("b")) { return 1; } else if (row_hash == keccak256("c")) { return 2; } else if (row_hash == keccak256("d")) { return 3; } else if (row_hash == keccak256("e")) { return 4; } else if (row_hash == keccak256("f")) { return 5; } else if (row_hash == keccak256("g")) { return 6; } else if (row_hash == keccak256("h")) { return 7; } else if (row_hash == keccak256("i")) { return 8; } else if (row_hash == keccak256("j")) { return 9; } } }
verify the distance between the starting and ending square matches the length of the ship
function verifyShipNotDiagnol(uint shipId, uint start_row_index, uint start_column_index, uint end_row_index, uint end_column_index) public view { bool horizontal = start_row_index == end_row_index; bool vertical = start_column_index == end_column_index; require(horizontal || vertical, "Not horizontal or vertical"); uint ship_length = getShipSingletonLength(shipId); if (horizontal) { require(end_column_index-start_column_index+1 == ship_length, "Ship placement doesn't match ship length"); } else if (vertical) { require(end_row_index-start_row_index+1 == ship_length, "Ship placement doesn't match ship length"); } }
12,657,494
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IIDO.sol"; import "../BEP20/IBEP20.sol"; import "./IPancakeRouter02.sol"; /** * @dev Implementation of the {IDO} interface. */ contract IDO is IIDO { IBEP20 public token; IPancakeRouter02 public router; address payable private _owner; /* deployers' address */ address private immutable _token; /* BEP20 token address for the IDO */ address private immutable _stablecoin; /* stablecoin address for the IDO. Used only for getting the rate between native coinand stablecoin */ address private immutable _wrappedNative; /* WETH for ethereum, WBNB for Binance coin */ address private immutable _panecakePool; /* panecake pool address between stablecoin and native coin */ uint256 private _ratio; /* fixed ratio for the offering between stablcoin and native coin */ uint256 private _initialAmount; /* Initial amount of tokens for IDO */ uint256 private _totalCoinsExchanged; uint256 private _totalTokensOffered; event Debug(uint256, uint256); // index and number constructor( address __token, address __stablecoin, address __router, address __panecakePool, uint256 __ratio, uint256 __initialAmount ) { _owner = payable(msg.sender); _token = __token; _stablecoin = __stablecoin; _panecakePool = __panecakePool; _ratio = __ratio; _initialAmount = __initialAmount; token = IBEP20(__token); router = IPancakeRouter02(__router); _wrappedNative = router.WETH(); } /** * @notice returns the current exchange rate using pancake swap (onchain oracle) * @param _amountIn - native coin amount * @return exRate - exchange rate between native coin and token */ function getCurrentRate(uint256 _amountIn) external view override returns (uint256 exRate) { return _getCurrentRate(_amountIn); } /** * @notice returns the fixed ratio for IDO (stablecoin to token) * @return offeringRate - IDO rate between token and stablecoin */ function getFixedRate() external view override returns (uint256 offeringRate) { return _ratio; } /** * @notice returns the fixed ratio for IDO (stablecoin to token) * @return offeringRatio - the amount of total deposited IDO tokens (maximum offered) */ function getInitialOffered() external view override returns (uint256 offeringRatio) { return _initialAmount; } /** * @return stablecoin - returns the stable coin address */ function getStablecoinAddress() external view override returns (address stablecoin) { return _stablecoin; } /** * @return tokenAddr - returns the token address */ function getTokenAddress() external view override returns (address tokenAddr) { return _token; } /** * @return totalCoins - returns the amount of native coins that exchanged so far */ function totalInNative() external view override returns (uint256 totalCoins) { return _totalCoinsExchanged; } /** * @return totalTokens - returns the amount of the token that was bought so far */ function totalOut() external view override returns (uint256 totalTokens) { return _totalTokensOffered; } /** * @notice owner only - transfer native coins to owner's wallet * @param _amount - how many native coins to withdraw. On zero , retrieve all avariable coins * @notice Emits an {Withdrawn} event. */ function withdrawCoins(uint256 _amount) external payable override { assert(msg.sender == _owner); uint256 remainingCoins = address(this).balance; require(remainingCoins > 0); uint256 transferAmount = _amount; if (_amount == 0 || _amount > remainingCoins) { transferAmount = remainingCoins; } (bool successfulTransfer, ) = _owner.call{value: _amount}(""); require(successfulTransfer); emit Withdrawn(transferAmount, true); } /** * @notice owner only - transfer tokens to owner's wallet * @param _amount - how many tokens to withdraw. On zero , retrieve all tokens left * @notice Emits an {Withdrawn} event. */ function withdrawTokens(uint256 _amount) external override { assert(msg.sender == _owner); uint256 remainingTokens = token.balanceOf(address(this)); require(remainingTokens > 0); uint256 transferAmount = _amount; if (_amount == 0 || _amount > remainingTokens) { transferAmount = remainingTokens; } require(token.transfer(_owner, transferAmount)); emit Withdrawn(transferAmount, false); } /** * @notice directly accept deposit in native coins. Exchange it to tokens and return them to sender's address * @notice that way a fornt end client is not necessary for investors. They can use their favourite wallet * @notice Emits an {Exchanged} event. */ receive() external payable override { require(msg.value > 0); uint256 tokenAmount = (_ratio * _getCurrentRate(msg.value)) / (10**(18 - 8)); /* BNB has 18 decimals, token has 8 */ uint256 maxTokens = token.balanceOf(address(this)); require(maxTokens >= tokenAmount); _totalCoinsExchanged += msg.value; /* send the tokens to the caller */ require(token.transfer(msg.sender, tokenAmount)); _totalTokensOffered += tokenAmount; emit Exchanged(msg.sender, msg.value, tokenAmount); } /* Internal functions */ function _getCurrentRate(uint256 _amountIn) internal view returns (uint256 exRate) { address[] memory path = new address[](2); path[0] = _wrappedNative; path[1] = _stablecoin; uint256[] memory amounts = new uint256[](2); amounts = router.getAmountsOut(_amountIn, path); return amounts[1]; } }
return totalCoins - returns the amount of native coins that exchanged so far/
function totalInNative() external view override returns (uint256 totalCoins) { return _totalCoinsExchanged; }
12,711,073
pragma solidity ^0.4.18; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; // Bank contract, for managing merchants and tokens contract Bank is Ownable { struct Merchant { address merchantAddress; string name; string typeOfGoods; // colon seperated list of goods sold } mapping (address => Merchant) merchants; // finds and returns if a Merchant exists with the provided address function findMerchant(address merchant) public view returns (address, string, string) { return (merchants[merchant].merchantAddress, merchants[merchant].name, merchants[merchant].typeOfGoods); } // adds a merchant if it does not exist function addMerchant(address merchant, string name, string typeOfGoods) onlyOwner public { var (m,,,) = findMerchant(merchant); require(m == address(0)); merchants[msg.sender] = Merchant(merchant, name, typeOfGoods); } // function removeMerchant(address merchant) onlyOwner public { var (m,,,) = findMerchant(merchant); require(m != address(0)); delete merchants[msg.sender]; } }
adds a merchant if it does not exist
function addMerchant(address merchant, string name, string typeOfGoods) onlyOwner public { var (m,,,) = findMerchant(merchant); require(m == address(0)); merchants[msg.sender] = Merchant(merchant, name, typeOfGoods); }
12,619,649
// File: contracts/libs/openzeppelin_upgradable_v2_5_0/Initializable.sol 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: contracts/libs/openzeppelin_upgradable_v2_5_0/GSN/Context.sol pragma solidity ^0.5.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 is Initializable { // 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; } } // File: contracts/libs/openzeppelin_upgradable_v2_5_0/ownership/Ownable.sol pragma solidity ^0.5.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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @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(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File: contracts/libs/SafeMath.sol pragma solidity ^0.5.5; /** * @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; } /** * @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/interfaces/ERC20Advanced.sol pragma solidity ^0.5.5; /** * @title ERC20 Advanced interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface ERC20Advanced { function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address from, address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/ERC20Basic.sol pragma solidity ^0.5.5; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ interface ERC20Basic { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts/interfaces/ERC20Standard.sol pragma solidity ^0.5.5; /** * @title ERC20Standard * @dev Full ERC20 interface */ contract ERC20Standard is ERC20Basic, ERC20Advanced {} // File: contracts/tokenDistribution/TokenDistribution.sol /** * @title TokenDistribution * @author @Ola, @ziweidream * @notice This contract allows Investors to claim tokens based on a future token WITHDRAWAL date, * and an amount of ether they contributed and bonus percentage of KTY allocations based on * amount of Ether contributed. */ pragma solidity ^0.5.5; contract TokenDistribution is Ownable { using SafeMath for uint256; /* GENERAL VARIABLES */ /* ============================================================================================================== */ ERC20Standard public token; // ERC20Token contract variable uint256 constant internal base18 = 1000000000000000000; uint256 public standardRate; uint256 public percentBonus; // Percentage Bonus uint256 public withdrawDate; // Withdraw Date uint256 public totalNumberOfInvestments; // total number of investments uint256 public totalEtherInvested; // total amount of ethers invested from all investments // details of an Investment struct Investment { address investAddr; uint256 ethAmount; bool hasClaimed; uint256 principalClaimed; uint256 bonusClaimed; uint256 claimTime; } // mapping investment number to the details of the investment mapping(uint256 => Investment) public investments; // mapping investment address to the investment ID of all the investments made by this address mapping(address => uint256[]) public investmentIDs; uint256 private unlocked; /* MODIFIERS */ /* ============================================================================================================== */ modifier lock() { require(unlocked == 1, 'Locked'); unlocked = 0; _; unlocked = 1; } /* INITIALIZER */ /* ============================================================================================================== */ function initialize ( address[] calldata _investors, uint256[] calldata _ethAmounts, ERC20Standard _erc20Token, uint256 _withdrawDate, uint256 _standardRate, uint256 _percentBonus ) external initializer { Ownable.initialize(_msgSender()); // set investments addInvestments(_investors, _ethAmounts); // set ERC20Token contract variable setERC20Token(_erc20Token); // Set withdraw date withdrawDate = _withdrawDate; standardRate = _standardRate; // Set percentage bonus percentBonus = _percentBonus; //Reentrancy lock unlocked = 1; } /* EVENTS */ /* ============================================================================================================== */ event WithDrawn( address indexed investor, uint256 indexed investmentID, uint256 principal, uint256 bonus, uint256 withdrawTime ); /* YIELD FARMING FUNCTIONS */ /* ============================================================================================================== */ /** * @notice Withdraw tokens * @param investmentID uint256 investment ID of the investment for which the bonus tokens are distributed * @return bool true if the withdraw is successful */ function withdraw(uint256 investmentID) external lock returns (bool) { require(investments[investmentID].investAddr == msg.sender, "You are not the investor of this investment"); require(block.timestamp >= withdrawDate, "Can only withdraw after withdraw date"); require(!investments[investmentID].hasClaimed, "Tokens already withdrawn for this investment"); require(investments[investmentID].ethAmount > 0, "0 ether in this investment"); // get the ether amount of this investment uint256 _ethAmount = investments[investmentID].ethAmount; (uint256 _principal, uint256 _bonus, uint256 _principalAndBonus) = calculatePrincipalAndBonus(_ethAmount); _updateWithdraw(investmentID, _principal, _bonus); // transfer tokens to this investor require(token.transfer(msg.sender, _principalAndBonus), "Fail to transfer tokens"); emit WithDrawn(msg.sender, investmentID, _principal, _bonus, block.timestamp); return true; } /* SETTER FUNCTIONS */ /* ============================================================================================================== */ /** * @dev Add new investments * @dev This function can only be carreid out by the owner of this contract. */ function addInvestments(address[] memory _investors, uint256[] memory _ethAmounts) public onlyOwner { require(_investors.length == _ethAmounts.length, "The number of investing addresses should equal the number of ether amounts"); for (uint256 i = 0; i < _investors.length; i++) { addInvestment(_investors[i], _ethAmounts[i]); } } /** * @dev Set ERC20Token contract * @dev This function can only be carreid out by the owner of this contract. */ function setERC20Token(ERC20Standard _erc20Token) public onlyOwner { token = _erc20Token; } /** * @dev Set standard rate. Standard rate is amplified 10**18 times for float precision * @dev This function can only be carreid out by the owner of this contract. */ function setStandardRate(uint256 _standardRate) public onlyOwner { standardRate = _standardRate; } /** * @dev Set percentage bonus. Percentage bonus is amplified 10**18 times for float precision * @dev This function can only be carreid out by the owner of this contract. */ function setPercentBonus(uint256 _percentBonus) public onlyOwner { percentBonus = _percentBonus; } /** * @notice This function transfers tokens out of this contract to a new address * @dev This function is used to transfer unclaimed KittieFightToken to a new address, * or transfer other tokens erroneously tranferred to this contract back to their original owner * @dev This function can only be carreid out by the owner of this contract. */ function returnTokens(address _token, uint256 _amount, address _newAddress) external onlyOwner { require(block.timestamp >= withdrawDate.add(7 * 24 * 60 * 60), "Cannot return any token within 7 days of withdraw date"); uint256 balance = ERC20Standard(_token).balanceOf(address(this)); require(_amount <= balance, "Exceeds balance"); require(ERC20Standard(_token).transfer(_newAddress, _amount), "Fail to transfer tokens"); } /** * @notice Set withdraw date for the token * @param _withdrawDate uint256 withdraw date for the token * @dev This function can only be carreid out by the owner of this contract. */ function setWithdrawDate(uint256 _withdrawDate) public onlyOwner { withdrawDate = _withdrawDate; } /* GETTER FUNCTIONS */ /* ============================================================================================================== */ /** * @return true and 0 if it is time to withdraw, false and time until withdraw if it is not the time to withdraw yet */ function canWithdraw() public view returns (bool, uint256) { if (block.timestamp >= withdrawDate) { return (true, 0); } else { return (false, withdrawDate.sub(block.timestamp)); } } /** * @return uint256 bonus tokens calculated for the amount of ether specified */ function calculatePrincipalAndBonus(uint256 _ether) public view returns (uint256, uint256, uint256) { uint256 principal = _ether.mul(standardRate).div(base18); uint256 bonus = principal.mul(percentBonus).div(base18); uint256 principalAndBonus = principal.add(bonus); return (principal, bonus, principalAndBonus); } /** * @return address an array of the ID of each investment belonging to the investor */ function getInvestmentIDs(address _investAddr) external view returns (uint256[] memory) { return investmentIDs[_investAddr]; } /** * @return the details of an investment associated with an investment ID, including the address * of the investor, the amount of ether invested in this investment, whether bonus tokens * have been claimed for this investment, the amount of bonus tokens already claimed for * this investment(0 if bonus tokens are not claimed yet), the unix time when the bonus tokens * have been claimed(0 if bonus tokens are not claimed yet) */ function getInvestment(uint256 _investmentID) external view returns(address _investAddr, uint256 _ethAmount, bool _hasClaimed, uint256 _principalClaimed, uint256 _bonusClaimed, uint256 _claimTime) { _investAddr = investments[_investmentID].investAddr; _ethAmount = investments[_investmentID].ethAmount; _hasClaimed = investments[_investmentID].hasClaimed; _principalClaimed = investments[_investmentID].principalClaimed; _bonusClaimed = investments[_investmentID].bonusClaimed; _claimTime = investments[_investmentID].claimTime; } /* PRIVATE FUNCTIONS */ /* ============================================================================================================== */ /** * @param _investmentID uint256 investment ID of the investment for which tokens are withdrawn * @param _bonus uint256 tokens distributed to this investor * @dev this function updates the storage upon successful withdraw of tokens. */ function _updateWithdraw(uint256 _investmentID, uint256 _principal, uint256 _bonus) private { investments[_investmentID].hasClaimed = true; investments[_investmentID].principalClaimed = _principal; investments[_investmentID].bonusClaimed = _bonus; investments[_investmentID].claimTime = block.timestamp; investments[_investmentID].ethAmount = 0; } /** * @dev Add one new investment */ function addInvestment(address _investor, uint256 _eth) private { uint256 investmentID = totalNumberOfInvestments.add(1); investments[investmentID].investAddr = _investor; investments[investmentID].ethAmount = _eth; totalEtherInvested = totalEtherInvested.add(_eth); totalNumberOfInvestments = investmentID; investmentIDs[_investor].push(investmentID); } }
ERC20 Advanced interface/
interface ERC20Advanced { function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address from, address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); }
15,039,905
//Address: 0x359a46571d4bc22a6a9310038b51e2d91163412f //Contract name: TokenSale //Balance: 0 Ether //Verification Date: 2/21/2018 //Transacion Count: 9 // CODE STARTS HERE pragma solidity ^0.4.15; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ApproveAndCallReceiver { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } contract TokenFactoryInterface { function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, string _tokenSymbol ) public returns (ServusToken newToken); } /** * @title Controllable * @dev The Controllable contract has an controller address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Controllable { address public controller; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender account. */ function Controllable() public { controller = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyController() { require(msg.sender == controller); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newController The address to transfer ownership to. */ function transferControl(address newController) public onlyController { if (newController != address(0)) { controller = newController; } } } /** * @title ServusToken (SRV) * Standard Mintable ERC20 Token * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ServusTokenInterface is Controllable { event Mint(address indexed to, uint256 amount); event MintFinished(); event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval(address indexed _owner, address indexed _spender, uint256 _amount); event Transfer(address indexed from, address indexed to, uint256 value); function totalSupply() public constant returns (uint); function totalSupplyAt(uint _blockNumber) public constant returns(uint); function balanceOf(address _owner) public constant returns (uint256 balance); function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint); function transfer(address _to, uint256 _amount) public returns (bool success); function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success); function approve(address _spender, uint256 _amount) public returns (bool success); function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); function mint(address _owner, uint _amount) public returns (bool); function importPresaleBalances(address[] _addresses, uint256[] _balances, address _presaleAddress) public returns (bool); function lockPresaleBalances() public returns (bool); function finishMinting() public returns (bool); function enableTransfers(bool _value) public; function enableMasterTransfers(bool _value) public; function createCloneToken(uint _snapshotBlock, string _cloneTokenName, string _cloneTokenSymbol) public returns (address); } /** * @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; /** * @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 { if (newOwner != address(0)) { owner = newOwner; } } } contract ServusToken is Controllable { using SafeMath for uint256; ServusTokenInterface public parentToken; TokenFactoryInterface public tokenFactory; string public name; string public symbol; string public version; uint8 public decimals; uint256 public parentSnapShotBlock; uint256 public creationBlock; bool public transfersEnabled; bool public masterTransfersEnabled; address public masterWallet = 0x9d23cc4efa366b70f34f1879bc6178e6f3342441; struct Checkpoint { uint128 fromBlock; uint128 value; } Checkpoint[] totalSupplyHistory; mapping(address => Checkpoint[]) balances; mapping (address => mapping (address => uint)) allowed; bool public mintingFinished = false; bool public presaleBalancesLocked = false; uint256 public constant TOTAL_PRESALE_TOKENS = 2896000000000000000000; event Mint(address indexed to, uint256 amount); event MintFinished(); event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount); event NewCloneToken(address indexed cloneToken); event Approval(address indexed _owner, address indexed _spender, uint256 _amount); event Transfer(address indexed from, address indexed to, uint256 value); function ServusToken( address _tokenFactory, address _parentToken, uint256 _parentSnapShotBlock, string _tokenName, string _tokenSymbol ) public { tokenFactory = TokenFactoryInterface(_tokenFactory); parentToken = ServusTokenInterface(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; name = _tokenName; symbol = _tokenSymbol; decimals = 6; transfersEnabled = false; masterTransfersEnabled = false; creationBlock = block.number; version = '0.1'; } function() public payable { revert(); } /** * Returns the total Servus token supply at the current block * @return total supply {uint256} */ function totalSupply() public constant returns (uint256) { return totalSupplyAt(block.number); } /** * Returns the total Servus token supply at the given block number * @param _blockNumber {uint256} * @return total supply {uint256} */ function totalSupplyAt(uint256 _blockNumber) public constant returns(uint256) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } /** * Returns the token holder balance at the current block * @param _owner {address} * @return balance {uint256} */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /** * Returns the token holder balance the the given block number * @param _owner {address} * @param _blockNumber {uint256} * @return balance {uint256} */ function balanceOfAt(address _owner, uint256 _blockNumber) public constant returns (uint256) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /** * Standard ERC20 transfer tokens function * @param _to {address} * @param _amount {uint} * @return success {bool} */ function transfer(address _to, uint256 _amount) public returns (bool success) { return doTransfer(msg.sender, _to, _amount); } /** * Standard ERC20 transferFrom function * @param _from {address} * @param _to {address} * @param _amount {uint256} * @return success {bool} */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; return doTransfer(_from, _to, _amount); } /** * Standard ERC20 approve function * @param _spender {address} * @param _amount {uint256} * @return success {bool} */ function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); //https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /** * Standard ERC20 approve function * @param _spender {address} * @param _amount {uint256} * @return success {bool} */ function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns (bool success) { approve(_spender, _amount); ApproveAndCallReceiver(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /** * Standard ERC20 allowance function * @param _owner {address} * @param _spender {address} * @return remaining {uint256} */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * Internal Transfer function - Updates the checkpoint ledger * @param _from {address} * @param _to {address} * @param _amount {uint256} * @return success {bool} */ function doTransfer(address _from, address _to, uint256 _amount) internal returns(bool) { if (msg.sender != masterWallet) { require(transfersEnabled); } else { require(masterTransfersEnabled); } require(_amount > 0); require(parentSnapShotBlock < block.number); require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false uint256 previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint256 previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /** * Token creation functions - can only be called by the tokensale controller during the tokensale period * @param _owner {address} * @param _amount {uint256} * @return success {bool} */ function mint(address _owner, uint256 _amount) public onlyController canMint returns (bool) { uint256 curTotalSupply = totalSupply(); uint256 previousBalanceTo = balanceOf(_owner); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } modifier canMint() { require(!mintingFinished); _; } /** * Import presale balances before the start of the token sale. After importing * balances, lockPresaleBalances() has to be called to prevent further modification * of presale balances. * @param _addresses {address[]} Array of presale addresses * @param _balances {uint256[]} Array of balances corresponding to presale addresses. * @return success {bool} */ function importPresaleBalances(address[] _addresses, uint256[] _balances) public onlyController returns (bool) { require(presaleBalancesLocked == false); for (uint256 i = 0; i < _addresses.length; i++) { updateValueAtNow(balances[_addresses[i]], _balances[i]); Transfer(0, _addresses[i], _balances[i]); } updateValueAtNow(totalSupplyHistory, TOTAL_PRESALE_TOKENS); return true; } /** * Lock presale balances after successful presale balance import * @return A boolean that indicates if the operation was successful. */ function lockPresaleBalances() public onlyController returns (bool) { presaleBalancesLocked = true; return true; } /** * Lock the minting of Servus Tokens - to be called after the presale * @return {bool} success */ function finishMinting() public onlyController returns (bool) { mintingFinished = true; MintFinished(); return true; } /** * Enable or block transfers - to be called in case of emergency * @param _value {bool} */ function enableTransfers(bool _value) public onlyController { transfersEnabled = _value; } /** * Enable or block transfers - to be called in case of emergency * @param _value {bool} */ function enableMasterTransfers(bool _value) public onlyController { masterTransfersEnabled = _value; } /** * Internal balance method - gets a certain checkpoint value a a certain _block * @param _checkpoints {Checkpoint[]} List of checkpoints - supply history or balance history * @return value {uint256} Value of _checkpoints at _block */ function getValueAt(Checkpoint[] storage _checkpoints, uint256 _block) constant internal returns (uint256) { if (_checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= _checkpoints[_checkpoints.length-1].fromBlock) return _checkpoints[_checkpoints.length-1].value; if (_block < _checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint256 min = 0; uint256 max = _checkpoints.length-1; while (max > min) { uint256 mid = (max + min + 1) / 2; if (_checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return _checkpoints[min].value; } /** * Internal update method - updates the checkpoint ledger at the current block * @param _checkpoints {Checkpoint[]} List of checkpoints - supply history or balance history * @return value {uint256} Value to add to the checkpoints ledger */ function updateValueAtNow(Checkpoint[] storage _checkpoints, uint256 _value) internal { if ((_checkpoints.length == 0) || (_checkpoints[_checkpoints.length-1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = _checkpoints[_checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = _checkpoints[_checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } function min(uint256 a, uint256 b) internal constant returns (uint) { return a < b ? a : b; } /** * Clones Servus Token at the given snapshot block * @param _snapshotBlock {uint256} * @param _name {string} - The cloned token name * @param _symbol {string} - The cloned token symbol * @return clonedTokenAddress {address} */ function createCloneToken(uint256 _snapshotBlock, string _name, string _symbol) public returns(address) { if (_snapshotBlock == 0) { _snapshotBlock = block.number; } if (_snapshotBlock > block.number) { _snapshotBlock = block.number; } ServusToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _name, _symbol ); cloneToken.transferControl(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken)); return address(cloneToken); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; function Pausable() public {} /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } /** * @title Tokensale * Tokensale allows investors to make token purchases and assigns them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet as they arrive. */ contract TokenSale is Pausable { using SafeMath for uint256; ServusTokenInterface public servusToken; uint256 public totalWeiRaised; uint256 public tokensMinted; uint256 public totalSupply; uint256 public contributors; uint256 public decimalsMultiplier; uint256 public startTime; uint256 public endTime; uint256 public remainingTokens; uint256 public allocatedTokens; bool public finalized; bool public servusTokensAllocated; address public servusMultiSig = 0x0cc3e09c8a52fa0313154321be706635cdbdec37; uint256 public constant BASE_PRICE_IN_WEI = 1000000000000000; uint256 public constant PUBLIC_TOKENS = 100000000 * (10 ** 6); uint256 public constant TOTAL_PRESALE_TOKENS = 50000000 * (10 ** 6); uint256 public constant TOKENS_ALLOCATED_TO_SERVUS = 100000000 * (10 ** 6); uint256 public tokenCap = PUBLIC_TOKENS - TOTAL_PRESALE_TOKENS; uint256 public cap = tokenCap; uint256 public weiCap = cap * BASE_PRICE_IN_WEI; uint256 public firstDiscountPrice = (BASE_PRICE_IN_WEI * 85) / 100; uint256 public secondDiscountPrice = (BASE_PRICE_IN_WEI * 90) / 100; uint256 public thirdDiscountPrice = (BASE_PRICE_IN_WEI * 95) / 100; uint256 public firstDiscountCap = (weiCap * 5) / 100; uint256 public secondDiscountCap = (weiCap * 10) / 100; uint256 public thirdDiscountCap = (weiCap * 20) / 100; bool public started = false; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event NewClonedToken(address indexed _cloneToken); event OnTransfer(address _from, address _to, uint _amount); event OnApprove(address _owner, address _spender, uint _amount); event LogInt(string _name, uint256 _value); event Finalized(); function TokenSale(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { require(_tokenAddress != 0x0); require(_startTime > 0); require(_endTime > _startTime); startTime = _startTime; endTime = _endTime; servusToken = ServusTokenInterface(_tokenAddress); decimalsMultiplier = (10 ** 6); } /** * High level token purchase function */ function() public payable { buyTokens(msg.sender); } /** * Low level token purchase function * @param _beneficiary will receive the tokens. */ function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; uint256 priceInWei = getPriceInWei(); totalWeiRaised = totalWeiRaised.add(weiAmount); uint256 tokens = weiAmount.mul(decimalsMultiplier).div(priceInWei); tokensMinted = tokensMinted.add(tokens); require(tokensMinted < tokenCap); contributors = contributors.add(1); servusToken.mint(_beneficiary, tokens); TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(); } /** * Get the price in wei for current premium * @return price {uint256} */ function getPriceInWei() constant public returns (uint256) { uint256 price; if (totalWeiRaised < firstDiscountCap) { price = firstDiscountPrice; } else if (totalWeiRaised < secondDiscountCap) { price = secondDiscountPrice; } else if (totalWeiRaised < thirdDiscountCap) { price = thirdDiscountPrice; } else { price = BASE_PRICE_IN_WEI; } return price; } /** * Forwards funds to the tokensale wallet */ function forwardFunds() internal { servusMultiSig.transfer(msg.value); } /** * Validates the purchase (period, minimum amount, within cap) * @return {bool} valid */ function validPurchase() internal constant returns (bool) { uint256 current = now; bool presaleStarted = (current >= startTime || started); bool presaleNotEnded = current <= endTime; bool nonZeroPurchase = msg.value != 0; return nonZeroPurchase && presaleStarted && presaleNotEnded; } /** * Returns the total Servus token supply * @return totalSupply {uint256} Servus Token Total Supply */ function totalSupply() public constant returns (uint256) { return servusToken.totalSupply(); } /** * Returns token holder Servus Token balance * @param _owner {address} Token holder address * @return balance {uint256} Corresponding token holder balance */ function balanceOf(address _owner) public constant returns (uint256) { return servusToken.balanceOf(_owner); } /** * Change the Servus Token controller * @param _newController {address} New Servus Token controller */ function changeController(address _newController) public { require(isContract(_newController)); servusToken.transferControl(_newController); } function enableTransfers() public { if (now < endTime) { require(msg.sender == owner); } servusToken.enableTransfers(true); } function lockTransfers() public onlyOwner { require(now < endTime); servusToken.enableTransfers(false); } function enableMasterTransfers() public onlyOwner { servusToken.enableMasterTransfers(true); } function lockMasterTransfers() public onlyOwner { servusToken.enableMasterTransfers(false); } function forceStart() public onlyOwner { started = true; } function allocateServusTokens() public onlyOwner whenNotFinalized { require(!servusTokensAllocated); servusToken.mint(servusMultiSig, TOKENS_ALLOCATED_TO_SERVUS); servusTokensAllocated = true; } function finalize() public onlyOwner { require(paused); require(servusTokensAllocated); servusToken.finishMinting(); servusToken.enableTransfers(true); Finalized(); finalized = true; } function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } modifier whenNotFinalized() { require(!finalized); _; } }
Returns the total Servus token supply return totalSupply {uint256} Servus Token Total Supply/
function totalSupply() public constant returns (uint256) { return servusToken.totalSupply(); }
13,013,135
//SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {IAaveGovernanceV2} from "./interfaces/Aave/IAaveGovernanceV2.sol"; import {IGovernanceStrategy} from "./interfaces/Aave/IGovernanceStrategy.sol"; import "./interfaces/IAavePool.sol"; import "./interfaces/IWrapperToken.sol"; import "./interfaces/Aave/IStakedAave.sol"; import "./interfaces/IERC20Details.sol"; import "./interfaces/IBribeExecutor.sol"; import "./BribePoolBase.sol"; //////////////////////////////////////////////////////////////////////////////////////////// /// /// @title AavePool /// @author [email protected] /// @notice /// //////////////////////////////////////////////////////////////////////////////////////////// contract AavePool is BribePoolBase, IAavePool, Pausable, ReentrancyGuard { using SafeERC20 for IERC20; using SafeCast for uint256; /// @dev share scale uint256 private constant SHARE_SCALE = 1e12; /// @dev maximum claim iterations uint64 internal constant MAX_CLAIM_ITERATIONS = 10; /// @dev fee precision uint64 internal constant FEE_PRECISION = 10000; /// @dev fee percentage share is 16% uint128 internal constant FEE_PERCENTAGE = 1600; /// @dev seconds per block uint64 internal constant secondPerBlock = 13; /// @dev aave governance address public immutable aaveGovernance; /// @dev bidders will bid with bidAsset e.g. usdc IERC20 public immutable bidAsset; /// @dev bribe token IERC20 public immutable bribeToken; /// @dev aave token IERC20 public immutable aaveToken; /// @dev stkAave token IERC20 public immutable stkAaveToken; /// @dev aave wrapper token IWrapperToken public immutable wrapperAaveToken; /// @dev stkAave wrapper token IWrapperToken public immutable wrapperStkAaveToken; /// @dev feeReceipient address to send received fees to address public feeReceipient; /// @dev pending rewards to be distributed uint128 internal pendingRewardToBeDistributed; /// @dev fees received uint128 public feesReceived; /// @dev asset index AssetIndex public assetIndex; /// @dev bribre reward config BribeReward public bribeRewardConfig; /// @dev bid id to bid information mapping(uint256 => Bid) public bids; /// @dev blocked proposals mapping(uint256 => bool) public blockedProposals; /// @dev proposal id to bid information mapping(uint256 => uint256) internal bidIdToProposalId; /// @dev user info mapping(address => UserInfo) internal users; constructor( address bribeToken_, address aaveToken_, address stkAaveToken_, address bidAsset_, address aave_, address feeReceipient_, IWrapperToken wrapperAaveToken_, IWrapperToken wrapperStkAaveToken_, BribeReward memory rewardConfig_ ) BribePoolBase() { require(bribeToken_ != address(0), "BRIBE_TOKEN"); require(aaveToken_ != address(0), "AAVE_TOKEN"); require(stkAaveToken_ != address(0), "STKAAVE_TOKEN"); require(aave_ != address(0), "AAVE_GOVERNANCE"); require(address(bidAsset_) != address(0), "BID_ASSET"); require(feeReceipient_ != address(0), "FEE_RECEIPIENT"); require(address(wrapperAaveToken_) != address(0), "AAVE_WRAPPER"); require(address(wrapperStkAaveToken_) != address(0), "STK_WRAPPER"); bribeToken = IERC20(bribeToken_); aaveToken = IERC20(aaveToken_); stkAaveToken = IERC20(stkAaveToken_); aaveGovernance = aave_; bidAsset = IERC20(bidAsset_); bribeRewardConfig = rewardConfig_; feeReceipient = feeReceipient_; // initialize wrapper tokens wrapperAaveToken_.initialize(aaveToken_); wrapperStkAaveToken_.initialize(stkAaveToken_); wrapperAaveToken = wrapperAaveToken_; wrapperStkAaveToken = wrapperStkAaveToken_; } /// @notice deposit /// @param asset either Aave or stkAave /// @param recipient address to mint the receipt tokens /// @param amount amount of tokens to deposit /// @param claim claim stk aave rewards from Aave function deposit( IERC20 asset, address recipient, uint128 amount, bool claim ) external override whenNotPaused nonReentrant { if (asset == aaveToken) { _deposit(asset, wrapperAaveToken, recipient, amount, claim); } else { _deposit(stkAaveToken, wrapperStkAaveToken, recipient, amount, claim); } } /// @notice withdraw /// @param asset either Aave or stkAave /// @param recipient address to mint the receipt tokens /// @param amount amount of tokens to deposit /// @param claim claim stk aave rewards from Aave function withdraw( IERC20 asset, address recipient, uint128 amount, bool claim ) external override nonReentrant { if (asset == aaveToken) { _withdraw(asset, wrapperAaveToken, recipient, amount, claim); } else { _withdraw(stkAaveToken, wrapperStkAaveToken, recipient, amount, claim); } } /// @dev vote to `proposalId` with `support` option /// @param proposalId proposal id function vote(uint256 proposalId) external nonReentrant { Bid storage currentBid = bids[proposalId]; require(currentBid.endTime > 0, "INVALID_PROPOSAL"); require(currentBid.endTime < block.timestamp, "BID_ACTIVE"); distributeRewards(proposalId); IAaveGovernanceV2(aaveGovernance).submitVote(proposalId, currentBid.support); emit Vote(proposalId, msg.sender, currentBid.support, block.timestamp); } /// @dev place a bid after check AaveGovernance status /// @param bidder bidder address /// @param proposalId proposal id /// @param amount amount of bid assets /// @param support the suport for the proposal function bid( address bidder, uint256 proposalId, uint128 amount, bool support ) external override whenNotPaused nonReentrant { IAaveGovernanceV2.ProposalState state = IAaveGovernanceV2(aaveGovernance).getProposalState( proposalId ); require( state == IAaveGovernanceV2.ProposalState.Pending || state == IAaveGovernanceV2.ProposalState.Active, "INVALID_PROPOSAL_STATE" ); require(blockedProposals[proposalId] == false, "PROPOSAL_BLOCKED"); Bid storage currentBid = bids[proposalId]; address prevHighestBidder = currentBid.highestBidder; uint128 currentHighestBid = currentBid.highestBid; uint128 newHighestBid; // new bid if (prevHighestBidder == address(0)) { uint64 endTime = uint64(_getAuctionExpiration(proposalId)); currentBid.endTime = endTime; currentBid.totalVotes = votingPower(proposalId); currentBid.proposalStartBlock = IAaveGovernanceV2(aaveGovernance) .getProposalById(proposalId) .startBlock; } require(currentBid.endTime > block.timestamp, "BID_ENDED"); require(currentBid.totalVotes > 0, "INVALID_VOTING_POWER"); // if bidder == currentHighestBidder increase the bid amount if (prevHighestBidder == bidder) { bidAsset.safeTransferFrom(msg.sender, address(this), amount); newHighestBid = currentHighestBid + amount; } else { require(amount > currentHighestBid, "LOW_BID"); bidAsset.safeTransferFrom(msg.sender, address(this), amount); // refund to previous highest bidder if (prevHighestBidder != address(0)) { pendingRewardToBeDistributed -= currentHighestBid; bidAsset.safeTransfer(prevHighestBidder, currentHighestBid); } newHighestBid = amount; } // write the new bid info to storage pendingRewardToBeDistributed += amount; currentBid.highestBid = newHighestBid; currentBid.support = support; currentBid.highestBidder = bidder; emit HighestBidIncreased( proposalId, prevHighestBidder, bidder, msg.sender, newHighestBid, support ); } /// @dev refund bid for a cancelled proposal ONLY if it was not voted on /// @param proposalId proposal id function refund(uint256 proposalId) external nonReentrant { IAaveGovernanceV2.ProposalState state = IAaveGovernanceV2(aaveGovernance).getProposalState( proposalId ); require(state == IAaveGovernanceV2.ProposalState.Canceled, "PROPOSAL_ACTIVE"); Bid storage currentBid = bids[proposalId]; uint128 highestBid = currentBid.highestBid; address highestBidder = currentBid.highestBidder; // we do not refund if no high bid or if the proposal has been voted on if (highestBid == 0 || currentBid.voted) return; // reset the bid proposal state delete bids[proposalId]; // refund the bid money pendingRewardToBeDistributed -= highestBid; bidAsset.safeTransfer(highestBidder, highestBid); emit Refund(proposalId, highestBidder, highestBid); } /// @dev distribute rewards for the proposal /// @notice called in children's vote function (after bidding process ended) /// @param proposalId id of proposal to distribute rewards fo function distributeRewards(uint256 proposalId) public { Bid storage currentBid = bids[proposalId]; // ensure that the bidding period has ended require(block.timestamp > currentBid.endTime, "BID_ACTIVE"); if (currentBid.voted) return; uint128 highestBid = currentBid.highestBid; uint128 feeAmount = _calculateFeeAmount(highestBid); // reduce pending reward pendingRewardToBeDistributed -= highestBid; assetIndex.bidIndex += (highestBid - feeAmount); feesReceived += feeAmount; currentBid.voted = true; // rewrite the highest bid minus fee // set and increase the bid id bidIdToProposalId[assetIndex.bidId] = proposalId; assetIndex.bidId += 1; emit RewardDistributed(proposalId, highestBid); } /// @dev withdrawFees withdraw fees /// Enables ONLY the fee receipient to withdraw the pool accrued fees function withdrawFees() external override nonReentrant returns (uint256 feeAmount) { require(msg.sender == feeReceipient, "ONLY_RECEIPIENT"); feeAmount = feesReceived; if (feeAmount > 0) { feesReceived = 0; bidAsset.safeTransfer(feeReceipient, feeAmount); } emit WithdrawFees(address(this), feeAmount, block.timestamp); } /// @dev get reward amount for user specified by `user` /// @param user address of user to check balance of function rewardBalanceOf(address user) external view returns ( uint256 totalPendingBidReward, uint256 totalPendingStkAaveReward, uint256 totalPendingBribeReward ) { uint256 userAaveBalance = wrapperAaveToken.balanceOf(user); uint256 userStkAaveBalance = wrapperStkAaveToken.balanceOf(user); uint256 pendingBribeReward = _userPendingBribeReward( userAaveBalance + userStkAaveBalance, users[user].bribeLastRewardPerShare, _calculateBribeRewardPerShare(_calculateBribeRewardIndex()) ); uint256 pendingBidReward; uint256 currentBidRewardCount = assetIndex.bidId; if (userAaveBalance > 0) { pendingBidReward += _calculateUserPendingBidRewards( wrapperAaveToken, user, users[user].aaveLastBidId, currentBidRewardCount ); } if (userStkAaveBalance > 0) { pendingBidReward += _calculateUserPendingBidRewards( wrapperStkAaveToken, user, users[user].stkAaveLastBidId, currentBidRewardCount ); } totalPendingBidReward = users[user].totalPendingBidReward + pendingBidReward; (uint128 rewardsToReceive, ) = _stkAaveRewardsToReceive(); totalPendingStkAaveReward = users[user].totalPendingStkAaveReward + _userPendingstkAaveRewards( user, users[user].stkAaveLastRewardPerShare, _calculateStkAaveRewardPerShare(rewardsToReceive), wrapperStkAaveToken ); totalPendingBribeReward = users[user].totalPendingBribeReward + pendingBribeReward; } /// @dev claimReward for msg.sender /// @param to address to send the rewards to /// @param executor An external contract to call with /// @param data data to call the executor contract /// @param claim claim stk aave rewards from Aave function claimReward( address to, IBribeExecutor executor, bytes calldata data, bool claim ) external whenNotPaused nonReentrant { // accrue rewards for both stkAave and Aave token balances _accrueRewards(msg.sender, claim); UserInfo storage _currentUser = users[msg.sender]; uint128 pendingBid = _currentUser.totalPendingBidReward; uint128 pendingStkAaveReward = _currentUser.totalPendingStkAaveReward; uint128 pendingBribeReward = _currentUser.totalPendingBribeReward; unchecked { // reset the reward calculation _currentUser.totalPendingBidReward = 0; _currentUser.totalPendingStkAaveReward = 0; // update lastStkAaveRewardBalance assetIndex.lastStkAaveRewardBalance -= pendingStkAaveReward; } if (pendingBid > 0) { bidAsset.safeTransfer(to, pendingBid); } if (pendingStkAaveReward > 0 && claim) { // claim stk aave rewards IStakedAave(address(stkAaveToken)).claimRewards(to, pendingStkAaveReward); } if (pendingBribeReward > 0 && bribeToken.balanceOf(address(this)) > pendingBribeReward) { _currentUser.totalPendingBribeReward = 0; if (address(executor) != address(0)) { bribeToken.safeTransfer(address(executor), pendingBribeReward); executor.execute(msg.sender, pendingBribeReward, data); } else { require(to != address(0), "INVALID_ADDRESS"); bribeToken.safeTransfer(to, pendingBribeReward); } } emit RewardClaim( msg.sender, pendingBid, pendingStkAaveReward, pendingBribeReward, block.timestamp ); } /// @dev block a proposalId from used in the pool /// @param proposalId proposalId function blockProposalId(uint256 proposalId) external onlyOwner { require(blockedProposals[proposalId] == false, "PROPOSAL_INACTIVE"); Bid storage currentBid = bids[proposalId]; // check if the propoal has already been voted on require(currentBid.voted == false, "BID_DISTRIBUTED"); blockedProposals[proposalId] = true; uint128 highestBid = currentBid.highestBid; // check if the proposalId has any bids // if there is any current highest bidder // and the reward has not been distributed refund the bidder if (highestBid > 0) { pendingRewardToBeDistributed -= highestBid; address highestBidder = currentBid.highestBidder; // reset the bids delete bids[proposalId]; bidAsset.safeTransfer(highestBidder, highestBid); } emit BlockProposalId(proposalId, block.timestamp); } /// @dev unblock a proposalId from used in the pool /// @param proposalId proposalId function unblockProposalId(uint256 proposalId) external onlyOwner { require(blockedProposals[proposalId] == true, "PROPOSAL_ACTIVE"); blockedProposals[proposalId] = false; emit UnblockProposalId(proposalId, block.timestamp); } /// @dev returns the pool voting power for a proposal /// @param proposalId proposalId to fetch pool voting power function votingPower(uint256 proposalId) public view returns (uint256 power) { IAaveGovernanceV2.ProposalWithoutVotes memory proposal = IAaveGovernanceV2(aaveGovernance) .getProposalById(proposalId); address governanceStrategy = IAaveGovernanceV2(aaveGovernance).getGovernanceStrategy(); power = IGovernanceStrategy(governanceStrategy).getVotingPowerAt( address(this), proposal.startBlock ); } /// @dev getPendingRewardToBeDistributed returns the pending reward to be distributed /// minus fees function getPendingRewardToBeDistributed() external view returns (uint256 pendingReward) { pendingReward = pendingRewardToBeDistributed - _calculateFeeAmount(pendingRewardToBeDistributed); } /// @notice pause pool actions function pause() external onlyOwner { _pause(); } /// @notice unpause pool actions function unpause() external onlyOwner { _unpause(); } /// @notice setFeeRecipient /// @param newReceipient new fee receipeitn function setFeeRecipient(address newReceipient) external onlyOwner { require(newReceipient != address(0), "INVALID_RECIPIENT"); feeReceipient = newReceipient; emit UpdateFeeRecipient(address(this), newReceipient); } /// @notice setStartTimestamp /// @param startTimestamp when to start distributing rewards /// @param rewardPerSecond reward to distribute per second function setStartTimestamp(uint64 startTimestamp, uint128 rewardPerSecond) external onlyOwner { require(startTimestamp > block.timestamp, "INVALID_START_TIMESTAMP"); if (bribeRewardConfig.endTimestamp != 0) { require(startTimestamp < bribeRewardConfig.endTimestamp, "HIGH_TIMESTAMP"); } _updateBribeRewardIndex(); uint64 oldTimestamp = bribeRewardConfig.startTimestamp; bribeRewardConfig.startTimestamp = startTimestamp; _setRewardPerSecond(rewardPerSecond); emit SetBribeRewardStartTimestamp(oldTimestamp, startTimestamp); } /// @notice setEndTimestamp /// @param endTimestamp end of bribe rewards function setEndTimestamp(uint64 endTimestamp) external onlyOwner { require(endTimestamp > block.timestamp, "INVALID_END_TIMESTAMP"); require(endTimestamp > bribeRewardConfig.startTimestamp, "LOW_TIMESTAMP"); _updateBribeRewardIndex(); uint64 oldTimestamp = bribeRewardConfig.endTimestamp; bribeRewardConfig.endTimestamp = endTimestamp; emit SetBribeRewardEndTimestamp(oldTimestamp, endTimestamp); } /// @notice setEndTimestamp /// @param rewardPerSecond amount of rewards to distribute per second function setRewardPerSecond(uint128 rewardPerSecond) public onlyOwner { _updateBribeRewardIndex(); _setRewardPerSecond(rewardPerSecond); } function _setRewardPerSecond(uint128 rewardPerSecond) internal { require(rewardPerSecond > 0, "INVALID_REWARD_SECOND"); uint128 oldReward = bribeRewardConfig.rewardAmountDistributedPerSecond; bribeRewardConfig.rewardAmountDistributedPerSecond = rewardPerSecond; emit SetBribeRewardPerSecond(oldReward, rewardPerSecond); } /// @notice withdrawRemainingBribeReward /// @dev there is a 30 days window period after endTimestamp where a user can claim /// rewards before it can be reclaimed by Bribe function withdrawRemainingBribeReward() external onlyOwner { require(bribeRewardConfig.endTimestamp != 0, "INVALID_END_TIMESTAMP"); require(block.timestamp > bribeRewardConfig.endTimestamp + 30 days, "GRACE_PERIOD"); uint256 remaining = bribeToken.balanceOf(address(this)); bribeToken.safeTransfer(address(this), remaining); emit WithdrawRemainingReward(remaining); } /// @dev _calculateFeeAmount calculate the fee percentage share function _calculateFeeAmount(uint128 amount) internal pure returns (uint128 feeAmount) { feeAmount = (amount * FEE_PERCENTAGE) / FEE_PRECISION; } struct NewUserRewardInfoLocalVars { uint256 pendingBidReward; uint256 pendingstkAaveReward; uint256 pendingBribeReward; uint256 newUserAaveBidId; uint256 newUserStAaveBidId; } /// @dev _accrueRewards accrue rewards for an address /// @param user address to accrue rewards for /// @param claim claim pending stk aave rewards function _accrueRewards(address user, bool claim) internal { require(user != address(0), "INVALID_ADDRESS"); UserInfo storage _user = users[user]; NewUserRewardInfoLocalVars memory userRewardVars; uint256 userAaveBalance = wrapperAaveToken.balanceOf(user); uint256 userStkAaveBalance = wrapperStkAaveToken.balanceOf(user); uint256 total = userAaveBalance + userStkAaveBalance; // update bribe reward index _updateBribeRewardIndex(); if (total > 0) { // calculate updated bribe rewards userRewardVars.pendingBribeReward = _userPendingBribeReward( total, _user.bribeLastRewardPerShare, assetIndex.bribeRewardPerShare ); } if (userAaveBalance > 0) { // calculate pendingBidRewards uint256 reward; (userRewardVars.newUserAaveBidId, reward) = _userPendingBidRewards( assetIndex.bidIndex, wrapperAaveToken, user, users[user].aaveLastBidId ); userRewardVars.pendingBidReward += reward; } if (claim) { _updateStkAaveStakeReward(); } if (userStkAaveBalance > 0) { // calculate pendingBidRewards uint256 reward; (userRewardVars.newUserStAaveBidId, reward) = _userPendingBidRewards( assetIndex.bidIndex, wrapperStkAaveToken, user, users[user].stkAaveLastBidId ); userRewardVars.pendingBidReward += reward; // distribute stkAaveTokenRewards to the user too userRewardVars.pendingstkAaveReward = _userPendingstkAaveRewards( user, users[user].stkAaveLastRewardPerShare, assetIndex.stkAaveRewardPerShare, wrapperStkAaveToken ); } // write to storage _user.totalPendingBribeReward += userRewardVars.pendingBribeReward.toUint128(); _user.totalPendingBidReward += userRewardVars.pendingBidReward.toUint128(); _user.totalPendingStkAaveReward += userRewardVars.pendingstkAaveReward.toUint128(); _user.stkAaveLastRewardPerShare = assetIndex.stkAaveRewardPerShare; _user.bribeLastRewardPerShare = assetIndex.bribeRewardPerShare; _user.aaveLastBidId = userRewardVars.newUserAaveBidId.toUint128(); _user.stkAaveLastBidId = userRewardVars.newUserStAaveBidId.toUint128(); emit RewardAccrue( user, userRewardVars.pendingBidReward, userRewardVars.pendingstkAaveReward, userRewardVars.pendingBribeReward, block.timestamp ); } /// @dev deposit governance token /// @param asset asset to withdraw /// @param receiptToken asset wrapper token /// @param recipient address to award the receipt tokens /// @param amount amount to deposit /// @param claim claim pending stk aave rewards /// @notice emit {Deposit} event function _deposit( IERC20 asset, IWrapperToken receiptToken, address recipient, uint128 amount, bool claim ) internal { require(amount > 0, "INVALID_AMOUNT"); // accrue user pending rewards _accrueRewards(recipient, claim); asset.safeTransferFrom(msg.sender, address(this), amount); // performs check that recipient != address(0) receiptToken.mint(recipient, amount); emit Deposit(asset, recipient, amount, block.timestamp); } /// @dev withdraw governance token /// @param asset asset to withdraw /// @param receiptToken asset wrapper token /// @param recipient address to award the receipt tokens /// @param amount amount to withdraw /// @param claim claim pending stk aave rewards function _withdraw( IERC20 asset, IWrapperToken receiptToken, address recipient, uint128 amount, bool claim ) internal { require(amount > 0, "INVALID_AMOUNT"); require(receiptToken.balanceOf(msg.sender) >= amount, "INVALID_BALANCE"); // claim pending bid rewards only _accrueRewards(msg.sender, claim); // burn tokens receiptToken.burn(msg.sender, amount); // send back tokens asset.safeTransfer(recipient, amount); emit Withdraw(asset, msg.sender, amount, block.timestamp); } /// @dev _calculateBribeRewardIndex function _calculateBribeRewardIndex() internal view returns (uint256 amount) { if ( bribeRewardConfig.startTimestamp == 0 || bribeRewardConfig.startTimestamp > block.timestamp ) return 0; uint64 startTimestamp = (bribeRewardConfig.startTimestamp > assetIndex.bribeLastRewardTimestamp) ? bribeRewardConfig.startTimestamp : assetIndex.bribeLastRewardTimestamp; uint256 endTimestamp; if (bribeRewardConfig.endTimestamp == 0) { endTimestamp = block.timestamp; } else { endTimestamp = block.timestamp > bribeRewardConfig.endTimestamp ? bribeRewardConfig.endTimestamp : block.timestamp; } if (endTimestamp > startTimestamp) { amount = (endTimestamp - startTimestamp) * bribeRewardConfig.rewardAmountDistributedPerSecond; } } /// @dev _updateBribeRewardIndex function _updateBribeRewardIndex() internal { uint256 newRewardAmount = _calculateBribeRewardIndex(); assetIndex.bribeLastRewardTimestamp = block.timestamp.toUint64(); assetIndex.bribeRewardIndex += newRewardAmount.toUint128(); assetIndex.bribeRewardPerShare = _calculateBribeRewardPerShare(newRewardAmount).toUint128(); emit AssetReward(bribeToken, assetIndex.bribeRewardIndex, block.timestamp); } /// @dev _calculateBribeRewardPerShare /// @param newRewardAmount additional reward function _calculateBribeRewardPerShare(uint256 newRewardAmount) internal view returns (uint256 newBribeRewardPerShare) { uint256 increaseSharePrice; if (newRewardAmount > 0) { increaseSharePrice = ((newRewardAmount * SHARE_SCALE) / _totalSupply()); } newBribeRewardPerShare = assetIndex.bribeRewardPerShare + increaseSharePrice; } /// @dev _userPendingBribeReward /// @param userBalance user aave + stkAave balance /// @param userLastPricePerShare user last price per share /// @param currentBribeRewardPerShare current reward per share function _userPendingBribeReward( uint256 userBalance, uint256 userLastPricePerShare, uint256 currentBribeRewardPerShare ) internal pure returns (uint256 pendingReward) { if (userBalance > 0 && currentBribeRewardPerShare > 0) { pendingReward = ((userBalance * (currentBribeRewardPerShare - userLastPricePerShare)) / SHARE_SCALE).toUint128(); } } /// @dev _totalSupply current total supply of tokens function _totalSupply() internal view returns (uint256) { return wrapperAaveToken.totalSupply() + wrapperStkAaveToken.totalSupply(); } /// @dev returns the user bid reward share /// @param receiptToken wrapper token /// @param user user /// @param userLastBidId user last bid id function _userPendingBidRewards( uint128 currentBidIndex, IWrapperToken receiptToken, address user, uint128 userLastBidId ) internal view returns (uint256 accrueBidId, uint256 totalPendingReward) { if (currentBidIndex == 0) return (0, 0); uint256 currentBidRewardCount = assetIndex.bidId; if (userLastBidId == currentBidRewardCount) return (currentBidRewardCount, 0); accrueBidId = (currentBidRewardCount - userLastBidId) <= MAX_CLAIM_ITERATIONS ? currentBidRewardCount : userLastBidId + MAX_CLAIM_ITERATIONS; totalPendingReward = _calculateUserPendingBidRewards( receiptToken, user, userLastBidId, accrueBidId ); } /// @dev _calculateUserPendingBidRewards /// @param receiptToken wrapper token /// @param user user /// @param userLastBidId user last bid id /// @param maxRewardId maximum bid id to accrue rewards to function _calculateUserPendingBidRewards( IWrapperToken receiptToken, address user, uint256 userLastBidId, uint256 maxRewardId ) internal view returns (uint256 totalPendingReward) { for (uint256 i = userLastBidId; i < maxRewardId; i++) { uint256 proposalId = bidIdToProposalId[i]; Bid storage _bid = bids[proposalId]; uint128 highestBid = _bid.highestBid; // only calculate if highest bid is available and it has been distributed if (highestBid > 0 && _bid.voted) { uint256 amount = receiptToken.getDepositAt(user, _bid.proposalStartBlock); if (amount > 0) { // subtract fee from highest bid totalPendingReward += (amount * (highestBid - _calculateFeeAmount(highestBid))) / _bid.totalVotes; } } } } /// @dev update the stkAAve aave reward index function _updateStkAaveStakeReward() internal { (uint128 rewardsToReceive, uint256 newBalance) = _stkAaveRewardsToReceive(); if (rewardsToReceive == 0) return; assetIndex.rewardIndex += rewardsToReceive; assetIndex.stkAaveRewardPerShare = _calculateStkAaveRewardPerShare(rewardsToReceive); assetIndex.lastStkAaveRewardBalance = newBalance; emit AssetReward(aaveToken, assetIndex.rewardIndex, block.timestamp); } /// @dev _calculateStkAaveRewardPerShare /// @param rewardsToReceive amount of aave rewards to receive function _calculateStkAaveRewardPerShare(uint256 rewardsToReceive) internal view returns (uint128 newRewardPerShare) { uint256 increaseRewardSharePrice; if (rewardsToReceive > 0) { increaseRewardSharePrice = ((rewardsToReceive * SHARE_SCALE) / wrapperStkAaveToken.totalSupply()); } newRewardPerShare = (assetIndex.stkAaveRewardPerShare + increaseRewardSharePrice) .toUint128(); } /// @dev _stkAaveRewardsToReceive function _stkAaveRewardsToReceive() internal view returns (uint128 rewardsToReceive, uint256 newBalance) { newBalance = IStakedAave(address(stkAaveToken)).getTotalRewardsBalance(address(this)); rewardsToReceive = newBalance.toUint128() - assetIndex.lastStkAaveRewardBalance.toUint128(); } /// @dev get the user stkAave aave reward share /// @param user user address /// @param userLastPricePerShare userLastPricePerShare /// @param currentStkAaveRewardPerShare the latest reward per share /// @param receiptToken stak aave wrapper token function _userPendingstkAaveRewards( address user, uint128 userLastPricePerShare, uint128 currentStkAaveRewardPerShare, IWrapperToken receiptToken ) internal view returns (uint256 pendingReward) { uint256 userBalance = receiptToken.balanceOf(user); if (userBalance > 0 && currentStkAaveRewardPerShare > 0) { uint128 rewardDebt = ((userBalance * userLastPricePerShare) / SHARE_SCALE).toUint128(); pendingReward = (((userBalance * currentStkAaveRewardPerShare) / SHARE_SCALE) - rewardDebt).toUint128(); } } /// @dev get auction expiration of `proposalId` /// @param proposalId proposal id function _getAuctionExpiration(uint256 proposalId) internal view returns (uint256) { IAaveGovernanceV2.ProposalWithoutVotes memory proposal = IAaveGovernanceV2(aaveGovernance) .getProposalById(proposalId); return block.timestamp + (proposal.endBlock - block.number) * secondPerBlock - 1 hours; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol) pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; pragma abicoder v2; import {IExecutorWithTimelock} from "./IExecutorWithTimelock.sol"; interface IAaveGovernanceV2 { enum ProposalState { Pending, Canceled, Active, Failed, Succeeded, Queued, Expired, Executed } struct Vote { bool support; uint248 votingPower; } struct Proposal { uint256 id; address creator; IExecutorWithTimelock executor; address[] targets; uint256[] values; string[] signatures; bytes[] calldatas; bool[] withDelegatecalls; uint256 startBlock; uint256 endBlock; uint256 executionTime; uint256 forVotes; uint256 againstVotes; bool executed; bool canceled; address strategy; bytes32 ipfsHash; mapping(address => Vote) votes; } struct ProposalWithoutVotes { uint256 id; address creator; IExecutorWithTimelock executor; address[] targets; uint256[] values; string[] signatures; bytes[] calldatas; bool[] withDelegatecalls; uint256 startBlock; uint256 endBlock; uint256 executionTime; uint256 forVotes; uint256 againstVotes; bool executed; bool canceled; address strategy; bytes32 ipfsHash; } /** * @dev emitted when a new proposal is created * @param id Id of the proposal * @param creator address of the creator * @param executor The ExecutorWithTimelock contract that will execute the proposal * @param targets list of contracts called by proposal's associated transactions * @param values list of value in wei for each propoposal's associated transaction * @param signatures list of function signatures (can be empty) to be used when created the callData * @param calldatas list of calldatas: if associated signature empty, calldata ready, else calldata is arguments * @param withDelegatecalls boolean, true = transaction delegatecalls the taget, else calls the target * @param startBlock block number when vote starts * @param endBlock block number when vote ends * @param strategy address of the governanceStrategy contract * @param ipfsHash IPFS hash of the proposal **/ event ProposalCreated( uint256 id, address indexed creator, IExecutorWithTimelock indexed executor, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, bool[] withDelegatecalls, uint256 startBlock, uint256 endBlock, address strategy, bytes32 ipfsHash ); /** * @dev emitted when a proposal is canceled * @param id Id of the proposal **/ event ProposalCanceled(uint256 id); /** * @dev emitted when a proposal is queued * @param id Id of the proposal * @param executionTime time when proposal underlying transactions can be executed * @param initiatorQueueing address of the initiator of the queuing transaction **/ event ProposalQueued(uint256 id, uint256 executionTime, address indexed initiatorQueueing); /** * @dev emitted when a proposal is executed * @param id Id of the proposal * @param initiatorExecution address of the initiator of the execution transaction **/ event ProposalExecuted(uint256 id, address indexed initiatorExecution); /** * @dev emitted when a vote is registered * @param id Id of the proposal * @param voter address of the voter * @param support boolean, true = vote for, false = vote against * @param votingPower Power of the voter/vote **/ event VoteEmitted(uint256 id, address indexed voter, bool support, uint256 votingPower); event GovernanceStrategyChanged(address indexed newStrategy, address indexed initiatorChange); event VotingDelayChanged(uint256 newVotingDelay, address indexed initiatorChange); event ExecutorAuthorized(address executor); event ExecutorUnauthorized(address executor); /** * @dev Creates a Proposal (needs Proposition Power of creator > Threshold) * @param executor The ExecutorWithTimelock contract that will execute the proposal * @param targets list of contracts called by proposal's associated transactions * @param values list of value in wei for each propoposal's associated transaction * @param signatures list of function signatures (can be empty) to be used when created the callData * @param calldatas list of calldatas: if associated signature empty, calldata ready, else calldata is arguments * @param withDelegatecalls if true, transaction delegatecalls the taget, else calls the target * @param ipfsHash IPFS hash of the proposal **/ function create( IExecutorWithTimelock executor, address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, bool[] memory withDelegatecalls, bytes32 ipfsHash ) external returns (uint256); /** * @dev Cancels a Proposal, * either at anytime by guardian * or when proposal is Pending/Active and threshold no longer reached * @param proposalId id of the proposal **/ function cancel(uint256 proposalId) external; /** * @dev Queue the proposal (If Proposal Succeeded) * @param proposalId id of the proposal to queue **/ function queue(uint256 proposalId) external; /** * @dev Execute the proposal (If Proposal Queued) * @param proposalId id of the proposal to execute **/ function execute(uint256 proposalId) external payable; /** * @dev Function allowing msg.sender to vote for/against a proposal * @param proposalId id of the proposal * @param support boolean, true = vote for, false = vote against **/ function submitVote(uint256 proposalId, bool support) external; /** * @dev Function to register the vote of user that has voted offchain via signature * @param proposalId id of the proposal * @param support boolean, true = vote for, false = vote against * @param v v part of the voter signature * @param r r part of the voter signature * @param s s part of the voter signature **/ function submitVoteBySignature( uint256 proposalId, bool support, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Set new GovernanceStrategy * Note: owner should be a timelocked executor, so needs to make a proposal * @param governanceStrategy new Address of the GovernanceStrategy contract **/ function setGovernanceStrategy(address governanceStrategy) external; /** * @dev Set new Voting Delay (delay before a newly created proposal can be voted on) * Note: owner should be a timelocked executor, so needs to make a proposal * @param votingDelay new voting delay in seconds **/ function setVotingDelay(uint256 votingDelay) external; /** * @dev Add new addresses to the list of authorized executors * @param executors list of new addresses to be authorized executors **/ function authorizeExecutors(address[] memory executors) external; /** * @dev Remove addresses to the list of authorized executors * @param executors list of addresses to be removed as authorized executors **/ function unauthorizeExecutors(address[] memory executors) external; /** * @dev Let the guardian abdicate from its priviledged rights **/ function __abdicate() external; /** * @dev Getter of the current GovernanceStrategy address * @return The address of the current GovernanceStrategy contracts **/ function getGovernanceStrategy() external view returns (address); /** * @dev Getter of the current Voting Delay (delay before a created proposal can be voted on) * Different from the voting duration * @return The voting delay in seconds **/ function getVotingDelay() external view returns (uint256); /** * @dev Returns whether an address is an authorized executor * @param executor address to evaluate as authorized executor * @return true if authorized **/ function isExecutorAuthorized(address executor) external view returns (bool); /** * @dev Getter the address of the guardian, that can mainly cancel proposals * @return The address of the guardian **/ function getGuardian() external view returns (address); /** * @dev Getter of the proposal count (the current number of proposals ever created) * @return the proposal count **/ function getProposalsCount() external view returns (uint256); /** * @dev Getter of a proposal by id * @param proposalId id of the proposal to get * @return the proposal as ProposalWithoutVotes memory object **/ function getProposalById(uint256 proposalId) external view returns (ProposalWithoutVotes memory); /** * @dev Getter of the Vote of a voter about a proposal * Note: Vote is a struct: ({bool support, uint248 votingPower}) * @param proposalId id of the proposal * @param voter address of the voter * @return The associated Vote memory object **/ function getVoteOnProposal(uint256 proposalId, address voter) external view returns (Vote memory); /** * @dev Get the current state of a proposal * @param proposalId id of the proposal * @return The current state if the proposal **/ function getProposalState(uint256 proposalId) external view returns (ProposalState); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; pragma abicoder v2; interface IGovernanceStrategy { /** * @dev Returns the Proposition Power of a user at a specific block number. * @param user Address of the user. * @param blockNumber Blocknumber at which to fetch Proposition Power * @return Power number **/ function getPropositionPowerAt(address user, uint256 blockNumber) external view returns (uint256); /** * @dev Returns the total supply of Outstanding Proposition Tokens * @param blockNumber Blocknumber at which to evaluate * @return total supply at blockNumber **/ function getTotalPropositionSupplyAt(uint256 blockNumber) external view returns (uint256); /** * @dev Returns the total supply of Outstanding Voting Tokens * @param blockNumber Blocknumber at which to evaluate * @return total supply at blockNumber **/ function getTotalVotingSupplyAt(uint256 blockNumber) external view returns (uint256); /** * @dev Returns the Vote Power of a user at a specific block number. * @param user Address of the user. * @param blockNumber Blocknumber at which to fetch Vote Power * @return Vote number **/ function getVotingPowerAt(address user, uint256 blockNumber) external view returns (uint256); } //SPDX-License-Identifier: Unlicense pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IAavePool { struct AssetIndex { // tracks the last stkAave aave reward balance uint256 lastStkAaveRewardBalance; // tracks the total Aave reward for stkAave holders uint128 rewardIndex; // bribe reward index; uint128 bribeRewardIndex; // bribe reward last timestamp uint64 bribeLastRewardTimestamp; // bid id uint64 bidId; // tracks the total bid reward // share to be distributed uint128 bidIndex; // tracks the reward per share uint128 bribeRewardPerShare; // tracks the reward per share uint128 stkAaveRewardPerShare; } struct BribeReward { uint128 rewardAmountDistributedPerSecond; uint64 startTimestamp; uint64 endTimestamp; } struct UserInfo { // stkaave reward index uint128 stkAaveLastRewardPerShare; // bribe reward index uint128 bribeLastRewardPerShare; // reward from the bids in the bribe pool uint128 totalPendingBidReward; // tracks aave reward from the stk aave pool uint128 totalPendingStkAaveReward; // tracks bribe distributed to the user uint128 totalPendingBribeReward; // tracks the last user bid id for aave deposit uint128 aaveLastBidId; // tracks the last user bid id for stkAave deposit uint128 stkAaveLastBidId; } /// @dev proposal bid info struct Bid { uint256 totalVotes; uint256 proposalStartBlock; uint128 highestBid; uint64 endTime; bool support; bool voted; address highestBidder; } /// @dev emitted on deposit event Deposit(IERC20 indexed token, address indexed user, uint256 amount, uint256 timestamp); /// @dev emitted on user reward accrue event AssetReward(IERC20 indexed asset, uint256 totalAmountAccrued, uint256 timestamp); /// @dev emitted on user reward accrue event RewardAccrue( address indexed user, uint256 pendingBidReward, uint256 pendingStkAaveReward, uint256 pendingBribeReward, uint256 timestamp ); event Withdraw(IERC20 indexed token, address indexed user, uint256 amount, uint256 timestamp); event RewardClaim( address indexed user, uint256 pendingBid, uint256 pendingReward, uint256 pendingBribeReward, uint256 timestamp ); event RewardDistributed(uint256 proposalId, uint256 amount); event HighestBidIncreased( uint256 indexed proposalId, address indexed prevHighestBidder, address indexed highestBidder, address sender, uint256 highestBid, bool support ); event BlockProposalId(uint256 indexed proposalId, uint256 timestamp); event UnblockProposalId(uint256 indexed proposalId, uint256 timestamp); event UpdateDelayPeriod(uint256 delayperiod, uint256 timestamp); /// @dev emitted on vote event Vote(uint256 indexed proposalId, address user, bool support, uint256 timestamp); /// @dev emitted on Refund event Refund(uint256 indexed proposalId, address bidder, uint256 bidAmount); /// @dev emitted on Unclaimed rewards event UnclaimedRewards(address owner, uint256 amount); /// @dev emitted on setEndTimestamp event SetBribeRewardEndTimestamp(uint256 oldTimestamp, uint256 endTimestamp); /// @dev emitted on setRewardPerSecond event SetBribeRewardPerSecond(uint256 oldRewardPerSecond, uint256 newRewardPerSecond); /// @dev emitted on withdrawRemainingReward event WithdrawRemainingReward(uint256 amount); /// @dev emmitted on setStartTimestamp event SetBribeRewardStartTimestamp(uint256 oldTimestamp, uint256 endTimestamp); /// @dev emitted on setFeeRecipient event UpdateFeeRecipient(address sender, address receipient); function deposit( IERC20 asset, address recipient, uint128 amount, bool claim ) external; function withdraw( IERC20 asset, address recipient, uint128 amount, bool claim ) external; function bid( address bidder, uint256 proposalId, uint128 amount, bool support ) external; } //SPDX-License-Identifier: Unlicense pragma solidity 0.8.4; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IWrapperToken is IERC20Upgradeable { function mint(address, uint256) external; function burn(address, uint256) external; function getAccountSnapshot(address user) external view returns (uint256[] memory, uint256[] memory); function getDepositAt(address user, uint256 blockNumber) external view returns (uint256 amount); function initialize(address underlying_) external; /// @dev emitted on update account snapshot event UpdateSnapshot( address indexed user, uint256 oldValue, uint256 newValue, uint256 timestamp ); } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IStakedAave is IERC20 { function claimRewards(address to, uint256 amount) external; function getTotalRewardsBalance(address staker) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; interface IERC20Details { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; interface IBribeExecutor { function execute( address user, uint256 amount, bytes calldata data ) external; } //SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/utils/Multicall.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import "./interfaces/Bribe/IBribeMultiAssetPool.sol"; import "./interfaces/IFeeDistributor.sol"; //////////////////////////////////////////////////////////////////////////////////////////// /// /// @title BribePoolBase /// @author [email protected] /// @notice /// //////////////////////////////////////////////////////////////////////////////////////////// abstract contract BribePoolBase is IBribeMultiAssetPool, IFeeDistributor, Ownable, Multicall { constructor() Ownable() {} /// @notice Call wrapper that performs `ERC20.permit` on `token`. // Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert) // if part of a batch this could be used to grief once as the second call would not need the permit function permitToken( IERC20Permit token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { token.permit(from, to, amount, deadline, v, r, s); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) 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 // 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: agpl-3.0 pragma solidity 0.8.4; pragma abicoder v2; import {IAaveGovernanceV2} from "./IAaveGovernanceV2.sol"; interface IExecutorWithTimelock { /** * @dev emitted when a new pending admin is set * @param newPendingAdmin address of the new pending admin **/ event NewPendingAdmin(address newPendingAdmin); /** * @dev emitted when a new admin is set * @param newAdmin address of the new admin **/ event NewAdmin(address newAdmin); /** * @dev emitted when a new delay (between queueing and execution) is set * @param delay new delay **/ event NewDelay(uint256 delay); /** * @dev emitted when a new (trans)action is Queued. * @param actionHash hash of the action * @param target address of the targeted contract * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target **/ event QueuedAction( bytes32 actionHash, address indexed target, uint256 value, string signature, bytes data, uint256 executionTime, bool withDelegatecall ); /** * @dev emitted when an action is Cancelled * @param actionHash hash of the action * @param target address of the targeted contract * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target **/ event CancelledAction( bytes32 actionHash, address indexed target, uint256 value, string signature, bytes data, uint256 executionTime, bool withDelegatecall ); /** * @dev emitted when an action is Cancelled * @param actionHash hash of the action * @param target address of the targeted contract * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target * @param resultData the actual callData used on the target **/ event ExecutedAction( bytes32 actionHash, address indexed target, uint256 value, string signature, bytes data, uint256 executionTime, bool withDelegatecall, bytes resultData ); /** * @dev Getter of the current admin address (should be governance) * @return The address of the current admin **/ function getAdmin() external view returns (address); /** * @dev Getter of the current pending admin address * @return The address of the pending admin **/ function getPendingAdmin() external view returns (address); /** * @dev Getter of the delay between queuing and execution * @return The delay in seconds **/ function getDelay() external view returns (uint256); /** * @dev Returns whether an action (via actionHash) is queued * @param actionHash hash of the action to be checked * keccak256(abi.encode(target, value, signature, data, executionTime, withDelegatecall)) * @return true if underlying action of actionHash is queued **/ function isActionQueued(bytes32 actionHash) external view returns (bool); /** * @dev Checks whether a proposal is over its grace period * @param governance Governance contract * @param proposalId Id of the proposal against which to test * @return true of proposal is over grace period **/ function isProposalOverGracePeriod(IAaveGovernanceV2 governance, uint256 proposalId) external view returns (bool); /** * @dev Getter of grace period constant * @return grace period in seconds **/ function GRACE_PERIOD() external view returns (uint256); /** * @dev Getter of minimum delay constant * @return minimum delay in seconds **/ function MINIMUM_DELAY() external view returns (uint256); /** * @dev Getter of maximum delay constant * @return maximum delay in seconds **/ function MAXIMUM_DELAY() external view returns (uint256); /** * @dev Function, called by Governance, that queue a transaction, returns action hash * @param target smart contract target * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target **/ function queueTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 executionTime, bool withDelegatecall ) external returns (bytes32); /** * @dev Function, called by Governance, that cancels a transaction, returns the callData executed * @param target smart contract target * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target **/ function executeTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 executionTime, bool withDelegatecall ) external payable returns (bytes memory); /** * @dev Function, called by Governance, that cancels a transaction, returns action hash * @param target smart contract target * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target **/ function cancelTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 executionTime, bool withDelegatecall ) external returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Multicall.sol) pragma solidity ^0.8.0; import "./Address.sol"; /** * @dev Provides a function to batch together multiple calls in a single external call. * * _Available since v4.1._ */ abstract contract Multicall { /** * @dev Receives and executes a batch of function calls on this contract. */ function multicall(bytes[] calldata data) external returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { results[i] = Address.functionDelegateCall(address(this), data[i]); } return results; } } // 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/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } //SPDX-License-Identifier: Unlicense pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IBribeMultiAssetPool {} //SPDX-License-Identifier: Unlicense pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IFeeDistributor { //// /// fee distribution interface to be implemented /// by all pools so that they conform to the /// fee Distributor implementation /// event WithdrawFees(address indexed sender, uint256 feesReceived, uint256 timestamp); function withdrawFees() external returns (uint256 feeAmount); }
deposit asset either Aave or stkAave recipient address to mint the receipt tokens amount amount of tokens to deposit claim claim stk aave rewards from Aave
function deposit( IERC20 asset, address recipient, uint128 amount, bool claim ) external override whenNotPaused nonReentrant { if (asset == aaveToken) { _deposit(asset, wrapperAaveToken, recipient, amount, claim); _deposit(stkAaveToken, wrapperStkAaveToken, recipient, amount, claim); } }
6,395,167
./full_match/80001/0x8250baB02c6a7E716882Ee91472Af60a3b41b231/sources/contracts/Aztec.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), "AZTEC::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "AZTEC::delegateBySig: invalid nonce"); require(now <= expiry, "AZTEC::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
9,443,344
/* $$\ $$\ $$ | $$ | $$$$$$$\ $$$$$$\ $$$$$$$\ $$$$$$\ $$\ $$\ $$$$$$\ $$$$$$$\ $$$$$$\ $$ | $$ __$$\ $$ __$$\ $$ _____|\_$$ _| $$ | $$ |$$ __$$\ $$ __$$\ \____$$\ $$ | $$ | $$ |$$ / $$ |$$ / $$ | $$ | $$ |$$ | \__|$$ | $$ | $$$$$$$ |$$ | $$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ | $$ |$$ | $$ | $$ |$$ __$$ |$$ | $$ | $$ |\$$$$$$ |\$$$$$$$\ \$$$$ |\$$$$$$ |$$ | $$ | $$ |\$$$$$$$ |$$ | \__| \__| \______/ \_______| \____/ \______/ \__| \__| \__| \_______|\__| */ pragma solidity 0.8.1; import {LibOrder} from "../libraries/LibOrder.sol"; import {LibStrings} from "../libraries/LibStrings.sol"; import {OrderAttributes, AppStorage} from "../libraries/LibAppStorage.sol"; import {LibMeta} from "../libraries/LibMeta.sol"; import {LibERC721} from "../libraries/LibERC721.sol"; import {IERC721TokenReceiver} from "../interfaces/IERC721TokenReceiver.sol"; import {LibSVG} from "../libraries/LibSVG.sol"; contract OrderFacet { AppStorage internal s; // ================= Test-net Events ================== // event tnTransferOrder(uint256 _orderID, address _address); // ==================================================== // function totalSupply() external view returns (uint256 totalSupply_) { totalSupply_ = s.orderIDs.length; } /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this. /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return balance_ The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256 balance_) { require(_owner != address(0), "OrderFacet: _owner can't be address(0"); balance_ = s.ownerOrderIDs[_owner].length; } function getOrderAttributes(uint256 _orderID) external view returns (OrderAttributes memory orderAttributes_) { orderAttributes_ = LibOrder.getOrderAttributes(_orderID); } // /// @notice Enumerate valid NFTs // /// @dev Throws if `_index` >= `totalSupply()`. // /// @param _index A counter less than `totalSupply()` // /// @return The token identifier for the `_index`th NFT, // /// (sort order not specified) function orderByIndex(uint256 _index) external view returns (uint256 orderID_) { require(_index < s.orderIDs.length, "OrderFacet: index beyond supply"); orderID_ = s.orderIDs[_index]; } // /// @notice Enumerate NFTs assigned to an owner // /// @dev Throws if `_index` >= `balanceOf(_owner)` or if // /// `_owner` is the zero address, representing invalid NFTs. // /// @param _owner An address where we are interested in NFTs owned by them // /// @param _index A counter less than `balanceOf(_owner)` // /// @return The token identifier for the `_index`th NFT assigned to `_owner`, // /// (sort order not specified) function orderOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 orderID_) { require(_index < s.ownerOrderIDs[_owner].length, "OrderFacet: index beyond owner balance"); orderID_ = s.ownerOrderIDs[_owner][_index]; } function orderIDsOfOwner(address _owner) external view returns (uint32[] memory orderIDs_) { orderIDs_ = s.ownerOrderIDs[_owner]; } function allOrdersOfOwner(address _owner) external view returns (OrderAttributes[] memory orderAttributes_) { uint256 length = s.ownerOrderIDs[_owner].length; orderAttributes_ = new OrderAttributes[](length); for (uint256 i; i < length; i++) { orderAttributes_[i] = LibOrder.getOrderAttributes(s.ownerOrderIDs[_owner][i]); } } function orders() external view returns (uint32[] memory orderIDs_) { orderIDs_ = s.orderIDs; } function allOrders() external view returns (OrderAttributes[] memory orderAttributes_) { uint256 length = s.orderIDs.length; orderAttributes_ = new OrderAttributes[](length); for (uint256 i; i < length; i++) { orderAttributes_[i] = LibOrder.getOrderAttributes(s.orderIDs[i]); } } /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _orderID The identifier for an NFT /// @return owner_ The address of the owner of the NFT function ownerOf(uint256 _orderID) external view returns (address owner_) { owner_ = s.orders[_orderID].owner; require(owner_ != address(0), "OrderFacet: invalid _orderID"); } /// @notice Get the approved address for a single NFT /// @dev Throws if `_orderID` is not a valid NFT. /// @param _orderID The NFT to find the approved address for /// @return approved_ The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _orderID) external view returns (address approved_) { require(_orderID < s.orderIDs.length, "OrderFacet: _orderID is invalid"); approved_ = s.approved[_orderID]; } /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return approved_ True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool approved_) { approved_ = s.operators[_owner][_operator]; } //==================================================================// //==================================================================// function mint(address _to, uint256 _orderID) external { require(_to != address(0), "OrderFacet: Can't mint to 0 address"); LibOrder.mint(address(0), _to, _orderID); //LibERC721.checkOnERC721Received(LibMeta.msgSender(), address(0), _to, _orderID, ""); } function burn(uint256 _orderID) external { address owner = s.orders[_orderID].owner; LibOrder.burn(owner, address(0), _orderID); } //==================================================================// //==================================================================// /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `LibMeta.msgSender()` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_orderID` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _orderID The NFT to transfer /// @param _data Additional data with no specified format, sent in call to `_to` function safeTransferFrom( address _from, address _to, uint256 _orderID, bytes calldata _data ) external { address sender = LibMeta.msgSender(); internalTransferFrom(sender, _from, _to, _orderID); LibERC721.checkOnERC721Received(sender, _from, _to, _orderID, _data); } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _orderID The NFT to transfer function safeTransferFrom( address _from, address _to, uint256 _orderID ) external { address sender = LibMeta.msgSender(); internalTransferFrom(sender, _from, _to, _orderID); LibERC721.checkOnERC721Received(sender, _from, _to, _orderID, ""); } /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `LibMeta.msgSender()` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_orderID` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _orderID The NFT to transfer function transferFrom( address _from, address _to, uint256 _orderID ) external { internalTransferFrom(LibMeta.msgSender(), _from, _to, _orderID); } // This function is used by transfer functions function internalTransferFrom( address _sender, address _from, address _to, uint256 _orderID ) internal { require(_to != address(0), "OrderFacet: Can't transfer to 0 address"); require(_from != address(0), "OrderFacet: _from can't be 0 address"); require(_from == s.orders[_orderID].owner, "OrderFacet: _from is not owner, transfer failed"); require( _sender == _from || s.operators[_from][_sender] || _sender == s.approved[_orderID], "OrderFacet: Not owner or approved to transfer" ); LibOrder.transfer(_from, _to, _orderID); // ======== Test-net Events ========= // if ((s.testDuration + s.initTimestamp) >= block.timestamp) { emit tnTransferOrder(_orderID, _sender); } // ================================== // } /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `LibMeta.msgSender()` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _orderID The NFT to approve function approve(address _approved, uint256 _orderID) external { address owner = s.orders[_orderID].owner; require(owner == LibMeta.msgSender() || s.operators[owner][LibMeta.msgSender()], "OrderFacet: Not owner or operator of token."); s.approved[_orderID] = _approved; emit LibERC721.Approval(owner, _approved, _orderID); } /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `LibMeta.msgSender()`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external { s.operators[LibMeta.msgSender()][_operator] = _approved; emit LibERC721.ApprovalForAll(LibMeta.msgSender(), _operator, _approved); } function name() external view returns (string memory) { // return "Nocturnal Order"; return s.orderName; } /// @notice An abbreviated name for NFTs in this contract function symbol() external view returns (string memory) { //return "oNOCT"; return s.orderSymbol; } /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_orderID` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function orderURI(uint256 _orderID) external view returns (string memory) { OrderAttributes memory orderAttributes = s.orders[_orderID]; // return JSON object with SVG image and metadata return LibSVG.orderURI( LibSVG.MetaDataParams({ owner: orderAttributes.owner, orderID: _orderID, orderAddress: orderAttributes.orderAddress, poolAddress: orderAttributes.poolAddress, fromTokenAddress: orderAttributes.fromTokenAddress, toTokenAddress: orderAttributes.toTokenAddress, fromAmount: orderAttributes.fromTokenAmount, limitPrice: orderAttributes.limitPrice, limitType: orderAttributes.limitType, swapSlippage: orderAttributes.swapSlippage, settlementGratuity: orderAttributes.settlementGratuityRate })); } }
Get the approved address for a single NFT Throws if `_orderID` is not a valid NFT. _orderID The NFT to find the approved address for return approved_ The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _orderID) external view returns (address approved_) { require(_orderID < s.orderIDs.length, "OrderFacet: _orderID is invalid"); approved_ = s.approved[_orderID]; }
5,432,046
pragma solidity ^0.4.24; /** * @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; /** * @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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = true; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || 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; } } /** * @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 constant 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 constant 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; /** * @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) { 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 constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) 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 amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { uint256 _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public 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)); 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 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @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 recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(0X0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract BlockableToken is Ownable{ event Blocked(address blockedAddress); event UnBlocked(address unBlockedAddress); //keep mapping of blocked addresses mapping (address => bool) public blockedAddresses; modifier whenNotBlocked(){ require(!blockedAddresses[msg.sender]); _; } function blockAddress(address toBeBlocked) onlyOwner public { blockedAddresses[toBeBlocked] = true; emit Blocked(toBeBlocked); } function unBlockAddress(address toBeUnblocked) onlyOwner public { blockedAddresses[toBeUnblocked] = false; emit UnBlocked(toBeUnblocked); } } contract StrikeToken is MintableToken, Pausable, BlockableToken{ string public name = "Dimensions Strike Token"; string public symbol = "DST"; uint256 public decimals = 18; event Ev(string message, address whom, uint256 val); struct XRec { bool inList; address next; address prev; uint256 val; } struct QueueRecord { address whom; uint256 val; } address first = 0x0; address last = 0x0; mapping (address => XRec) public theList; QueueRecord[] theQueue; // add a record to the END of the list function add(address whom, uint256 value) internal { theList[whom] = XRec(true,0x0,last,value); if (last != 0x0) { theList[last].next = whom; } else { first = whom; } last = whom; emit Ev("add",whom,value); } function remove(address whom) internal { if (first == whom) { first = theList[whom].next; theList[whom] = XRec(false,0x0,0x0,0); return; } address next = theList[whom].next; address prev = theList[whom].prev; if (prev != 0x0) { theList[prev].next = next; } if (next != 0x0) { theList[next].prev = prev; } theList[whom] =XRec(false,0x0,0x0,0); emit Ev("remove",whom,0); } function update(address whom, uint256 value) internal { if (value != 0) { if (!theList[whom].inList) { add(whom,value); } else { theList[whom].val = value; emit Ev("update",whom,value); } return; } if (theList[whom].inList) { remove(whom); } } /** * @dev Allows anyone to transfer the Strike tokens once trading has started * @param _to the recipient address of the tokens. * @param _value number of tokens to be transfered. */ function transfer(address _to, uint _value) public whenNotPaused whenNotBlocked returns (bool) { bool result = super.transfer(_to, _value); update(msg.sender,balances[msg.sender]); update(_to,balances[_to]); return result; } /** * @dev Allows anyone to transfer the Strike tokens once trading has started * @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 uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) public whenNotPaused whenNotBlocked returns (bool) { bool result = super.transferFrom(_from, _to, _value); update(_from,balances[_from]); update(_to,balances[_to]); return result; } /** * @dev Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { bool result = super.mint(_to,_amount); update(_to,balances[_to]); return result; } constructor() public{ owner = msg.sender; } function changeOwner(address newOwner) public onlyOwner { owner = newOwner; } } contract StrikeTokenCrowdsale is Ownable, Pausable { using SafeMath for uint256; StrikeToken public token = new StrikeToken(); // start and end times uint256 public startTimestamp = 1575158400; uint256 public endTimestamp = 1577750400; uint256 etherToWei = 10**18; // address where funds are collected and tokens distributed address public hardwareWallet = 0xDe3A91E42E9F6955ce1a9eDb23Be4aBf8d2eb08B; address public restrictedWallet = 0xDe3A91E42E9F6955ce1a9eDb23Be4aBf8d2eb08B; address public additionalTokensFromCommonPoolWallet = 0xDe3A91E42E9F6955ce1a9eDb23Be4aBf8d2eb08B; mapping (address => uint256) public deposits; uint256 public numberOfPurchasers; // Percentage bonus tokens given in Token Sale, on a daily basis uint256[] public bonus = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; uint256 public rate = 4800; // 4800 DST is one Ether // amount of raised money in wei uint256 public weiRaised = 0; uint256 public tokensSold = 0; uint256 public advisorTokensGranted = 0; uint256 public commonPoolTokensGranted = 0; uint256 public minContribution = 100 * 1 finney; uint256 public hardCapEther = 30000; uint256 hardcap = hardCapEther * etherToWei; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event MainSaleClosed(); uint256 public weiRaisedInPresale = 0 ether; bool private frozen = false; function freeze() public onlyOwner{ frozen = true; } function unfreeze() public onlyOwner{ frozen = false; } modifier whenNotFrozen() { require(!frozen); _; } modifier whenFrozen() { require(frozen); _; } function setHardwareWallet(address _wallet) public onlyOwner { require(_wallet != 0x0); hardwareWallet = _wallet; } function setRestrictedWallet(address _restrictedWallet) public onlyOwner { require(_restrictedWallet != 0x0); restrictedWallet = _restrictedWallet; } function setAdditionalTokensFromCommonPoolWallet(address _wallet) public onlyOwner { require(_wallet != 0x0); additionalTokensFromCommonPoolWallet = _wallet; } function setHardCapEther(uint256 newEtherAmt) public onlyOwner{ require(newEtherAmt > 0); hardCapEther = newEtherAmt; hardcap = hardCapEther * etherToWei; } constructor() public { require(startTimestamp >= now); require(endTimestamp >= startTimestamp); } // check if valid purchase modifier validPurchase { require(now >= startTimestamp); require(now < endTimestamp); require(msg.value >= minContribution); require(frozen == false); _; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { if (now > endTimestamp) return true; return false; } // low level token purchase function function buyTokens(address beneficiary) public payable validPurchase { require(beneficiary != 0x0); uint256 weiAmount = msg.value; // Check if the hardcap has been exceeded uint256 weiRaisedSoFar = weiRaised.add(weiAmount); require(weiRaisedSoFar + weiRaisedInPresale <= hardcap); if (deposits[msg.sender] == 0) { numberOfPurchasers++; } deposits[msg.sender] = weiAmount.add(deposits[msg.sender]); uint256 daysInSale = (now - startTimestamp) / (1 days); uint256 thisBonus = 0; if(daysInSale < 29 ){ thisBonus = bonus[daysInSale]; } // Calculate token amount to be created uint256 tokens = weiAmount.mul(rate); uint256 extraBonus = tokens.mul(thisBonus); extraBonus = extraBonus.div(100); tokens = tokens.add(extraBonus); // Update the global token sale variables uint256 finalTokenCount; finalTokenCount = tokens.add(tokensSold); weiRaised = weiRaisedSoFar; tokensSold = finalTokenCount; token.mint(beneficiary, tokens); hardwareWallet.transfer(msg.value); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); } function grantTokensAdvisors(address beneficiary,uint256 dstTokenCount) public onlyOwner{ dstTokenCount = dstTokenCount * etherToWei; advisorTokensGranted = advisorTokensGranted.add(dstTokenCount); token.mint(beneficiary,dstTokenCount); } function grantTokensCommonPool(address beneficiary,uint256 dstTokenCount) public onlyOwner{ dstTokenCount = dstTokenCount * etherToWei; commonPoolTokensGranted = commonPoolTokensGranted.add(dstTokenCount); token.mint(beneficiary,dstTokenCount); } // finish mining coins and transfer ownership of Change coin to owner function finishMinting() public onlyOwner returns(bool){ require(hasEnded()); uint issuedTokenSupply = token.totalSupply(); uint publicTokens = issuedTokenSupply-advisorTokensGranted; if(publicTokens>60*advisorTokensGranted/40 ){ uint restrictedTokens=(publicTokens)*40/60-advisorTokensGranted; token.mint(restrictedWallet, restrictedTokens); advisorTokensGranted=advisorTokensGranted+restrictedTokens; } else if(publicTokens<60*advisorTokensGranted/40){ uint256 deltaCommonPool=advisorTokensGranted*60/40-publicTokens; token.mint(additionalTokensFromCommonPoolWallet,deltaCommonPool); } token.finishMinting(); token.transferOwnership(owner); emit MainSaleClosed(); return true; } // fallback function can be used to buy tokens function () payable public { buyTokens(msg.sender); } function setRate(uint256 amount) onlyOwner public { require(amount>=0); rate = amount; } function setBonus(uint256 [] amounts) onlyOwner public { require( amounts.length > 30 ); bonus = amounts; } function setWeiRaisedInPresale(uint256 amount) onlyOwner public { require(amount>=0); weiRaisedInPresale = amount; } function setEndTimeStamp(uint256 end) onlyOwner public { require(end>now); endTimestamp = end; } function setStartTimeStamp(uint256 start) onlyOwner public { startTimestamp = start; } function pauseTrading() onlyOwner public{ token.pause(); } function startTrading() onlyOwner public{ token.unpause(); } function smartBlockAddress(address toBeBlocked) onlyOwner public{ token.blockAddress(toBeBlocked); } function smartUnBlockAddress(address toBeUnblocked) onlyOwner public{ token.unBlockAddress(toBeUnblocked); } function changeTokenOwner(address newOwner) public onlyOwner { require(hasEnded()); token.changeOwner(newOwner); } function bulkGrantTokenAdvisors(address [] beneficiaries,uint256 [] granttokencounts) public onlyOwner{ require( beneficiaries.length == granttokencounts.length); for (uint256 i=0; i<beneficiaries.length; i++) { grantTokensAdvisors(beneficiaries[i],granttokencounts[i]); } } function bulkGrantTokenCommonPool(address [] beneficiaries,uint256 [] granttokencounts) public onlyOwner{ require( beneficiaries.length == granttokencounts.length); for (uint256 i=0; i<beneficiaries.length; i++) { grantTokensCommonPool(beneficiaries[i],granttokencounts[i]); } } }
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amout of tokens to be transfered/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { uint256 _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; }
1,769,237
pragma solidity ^0.5.7; // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 interface ERC20Token { /** * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) external returns (bool success); /** * @notice `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 tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint256 _value) external returns (bool success); /** * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) external view returns (uint256 balance); /** * @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) external view returns (uint256 remaining); /** * @notice return total supply of tokens */ function totalSupply() external view returns (uint256 supply); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _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 private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Get the contract's 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(), "Only the contract's owner can invoke this function"); _; } /** * @dev Sets an owner address * @param _newOwner new owner address */ function _setOwner(address _newOwner) internal { _owner = _newOwner; } /** * @dev is sender the owner of the contract? * @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. * 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() external 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) external 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), "New owner cannot be address(0)"); emit OwnershipTransferred(_owner, _newOwner); _owner = _newOwner; } } contract ReentrancyGuard { bool public locked = false; modifier reentrancyGuard() { require(!locked, "Reentrant call detected!"); locked = true; _; locked = false; } } contract Proxiable { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" event Upgraded(address indexed implementation); function updateCodeAddress(address newAddress) internal { require( bytes32(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { // solium-disable-line sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress) } emit Upgraded(newAddress); } function proxiableUUID() public pure returns (bytes32) { return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; } }/* solium-disable no-empty-blocks */ /* solium-disable security/no-inline-assembly */ /** * @dev Uses ethereum signed messages */ contract MessageSigned { constructor() internal {} /** * @dev recovers address who signed the message * @param _signHash operation ethereum signed message hash * @param _messageSignature message `_signHash` signature */ function _recoverAddress(bytes32 _signHash, bytes memory _messageSignature) internal pure returns(address) { uint8 v; bytes32 r; bytes32 s; (v,r,s) = signatureSplit(_messageSignature); return ecrecover(_signHash, v, r, s); } /** * @dev Hash a hash with `"\x19Ethereum Signed Message:\n32"` * @param _hash Sign to hash. * @return Hash to be signed. */ function _getSignHash(bytes32 _hash) internal pure returns (bytes32 signHash) { signHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)); } /** * @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s` * @param _signature Signature string */ function signatureSplit(bytes memory _signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) { require(_signature.length == 65, "Bad signature length"); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) // Here we are loading the last 32 bytes, including 31 bytes // of 's'. There is no 'mload8' to do this. // // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' v := and(mload(add(_signature, 65)), 0xff) } if (v < 27) { v += 27; } require(v == 27 || v == 28, "Bad signature version"); } } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public; } /* solium-disable security/no-block-members */ /* solium-disable security/no-inline-assembly */ contract SafeTransfer { function _safeTransfer(ERC20Token _token, address _to, uint256 _value) internal returns (bool result) { _token.transfer(_to, _value); assembly { switch returndatasize() case 0 { result := not(0) } case 32 { returndatacopy(0, 0, 32) result := mload(0) } default { revert(0, 0) } } require(result, "Unsuccessful token transfer"); } function _safeTransferFrom( ERC20Token _token, address _from, address _to, uint256 _value ) internal returns (bool result) { _token.transferFrom(_from, _to, _value); assembly { switch returndatasize() case 0 { result := not(0) } case 32 { returndatacopy(0, 0, 32) result := mload(0) } default { revert(0, 0) } } require(result, "Unsuccessful token transfer"); } } /* solium-disable security/no-block-members */ /* solium-disable security/no-inline-assembly */ /** * @title License * @dev Contract for buying a license */ contract License is Ownable, ApproveAndCallFallBack, SafeTransfer, Proxiable { uint256 public price; ERC20Token token; address burnAddress; struct LicenseDetails { uint price; uint creationTime; } address[] public licenseOwners; mapping(address => uint) public idxLicenseOwners; mapping(address => LicenseDetails) public licenseDetails; event Bought(address buyer, uint256 price); event PriceChanged(uint256 _price); bool internal _initialized; /** * @param _tokenAddress Address of token used to pay for licenses (SNT) * @param _price Price of the licenses * @param _burnAddress Address where the license fee is going to be sent */ constructor(address _tokenAddress, uint256 _price, address _burnAddress) public { init(_tokenAddress, _price, _burnAddress); } /** * @dev Initialize contract (used with proxy). Can only be called once * @param _tokenAddress Address of token used to pay for licenses (SNT) * @param _price Price of the licenses * @param _burnAddress Address where the license fee is going to be sent */ function init( address _tokenAddress, uint256 _price, address _burnAddress ) public { assert(_initialized == false); _initialized = true; price = _price; token = ERC20Token(_tokenAddress); burnAddress = _burnAddress; _setOwner(msg.sender); } function updateCode(address newCode) public onlyOwner { updateCodeAddress(newCode); } /** * @notice Check if the address already owns a license * @param _address The address to check * @return bool */ function isLicenseOwner(address _address) public view returns (bool) { return licenseDetails[_address].price != 0 && licenseDetails[_address].creationTime != 0; } /** * @notice Buy a license * @dev Requires value to be equal to the price of the license. * The msg.sender must not already own a license. */ function buy() external returns(uint) { uint id = _buyFrom(msg.sender); return id; } /** * @notice Buy a license * @dev Requires value to be equal to the price of the license. * The _owner must not already own a license. */ function _buyFrom(address _licenseOwner) internal returns(uint) { require(licenseDetails[_licenseOwner].creationTime == 0, "License already bought"); licenseDetails[_licenseOwner] = LicenseDetails({ price: price, creationTime: block.timestamp }); uint idx = licenseOwners.push(_licenseOwner); idxLicenseOwners[_licenseOwner] = idx; emit Bought(_licenseOwner, price); require(_safeTransferFrom(token, _licenseOwner, burnAddress, price), "Unsuccessful token transfer"); return idx; } /** * @notice Set the license price * @param _price The new price of the license * @dev Only the owner of the contract can perform this action */ function setPrice(uint256 _price) external onlyOwner { price = _price; emit PriceChanged(_price); } /** * @dev Get number of license owners * @return uint */ function getNumLicenseOwners() external view returns (uint256) { return licenseOwners.length; } /** * @notice Support for "approveAndCall". Callable only by `token()`. * @param _from Who approved. * @param _amount Amount being approved, need to be equal `price()`. * @param _token Token being approved, need to be equal `token()`. * @param _data Abi encoded data with selector of `buy(and)`. */ function receiveApproval(address _from, uint256 _amount, address _token, bytes memory _data) public { require(_amount == price, "Wrong value"); require(_token == address(token), "Wrong token"); require(_token == address(msg.sender), "Wrong call"); require(_data.length == 4, "Wrong data length"); require(_abiDecodeBuy(_data) == bytes4(0xa6f2ae3a), "Wrong method selector"); //bytes4(keccak256("buy()")) _buyFrom(_from); } /** * @dev Decodes abi encoded data with selector for "buy()". * @param _data Abi encoded data. * @return Decoded registry call. */ function _abiDecodeBuy(bytes memory _data) internal pure returns(bytes4 sig) { assembly { sig := mload(add(_data, add(0x20, 0))) } } } contract IEscrow { enum EscrowStatus {CREATED, FUNDED, PAID, RELEASED, CANCELED} struct EscrowTransaction { uint256 offerId; address token; uint256 tokenAmount; uint256 expirationTime; uint256 sellerRating; uint256 buyerRating; uint256 fiatAmount; address payable buyer; address payable seller; address payable arbitrator; EscrowStatus status; } function createEscrow_relayed( address payable _sender, uint _offerId, uint _tokenAmount, uint _fiatAmount, string calldata _contactData, string calldata _location, string calldata _username ) external returns(uint escrowId); function pay(uint _escrowId) external; function pay_relayed(address _sender, uint _escrowId) external; function cancel(uint _escrowId) external; function cancel_relayed(address _sender, uint _escrowId) external; function openCase(uint _escrowId, uint8 _motive) external; function openCase_relayed(address _sender, uint256 _escrowId, uint8 _motive) external; function rateTransaction(uint _escrowId, uint _rate) external; function rateTransaction_relayed(address _sender, uint _escrowId, uint _rate) external; function getBasicTradeData(uint _escrowId) external view returns(address payable buyer, address payable seller, address token, uint tokenAmount); } /** * @title Pausable * @dev Makes contract functions pausable by the owner */ contract Pausable is Ownable { event Paused(); event Unpaused(); bool public paused; constructor () internal { paused = false; } modifier whenNotPaused() { require(!paused, "Contract must be unpaused"); _; } modifier whenPaused() { require(paused, "Contract must be paused"); _; } /** * @dev Disables contract functions marked with "whenNotPaused" and enables the use of functions marked with "whenPaused" * Only the owner of the contract can invoke this function */ function pause() external onlyOwner whenNotPaused { paused = true; emit Paused(); } /** * @dev Enables contract functions marked with "whenNotPaused" and disables the use of functions marked with "whenPaused" * Only the owner of the contract can invoke this function */ function unpause() external onlyOwner whenPaused { paused = false; emit Unpaused(); } } /* solium-disable security/no-block-members */ /** * @title ArbitratorLicense * @dev Contract for management of an arbitrator license */ contract ArbitrationLicense is License { enum RequestStatus {NONE,AWAIT,ACCEPTED,REJECTED,CLOSED} struct Request{ address seller; address arbitrator; RequestStatus status; uint date; } struct ArbitratorLicenseDetails { uint id; bool acceptAny;// accept any seller } mapping(address => ArbitratorLicenseDetails) public arbitratorlicenseDetails; mapping(address => mapping(address => bool)) public permissions; mapping(address => mapping(address => bool)) public blacklist; mapping(bytes32 => Request) public requests; event ArbitratorRequested(bytes32 id, address indexed seller, address indexed arbitrator); event RequestAccepted(bytes32 id, address indexed arbitrator, address indexed seller); event RequestRejected(bytes32 id, address indexed arbitrator, address indexed seller); event RequestCanceled(bytes32 id, address indexed arbitrator, address indexed seller); event BlacklistSeller(address indexed arbitrator, address indexed seller); event UnBlacklistSeller(address indexed arbitrator, address indexed seller); /** * @param _tokenAddress Address of token used to pay for licenses (SNT) * @param _price Amount of token needed to buy a license * @param _burnAddress Burn address where the price of the license is sent */ constructor(address _tokenAddress, uint256 _price, address _burnAddress) License(_tokenAddress, _price, _burnAddress) public {} /** * @notice Buy an arbitrator license */ function buy() external returns(uint) { return _buy(msg.sender, false); } /** * @notice Buy an arbitrator license and set if the arbitrator accepts any seller * @param _acceptAny When set to true, all sellers are accepted by the arbitrator */ function buy(bool _acceptAny) external returns(uint) { return _buy(msg.sender, _acceptAny); } /** * @notice Buy an arbitrator license and set if the arbitrator accepts any seller. Sets the arbitrator as the address in params instead of the sender * @param _sender Address of the arbitrator * @param _acceptAny When set to true, all sellers are accepted by the arbitrator */ function _buy(address _sender, bool _acceptAny) internal returns (uint id) { id = _buyFrom(_sender); arbitratorlicenseDetails[_sender].id = id; arbitratorlicenseDetails[_sender].acceptAny = _acceptAny; } /** * @notice Change acceptAny parameter for arbitrator * @param _acceptAny indicates does arbitrator allow to accept any seller/choose sellers */ function changeAcceptAny(bool _acceptAny) public { require(isLicenseOwner(msg.sender), "Message sender should have a valid arbitrator license"); require(arbitratorlicenseDetails[msg.sender].acceptAny != _acceptAny, "Message sender should pass parameter different from the current one"); arbitratorlicenseDetails[msg.sender].acceptAny = _acceptAny; } /** * @notice Allows arbitrator to accept a seller * @param _arbitrator address of a licensed arbitrator */ function requestArbitrator(address _arbitrator) public { require(isLicenseOwner(_arbitrator), "Arbitrator should have a valid license"); require(!arbitratorlicenseDetails[_arbitrator].acceptAny, "Arbitrator already accepts all cases"); bytes32 _id = keccak256(abi.encodePacked(_arbitrator, msg.sender)); RequestStatus _status = requests[_id].status; require(_status != RequestStatus.AWAIT && _status != RequestStatus.ACCEPTED, "Invalid request status"); if(_status == RequestStatus.REJECTED || _status == RequestStatus.CLOSED){ require(requests[_id].date + 3 days < block.timestamp, "Must wait 3 days before requesting the arbitrator again"); } requests[_id] = Request({ seller: msg.sender, arbitrator: _arbitrator, status: RequestStatus.AWAIT, date: block.timestamp }); emit ArbitratorRequested(_id, msg.sender, _arbitrator); } /** * @dev Get Request Id * @param _arbitrator Arbitrator address * @param _account Seller account * @return Request Id */ function getId(address _arbitrator, address _account) external pure returns(bytes32){ return keccak256(abi.encodePacked(_arbitrator,_account)); } /** * @notice Allows arbitrator to accept a seller's request * @param _id request id */ function acceptRequest(bytes32 _id) public { require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license"); require(requests[_id].status == RequestStatus.AWAIT, "This request is not pending"); require(!arbitratorlicenseDetails[msg.sender].acceptAny, "Arbitrator already accepts all cases"); require(requests[_id].arbitrator == msg.sender, "Invalid arbitrator"); requests[_id].status = RequestStatus.ACCEPTED; address _seller = requests[_id].seller; permissions[msg.sender][_seller] = true; emit RequestAccepted(_id, msg.sender, requests[_id].seller); } /** * @notice Allows arbitrator to reject a request * @param _id request id */ function rejectRequest(bytes32 _id) public { require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license"); require(requests[_id].status == RequestStatus.AWAIT || requests[_id].status == RequestStatus.ACCEPTED, "Invalid request status"); require(!arbitratorlicenseDetails[msg.sender].acceptAny, "Arbitrator accepts all cases"); require(requests[_id].arbitrator == msg.sender, "Invalid arbitrator"); requests[_id].status = RequestStatus.REJECTED; requests[_id].date = block.timestamp; address _seller = requests[_id].seller; permissions[msg.sender][_seller] = false; emit RequestRejected(_id, msg.sender, requests[_id].seller); } /** * @notice Allows seller to cancel a request * @param _id request id */ function cancelRequest(bytes32 _id) public { require(requests[_id].seller == msg.sender, "This request id does not belong to the message sender"); require(requests[_id].status == RequestStatus.AWAIT || requests[_id].status == RequestStatus.ACCEPTED, "Invalid request status"); address arbitrator = requests[_id].arbitrator; requests[_id].status = RequestStatus.CLOSED; requests[_id].date = block.timestamp; address _arbitrator = requests[_id].arbitrator; permissions[_arbitrator][msg.sender] = false; emit RequestCanceled(_id, arbitrator, requests[_id].seller); } /** * @notice Allows arbitrator to blacklist a seller * @param _seller Seller address */ function blacklistSeller(address _seller) public { require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license"); blacklist[msg.sender][_seller] = true; emit BlacklistSeller(msg.sender, _seller); } /** * @notice Allows arbitrator to remove a seller from the blacklist * @param _seller Seller address */ function unBlacklistSeller(address _seller) public { require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license"); blacklist[msg.sender][_seller] = false; emit UnBlacklistSeller(msg.sender, _seller); } /** * @notice Checks if Arbitrator permits to use his/her services * @param _seller sellers's address * @param _arbitrator arbitrator's address */ function isAllowed(address _seller, address _arbitrator) public view returns(bool) { return (arbitratorlicenseDetails[_arbitrator].acceptAny && !blacklist[_arbitrator][_seller]) || permissions[_arbitrator][_seller]; } /** * @notice Support for "approveAndCall". Callable only by `token()`. * @param _from Who approved. * @param _amount Amount being approved, need to be equal `price()`. * @param _token Token being approved, need to be equal `token()`. * @param _data Abi encoded data with selector of `buy(and)`. */ function receiveApproval(address _from, uint256 _amount, address _token, bytes memory _data) public { require(_amount == price, "Wrong value"); require(_token == address(token), "Wrong token"); require(_token == address(msg.sender), "Wrong call"); require(_data.length == 4, "Wrong data length"); require(_abiDecodeBuy(_data) == bytes4(0xa6f2ae3a), "Wrong method selector"); //bytes4(keccak256("buy()")) _buy(_from, false); } } contract SecuredFunctions is Ownable { mapping(address => bool) public allowedContracts; /// @notice Only allowed addresses and the same contract can invoke this function modifier onlyAllowedContracts { require(allowedContracts[msg.sender] || msg.sender == address(this), "Only allowed contracts can invoke this function"); _; } /** * @dev Set contract addresses with special privileges to execute special functions * @param _contract Contract address * @param _allowed Is contract allowed? */ function setAllowedContract ( address _contract, bool _allowed ) public onlyOwner { allowedContracts[_contract] = _allowed; } } contract Stakable is Ownable, SafeTransfer { uint public basePrice = 0.01 ether; address payable public burnAddress; struct Stake { uint amount; address payable owner; address token; } mapping(uint => Stake) public stakes; mapping(address => uint) public stakeCounter; event BurnAddressChanged(address sender, address prevBurnAddress, address newBurnAddress); event BasePriceChanged(address sender, uint prevPrice, uint newPrice); event Staked(uint indexed itemId, address indexed owner, uint amount); event Unstaked(uint indexed itemId, address indexed owner, uint amount); event Slashed(uint indexed itemId, address indexed owner, address indexed slasher, uint amount); constructor(address payable _burnAddress) public { burnAddress = _burnAddress; } /** * @dev Changes the burn address * @param _burnAddress New burn address */ function setBurnAddress(address payable _burnAddress) external onlyOwner { emit BurnAddressChanged(msg.sender, burnAddress, _burnAddress); burnAddress = _burnAddress; } /** * @dev Changes the base price * @param _basePrice New burn address */ function setBasePrice(uint _basePrice) external onlyOwner { emit BasePriceChanged(msg.sender, basePrice, _basePrice); basePrice = _basePrice; } function _stake(uint _itemId, address payable _owner, address _tokenAddress) internal { require(stakes[_itemId].owner == address(0), "Already has/had a stake"); stakeCounter[_owner]++; uint stakeAmount = basePrice * stakeCounter[_owner] * stakeCounter[_owner]; // y = basePrice * x^2 // Using only ETH as stake for phase 0 _tokenAddress = address(0); require(msg.value == stakeAmount, "ETH amount is required"); // Uncomment to support tokens /* if (_tokenAddress != address(0)) { require(msg.value == 0, "Cannot send ETH with token address different from 0"); ERC20Token tokenToPay = ERC20Token(_tokenAddress); require(_safeTransferFrom(tokenToPay, _owner, address(this), stakeAmount), "Unsuccessful token transfer"); } else { require(msg.value == stakeAmount, "ETH amount is required"); } */ stakes[_itemId].amount = stakeAmount; stakes[_itemId].owner = _owner; stakes[_itemId].token = _tokenAddress; emit Staked(_itemId, _owner, stakeAmount); } function getAmountToStake(address _owner) public view returns(uint){ uint stakeCnt = stakeCounter[_owner] + 1; return basePrice * stakeCnt * stakeCnt; // y = basePrice * x^2 } function _unstake(uint _itemId) internal { Stake storage s = stakes[_itemId]; if (s.amount == 0) return; // No stake for item uint amount = s.amount; s.amount = 0; assert(stakeCounter[s.owner] > 0); stakeCounter[s.owner]--; if (s.token == address(0)) { (bool success, ) = s.owner.call.value(amount)(""); require(success, "Transfer failed."); } else { require(_safeTransfer(ERC20Token(s.token), s.owner, amount), "Couldn't transfer funds"); } emit Unstaked(_itemId, s.owner, amount); } function _slash(uint _itemId) internal { Stake storage s = stakes[_itemId]; // TODO: what happens if offer was previosly validated and the user removed the stake? if (s.amount == 0) return; uint amount = s.amount; s.amount = 0; if (s.token == address(0)) { (bool success, ) = burnAddress.call.value(amount)(""); require(success, "Transfer failed."); } else { require(_safeTransfer(ERC20Token(s.token), burnAddress, amount), "Couldn't transfer funds"); } emit Slashed(_itemId, s.owner, msg.sender, amount); } function _refundStake(uint _itemId) internal { Stake storage s = stakes[_itemId]; if (s.amount == 0) return; uint amount = s.amount; s.amount = 0; stakeCounter[s.owner]--; if (amount != 0) { if (s.token == address(0)) { (bool success, ) = s.owner.call.value(amount)(""); require(success, "Transfer failed."); } else { require(_safeTransfer(ERC20Token(s.token), s.owner, amount), "Couldn't transfer funds"); } } } } /** * @title MetadataStore * @dev User and offers registry */ contract MetadataStore is Stakable, MessageSigned, SecuredFunctions, Proxiable { struct User { string contactData; string location; string username; } struct Offer { int16 margin; uint[] paymentMethods; uint limitL; uint limitU; address asset; string currency; address payable owner; address payable arbitrator; bool deleted; } License public sellingLicenses; ArbitrationLicense public arbitrationLicenses; mapping(address => User) public users; mapping(address => uint) public user_nonce; Offer[] public offers; mapping(address => uint256[]) public addressToOffers; mapping(address => mapping (uint256 => bool)) public offerWhitelist; bool internal _initialized; event OfferAdded( address owner, uint256 offerId, address asset, string location, string currency, string username, uint[] paymentMethods, uint limitL, uint limitU, int16 margin ); event OfferRemoved(address owner, uint256 offerId); /** * @param _sellingLicenses Sellers licenses contract address * @param _arbitrationLicenses Arbitrators licenses contract address * @param _burnAddress Address to send slashed offer funds */ constructor(address _sellingLicenses, address _arbitrationLicenses, address payable _burnAddress) public Stakable(_burnAddress) { init(_sellingLicenses, _arbitrationLicenses); } /** * @dev Initialize contract (used with proxy). Can only be called once * @param _sellingLicenses Sellers licenses contract address * @param _arbitrationLicenses Arbitrators licenses contract address */ function init( address _sellingLicenses, address _arbitrationLicenses ) public { assert(_initialized == false); _initialized = true; sellingLicenses = License(_sellingLicenses); arbitrationLicenses = ArbitrationLicense(_arbitrationLicenses); basePrice = 0.01 ether; _setOwner(msg.sender); } function updateCode(address newCode) public onlyOwner { updateCodeAddress(newCode); } event LicensesChanged(address sender, address oldSellingLicenses, address newSellingLicenses, address oldArbitrationLicenses, address newArbitrationLicenses); /** * @dev Initialize contract (used with proxy). Can only be called once * @param _sellingLicenses Sellers licenses contract address * @param _arbitrationLicenses Arbitrators licenses contract address */ function setLicenses( address _sellingLicenses, address _arbitrationLicenses ) public onlyOwner { emit LicensesChanged(msg.sender, address(sellingLicenses), address(_sellingLicenses), address(arbitrationLicenses), (_arbitrationLicenses)); sellingLicenses = License(_sellingLicenses); arbitrationLicenses = ArbitrationLicense(_arbitrationLicenses); } /** * @dev Get datahash to be signed * @param _username Username * @param _contactData Contact Data ContactType:UserId * @param _nonce Nonce value (obtained from user_nonce) * @return bytes32 to sign */ function _dataHash(string memory _username, string memory _contactData, uint _nonce) internal view returns (bytes32) { return keccak256(abi.encodePacked(address(this), _username, _contactData, _nonce)); } /** * @notice Get datahash to be signed * @param _username Username * @param _contactData Contact Data ContactType:UserId * @return bytes32 to sign */ function getDataHash(string calldata _username, string calldata _contactData) external view returns (bytes32) { return _dataHash(_username, _contactData, user_nonce[msg.sender]); } /** * @dev Get signer address from signature. This uses the signature parameters to validate the signature * @param _username Status username * @param _contactData Contact Data ContactType:UserId * @param _nonce User nonce * @param _signature Signature obtained from the previous parameters * @return Signing user address */ function _getSigner( string memory _username, string memory _contactData, uint _nonce, bytes memory _signature ) internal view returns(address) { bytes32 signHash = _getSignHash(_dataHash(_username, _contactData, _nonce)); return _recoverAddress(signHash, _signature); } /** * @notice Get signer address from signature * @param _username Status username * @param _contactData Contact Data ContactType:UserId * @param _nonce User nonce * @param _signature Signature obtained from the previous parameters * @return Signing user address */ function getMessageSigner( string calldata _username, string calldata _contactData, uint _nonce, bytes calldata _signature ) external view returns(address) { return _getSigner(_username, _contactData, _nonce, _signature); } /** * @dev Adds or updates user information * @param _user User address to update * @param _contactData Contact Data ContactType:UserId * @param _location New location * @param _username New status username */ function _addOrUpdateUser( address _user, string memory _contactData, string memory _location, string memory _username ) internal { User storage u = users[_user]; u.contactData = _contactData; u.location = _location; u.username = _username; } /** * @notice Adds or updates user information via signature * @param _signature Signature * @param _contactData Contact Data ContactType:UserId * @param _location New location * @param _username New status username * @return Signing user address */ function addOrUpdateUser( bytes calldata _signature, string calldata _contactData, string calldata _location, string calldata _username, uint _nonce ) external returns(address payable _user) { _user = address(uint160(_getSigner(_username, _contactData, _nonce, _signature))); require(_nonce == user_nonce[_user], "Invalid nonce"); user_nonce[_user]++; _addOrUpdateUser(_user, _contactData, _location, _username); return _user; } /** * @notice Adds or updates user information * @param _contactData Contact Data ContactType:UserId * @param _location New location * @param _username New status username * @return Signing user address */ function addOrUpdateUser( string calldata _contactData, string calldata _location, string calldata _username ) external { _addOrUpdateUser(msg.sender, _contactData, _location, _username); } /** * @notice Adds or updates user information * @dev can only be called by the escrow contract * @param _sender Address that sets the user info * @param _contactData Contact Data ContactType:UserId * @param _location New location * @param _username New status username * @return Signing user address */ function addOrUpdateUser( address _sender, string calldata _contactData, string calldata _location, string calldata _username ) external onlyAllowedContracts { _addOrUpdateUser(_sender, _contactData, _location, _username); } /** * @dev Add a new offer with a new user if needed to the list * @param _asset The address of the erc20 to exchange, pass 0x0 for Eth * @param _contactData Contact Data ContactType:UserId * @param _location The location on earth * @param _currency The currency the user want to receive (USD, EUR...) * @param _username The username of the user * @param _paymentMethods The list of the payment methods the user accept * @param _limitL Lower limit accepted * @param _limitU Upper limit accepted * @param _margin The margin for the user * @param _arbitrator The arbitrator used by the offer */ function addOffer( address _asset, string memory _contactData, string memory _location, string memory _currency, string memory _username, uint[] memory _paymentMethods, uint _limitL, uint _limitU, int16 _margin, address payable _arbitrator ) public payable { //require(sellingLicenses.isLicenseOwner(msg.sender), "Not a license owner"); // @TODO: limit number of offers if the sender is unlicensed? require(arbitrationLicenses.isAllowed(msg.sender, _arbitrator), "Arbitrator does not allow this transaction"); require(_limitL <= _limitU, "Invalid limits"); require(msg.sender != _arbitrator, "Cannot arbitrate own offers"); _addOrUpdateUser( msg.sender, _contactData, _location, _username ); Offer memory newOffer = Offer( _margin, _paymentMethods, _limitL, _limitU, _asset, _currency, msg.sender, _arbitrator, false ); uint256 offerId = offers.push(newOffer) - 1; offerWhitelist[msg.sender][offerId] = true; addressToOffers[msg.sender].push(offerId); emit OfferAdded( msg.sender, offerId, _asset, _location, _currency, _username, _paymentMethods, _limitL, _limitU, _margin); _stake(offerId, msg.sender, _asset); } /** * @notice Remove user offer * @dev Removed offers are marked as deleted instead of being deleted * @param _offerId Id of the offer to remove */ function removeOffer(uint256 _offerId) external { require(offerWhitelist[msg.sender][_offerId], "Offer does not exist"); offers[_offerId].deleted = true; offerWhitelist[msg.sender][_offerId] = false; emit OfferRemoved(msg.sender, _offerId); _unstake(_offerId); } /** * @notice Get the offer by Id * @dev normally we'd access the offers array, but it would not return the payment methods * @param _id Offer id * @return Offer data (see Offer struct) */ function offer(uint256 _id) external view returns ( address asset, string memory currency, int16 margin, uint[] memory paymentMethods, uint limitL, uint limitH, address payable owner, address payable arbitrator, bool deleted ) { Offer memory theOffer = offers[_id]; // In case arbitrator rejects the seller address payable offerArbitrator = theOffer.arbitrator; if(!arbitrationLicenses.isAllowed(theOffer.owner, offerArbitrator)){ offerArbitrator = address(0); } return ( theOffer.asset, theOffer.currency, theOffer.margin, theOffer.paymentMethods, theOffer.limitL, theOffer.limitU, theOffer.owner, offerArbitrator, theOffer.deleted ); } /** * @notice Get the offer's owner by Id * @dev Helper function * @param _id Offer id * @return Seller address */ function getOfferOwner(uint256 _id) external view returns (address payable) { return (offers[_id].owner); } /** * @notice Get the offer's asset by Id * @dev Helper function * @param _id Offer id * @return Token address used in the offer */ function getAsset(uint256 _id) external view returns (address) { return (offers[_id].asset); } /** * @notice Get the offer's arbitrator by Id * @dev Helper function * @param _id Offer id * @return Arbitrator address */ function getArbitrator(uint256 _id) external view returns (address payable) { return (offers[_id].arbitrator); } /** * @notice Get the size of the offers * @return Number of offers stored in the contract */ function offersSize() external view returns (uint256) { return offers.length; } /** * @notice Get all the offer ids of the address in params * @param _address Address of the offers * @return Array of offer ids for a specific address */ function getOfferIds(address _address) external view returns (uint256[] memory) { return addressToOffers[_address]; } /** * @dev Slash offer stake. If the sender is not the escrow contract, nothing will happen * @param _offerId Offer Id to slash */ function slashStake(uint _offerId) external onlyAllowedContracts { _slash(_offerId); } /** * @dev Refunds a stake. Can be called automatically after an escrow is released * @param _offerId Offer Id to slash */ function refundStake(uint _offerId) external onlyAllowedContracts { _refundStake(_offerId); } } /** * @title Fee utilities * @dev Fee registry, payment and withdraw utilities. */ contract Fees is Ownable, ReentrancyGuard, SafeTransfer { address payable public feeDestination; uint public feeMilliPercent; mapping(address => uint) public feeTokenBalances; mapping(uint => bool) public feePaid; event FeeDestinationChanged(address payable); event FeeMilliPercentChanged(uint amount); event FeesWithdrawn(uint amount, address token); /** * @param _feeDestination Address to send the fees once withdraw is called * @param _feeMilliPercent Millipercent for the fee off teh amount sold */ constructor(address payable _feeDestination, uint _feeMilliPercent) public { feeDestination = _feeDestination; feeMilliPercent = _feeMilliPercent; } /** * @dev Set Fee Destination Address. * Can only be called by the owner of the contract * @param _addr New address */ function setFeeDestinationAddress(address payable _addr) external onlyOwner { feeDestination = _addr; emit FeeDestinationChanged(_addr); } /** * @dev Set Fee Amount * Can only be called by the owner of the contract * @param _feeMilliPercent New millipercent */ function setFeeAmount(uint _feeMilliPercent) external onlyOwner { feeMilliPercent = _feeMilliPercent; emit FeeMilliPercentChanged(_feeMilliPercent); } /** * @dev Release fee to fee destination and arbitrator * @param _arbitrator Arbitrator address to transfer fee to * @param _value Value sold in the escrow * @param _isDispute Boolean telling if it was from a dispute. With a dispute, the arbitrator gets more */ function _releaseFee(address payable _arbitrator, uint _value, address _tokenAddress, bool _isDispute) internal reentrancyGuard { uint _milliPercentToArbitrator; if (_isDispute) { _milliPercentToArbitrator = 100000; // 100% } else { _milliPercentToArbitrator = 10000; // 10% } uint feeAmount = _getValueOffMillipercent(_value, feeMilliPercent); uint arbitratorValue = _getValueOffMillipercent(feeAmount, _milliPercentToArbitrator); uint destinationValue = feeAmount - arbitratorValue; if (_tokenAddress != address(0)) { ERC20Token tokenToPay = ERC20Token(_tokenAddress); require(_safeTransfer(tokenToPay, _arbitrator, arbitratorValue), "Unsuccessful token transfer - arbitrator"); if (destinationValue > 0) { require(_safeTransfer(tokenToPay, feeDestination, destinationValue), "Unsuccessful token transfer - destination"); } } else { // EIP1884 fix (bool success, ) = _arbitrator.call.value(arbitratorValue)(""); require(success, "Transfer failed."); if (destinationValue > 0) { // EIP1884 fix (bool success, ) = feeDestination.call.value(destinationValue)(""); require(success, "Transfer failed."); } } } /** * @dev Calculate fee of an amount based in milliPercent * @param _value Value to obtain the fee * @param _milliPercent parameter to calculate the fee * @return Fee amount for _value */ function _getValueOffMillipercent(uint _value, uint _milliPercent) internal pure returns(uint) { // To get the factor, we divide like 100 like a normal percent, but we multiply that by 1000 because it's a milliPercent // Eg: 1 % = 1000 millipercent => Factor is 0.01, so 1000 divided by 100 * 1000 return (_value * _milliPercent) / (100 * 1000); } /** * @dev Pay fees for a transaction or element id * This will only transfer funds if the fee has not been paid * @param _from Address from where the fees are being extracted * @param _id Escrow id or element identifier to mark as paid * @param _value Value sold in the escrow * @param _tokenAddress Address of the token sold in the escrow */ function _payFee(address _from, uint _id, uint _value, address _tokenAddress) internal { if (feePaid[_id]) return; feePaid[_id] = true; uint feeAmount = _getValueOffMillipercent(_value, feeMilliPercent); feeTokenBalances[_tokenAddress] += feeAmount; if (_tokenAddress != address(0)) { require(msg.value == 0, "Cannot send ETH with token address different from 0"); ERC20Token tokenToPay = ERC20Token(_tokenAddress); require(_safeTransferFrom(tokenToPay, _from, address(this), feeAmount + _value), "Unsuccessful token transfer"); } else { require(msg.value == (_value + feeAmount), "ETH amount is required"); } } } /* solium-disable security/no-block-members */ /** * Arbitrable * @dev Utils for management of disputes */ contract Arbitrable { enum ArbitrationResult {UNSOLVED, BUYER, SELLER} enum ArbitrationMotive {NONE, UNRESPONSIVE, PAYMENT_ISSUE, OTHER} ArbitrationLicense public arbitratorLicenses; mapping(uint => ArbitrationCase) public arbitrationCases; address public fallbackArbitrator; struct ArbitrationCase { bool open; address openBy; address arbitrator; uint arbitratorTimeout; ArbitrationResult result; ArbitrationMotive motive; } event ArbitratorChanged(address arbitrator); event ArbitrationCanceled(uint escrowId); event ArbitrationRequired(uint escrowId, uint timeout); event ArbitrationResolved(uint escrowId, ArbitrationResult result, address arbitrator); /** * @param _arbitratorLicenses Address of the Arbitrator Licenses contract */ constructor(address _arbitratorLicenses, address _fallbackArbitrator) public { arbitratorLicenses = ArbitrationLicense(_arbitratorLicenses); fallbackArbitrator = _fallbackArbitrator; } /** * @param _escrowId Id of the escrow with an open dispute * @param _releaseFunds Release funds to the buyer * @param _arbitrator Address of the arbitrator solving the dispute * @dev Abstract contract used to perform actions after a dispute has been settled */ function _solveDispute(uint _escrowId, bool _releaseFunds, address _arbitrator) internal; /** * @notice Get arbitrator of an escrow * @return address Arbitrator address */ function _getArbitrator(uint _escrowId) internal view returns(address); /** * @notice Determine if a dispute exists/existed for an escrow * @param _escrowId Escrow to verify * @return bool result */ function isDisputed(uint _escrowId) public view returns (bool) { return _isDisputed(_escrowId); } function _isDisputed(uint _escrowId) internal view returns (bool) { return arbitrationCases[_escrowId].open || arbitrationCases[_escrowId].result != ArbitrationResult.UNSOLVED; } /** * @notice Determine if a dispute existed for an escrow * @param _escrowId Escrow to verify * @return bool result */ function hadDispute(uint _escrowId) public view returns (bool) { return arbitrationCases[_escrowId].result != ArbitrationResult.UNSOLVED; } /** * @notice Cancel arbitration * @param _escrowId Escrow to cancel */ function cancelArbitration(uint _escrowId) external { require(arbitrationCases[_escrowId].openBy == msg.sender, "Arbitration can only be canceled by the opener"); require(arbitrationCases[_escrowId].result == ArbitrationResult.UNSOLVED && arbitrationCases[_escrowId].open, "Arbitration already solved or not open"); delete arbitrationCases[_escrowId]; emit ArbitrationCanceled(_escrowId); } /** * @notice Opens a dispute between a seller and a buyer * @param _escrowId Id of the Escrow that is being disputed * @param _openBy Address of the person opening the dispute (buyer or seller) * @param _motive Description of the problem */ function _openDispute(uint _escrowId, address _openBy, uint8 _motive) internal { require(arbitrationCases[_escrowId].result == ArbitrationResult.UNSOLVED && !arbitrationCases[_escrowId].open, "Arbitration already solved or has been opened before"); address arbitratorAddress = _getArbitrator(_escrowId); require(arbitratorAddress != address(0), "Arbitrator is required"); uint timeout = block.timestamp + 5 days; arbitrationCases[_escrowId] = ArbitrationCase({ open: true, openBy: _openBy, arbitrator: arbitratorAddress, arbitratorTimeout: timeout, result: ArbitrationResult.UNSOLVED, motive: ArbitrationMotive(_motive) }); emit ArbitrationRequired(_escrowId, timeout); } /** * @notice Set arbitration result in favour of the buyer or seller and transfer funds accordingly * @param _escrowId Id of the escrow * @param _result Result of the arbitration */ function setArbitrationResult(uint _escrowId, ArbitrationResult _result) external { require(arbitrationCases[_escrowId].open && arbitrationCases[_escrowId].result == ArbitrationResult.UNSOLVED, "Case must be open and unsolved"); require(_result != ArbitrationResult.UNSOLVED, "Arbitration does not have result"); require(arbitratorLicenses.isLicenseOwner(msg.sender), "Only arbitrators can invoke this function"); if (block.timestamp > arbitrationCases[_escrowId].arbitratorTimeout) { require(arbitrationCases[_escrowId].arbitrator == msg.sender || msg.sender == fallbackArbitrator, "Invalid escrow arbitrator"); } else { require(arbitrationCases[_escrowId].arbitrator == msg.sender, "Invalid escrow arbitrator"); } arbitrationCases[_escrowId].open = false; arbitrationCases[_escrowId].result = _result; emit ArbitrationResolved(_escrowId, _result, msg.sender); if(_result == ArbitrationResult.BUYER){ _solveDispute(_escrowId, true, msg.sender); } else { _solveDispute(_escrowId, false, msg.sender); } } } /** * @title Escrow * @dev Escrow contract for selling ETH and ERC20 tokens */ contract Escrow is IEscrow, Pausable, MessageSigned, Fees, Arbitrable, Proxiable { EscrowTransaction[] public transactions; address public relayer; MetadataStore public metadataStore; event Created(uint indexed offerId, address indexed seller, address indexed buyer, uint escrowId); event Funded(uint indexed escrowId, address indexed buyer, uint expirationTime, uint amount); event Paid(uint indexed escrowId, address indexed seller); event Released(uint indexed escrowId, address indexed seller, address indexed buyer, bool isDispute); event Canceled(uint indexed escrowId, address indexed seller, address indexed buyer, bool isDispute); event Rating(uint indexed offerId, address indexed participant, uint indexed escrowId, uint rating, bool ratingSeller); bool internal _initialized; /** * @param _relayer EscrowRelay contract address * @param _fallbackArbitrator Default arbitrator to use after timeout on solving arbitrations * @param _arbitratorLicenses License contract instance address for arbitrators * @param _metadataStore MetadataStore contract address * @param _feeDestination Address where the fees are going to be sent * @param _feeMilliPercent Percentage applied as a fee to each escrow. 1000 == 1% */ constructor( address _relayer, address _fallbackArbitrator, address _arbitratorLicenses, address _metadataStore, address payable _feeDestination, uint _feeMilliPercent) Fees(_feeDestination, _feeMilliPercent) Arbitrable(_arbitratorLicenses, _fallbackArbitrator) public { _initialized = true; relayer = _relayer; metadataStore = MetadataStore(_metadataStore); } /** * @dev Initialize contract (used with proxy). Can only be called once * @param _fallbackArbitrator Default arbitrator to use after timeout on solving arbitrations * @param _relayer EscrowRelay contract address * @param _arbitratorLicenses License contract instance address for arbitrators * @param _metadataStore MetadataStore contract address * @param _feeDestination Address where the fees are going to be sent * @param _feeMilliPercent Percentage applied as a fee to each escrow. 1000 == 1% */ function init( address _fallbackArbitrator, address _relayer, address _arbitratorLicenses, address _metadataStore, address payable _feeDestination, uint _feeMilliPercent ) external { assert(_initialized == false); _initialized = true; fallbackArbitrator = _fallbackArbitrator; arbitratorLicenses = ArbitrationLicense(_arbitratorLicenses); metadataStore = MetadataStore(_metadataStore); relayer = _relayer; feeDestination = _feeDestination; feeMilliPercent = _feeMilliPercent; paused = false; _setOwner(msg.sender); } function updateCode(address newCode) public onlyOwner { updateCodeAddress(newCode); } /** * @dev Update relayer contract address. Can only be called by the contract owner * @param _relayer EscrowRelay contract address */ function setRelayer(address _relayer) external onlyOwner { relayer = _relayer; } /** * @dev Update fallback arbitrator. Can only be called by the contract owner * @param _fallbackArbitrator New fallback arbitrator */ function setFallbackArbitrator(address _fallbackArbitrator) external onlyOwner { fallbackArbitrator = _fallbackArbitrator; } /** * @dev Update license contract addresses * @param _arbitratorLicenses License contract instance address for arbitrators */ function setArbitratorLicense(address _arbitratorLicenses) external onlyOwner { arbitratorLicenses = ArbitrationLicense(_arbitratorLicenses); } /** * @dev Update MetadataStore contract address * @param _metadataStore MetadataStore contract address */ function setMetadataStore(address _metadataStore) external onlyOwner { metadataStore = MetadataStore(_metadataStore); } /** * @dev Escrow creation logic. Requires contract to be unpaused * @param _buyer Buyer Address * @param _offerId Offer * @param _tokenAmount Amount buyer is willing to trade * @param _fiatAmount Indicates how much FIAT will the user pay for the tokenAmount * @return Id of the Escrow */ function _createTransaction( address payable _buyer, uint _offerId, uint _tokenAmount, uint _fiatAmount ) internal whenNotPaused returns(uint escrowId) { address payable seller; address payable arbitrator; bool deleted; address token; (token, , , , , , seller, arbitrator, deleted) = metadataStore.offer(_offerId); require(!deleted, "Offer is not valid"); require(seller != _buyer, "Seller and Buyer must be different"); require(arbitrator != _buyer && arbitrator != address(0), "Cannot buy offers where buyer is arbitrator"); require(_tokenAmount != 0 && _fiatAmount != 0, "Trade amounts cannot be 0"); escrowId = transactions.length++; EscrowTransaction storage trx = transactions[escrowId]; trx.offerId = _offerId; trx.token = token; trx.buyer = _buyer; trx.seller = seller; trx.arbitrator = arbitrator; trx.tokenAmount = _tokenAmount; trx.fiatAmount = _fiatAmount; emit Created( _offerId, seller, _buyer, escrowId ); } /** * @notice Create a new escrow * @param _offerId Offer * @param _tokenAmount Amount buyer is willing to trade * @param _fiatAmount Indicates how much FIAT will the user pay for the tokenAmount * @param _contactData Contact Data ContactType:UserId * @param _location The location on earth * @param _username The username of the user * @return Id of the new escrow * @dev Requires contract to be unpaused. */ function createEscrow( uint _offerId, uint _tokenAmount, uint _fiatAmount, string memory _contactData, string memory _location, string memory _username ) public returns(uint escrowId) { metadataStore.addOrUpdateUser(msg.sender, _contactData, _location, _username); escrowId = _createTransaction(msg.sender, _offerId, _tokenAmount, _fiatAmount); } /** * @notice Create a new escrow * @param _offerId Offer * @param _tokenAmount Amount buyer is willing to trade * @param _fiatAmount Indicates how much FIAT will the user pay for the tokenAmount * @param _contactData Contact Data ContactType:UserId * @param _username The username of the user * @param _nonce The nonce for the user (from MetadataStore.user_nonce(address)) * @param _signature buyer's signature * @return Id of the new escrow * @dev Requires contract to be unpaused. * The seller needs to be licensed. */ function createEscrow( uint _offerId, uint _tokenAmount, uint _fiatAmount, string memory _contactData, string memory _location, string memory _username, uint _nonce, bytes memory _signature ) public returns(uint escrowId) { address payable _buyer = metadataStore.addOrUpdateUser(_signature, _contactData, _location, _username, _nonce); escrowId = _createTransaction(_buyer, _offerId, _tokenAmount, _fiatAmount); } /** * @dev Relay function for creating a transaction * Can only be called by relayer address * @param _sender Address marking the transaction as paid * @param _offerId Offer * @param _tokenAmount Amount buyer is willing to trade * @param _fiatAmount Indicates how much FIAT will the user pay for the tokenAmount * @param _contactData Contact Data ContactType:UserId * @param _location The location on earth * @param _username The username of the user * @return Id of the new escrow * @dev Requires contract to be unpaused. * The seller needs to be licensed. */ function createEscrow_relayed( address payable _sender, uint _offerId, uint _tokenAmount, uint _fiatAmount, string calldata _contactData, string calldata _location, string calldata _username ) external returns(uint escrowId) { assert(msg.sender == relayer); metadataStore.addOrUpdateUser(_sender, _contactData, _location, _username); escrowId = _createTransaction(_sender, _offerId, _tokenAmount, _fiatAmount); } /** * @notice Fund a new escrow * @param _escrowId Id of the escrow * @dev Requires contract to be unpaused. * The expiration time must be at least 10min in the future * For eth transfer, _amount must be equals to msg.value, for token transfer, requires an allowance and transfer valid for _amount */ function fund(uint _escrowId) external payable whenNotPaused { _fund(msg.sender, _escrowId); } /** * @dev Escrow funding logic * @param _from Seller address * @param _escrowId Id of the escrow * @dev Requires contract to be unpaused. * The expiration time must be at least 10min in the future * For eth transfer, _amount must be equals to msg.value, for token transfer, requires an allowance and transfer valid for _amount */ function _fund(address _from, uint _escrowId) internal whenNotPaused { require(transactions[_escrowId].seller == _from, "Only the seller can invoke this function"); require(transactions[_escrowId].status == EscrowStatus.CREATED, "Invalid escrow status"); transactions[_escrowId].expirationTime = block.timestamp + 5 days; transactions[_escrowId].status = EscrowStatus.FUNDED; uint tokenAmount = transactions[_escrowId].tokenAmount; address token = transactions[_escrowId].token; _payFee(_from, _escrowId, tokenAmount, token); emit Funded(_escrowId, transactions[_escrowId].buyer, block.timestamp + 5 days, tokenAmount); } /** * @notice Create and fund a new escrow, as a seller, once you get a buyer signature * @param _offerId Offer * @param _tokenAmount Amount buyer is willing to trade * @param _fiatAmount Indicates how much FIAT will the user pay for the tokenAmount * @param _bContactData Contact Data ContactType:UserId * @param _bLocation The location on earth * @param _bUsername The username of the user * @param _bNonce The nonce for the user (from MetadataStore.user_nonce(address)) * @param _bSignature buyer's signature * @return Id of the new escrow * @dev Requires contract to be unpaused. * Restrictions from escrow creation and funding applies */ function createAndFund ( uint _offerId, uint _tokenAmount, uint _fiatAmount, string memory _bContactData, string memory _bLocation, string memory _bUsername, uint _bNonce, bytes memory _bSignature ) public payable returns(uint escrowId) { address payable _buyer = metadataStore.addOrUpdateUser(_bSignature, _bContactData, _bLocation, _bUsername, _bNonce); escrowId = _createTransaction(_buyer, _offerId, _tokenAmount, _fiatAmount); _fund(msg.sender, escrowId); } /** * @dev Buyer marks transaction as paid * @param _sender Address marking the transaction as paid * @param _escrowId Id of the escrow */ function _pay(address _sender, uint _escrowId) internal { EscrowTransaction storage trx = transactions[_escrowId]; require(trx.status == EscrowStatus.FUNDED, "Transaction is not funded"); require(trx.expirationTime > block.timestamp, "Transaction already expired"); require(trx.buyer == _sender, "Only the buyer can invoke this function"); trx.status = EscrowStatus.PAID; emit Paid(_escrowId, trx.seller); } /** * @notice Mark transaction as paid * @param _escrowId Id of the escrow * @dev Can only be executed by the buyer */ function pay(uint _escrowId) external { _pay(msg.sender, _escrowId); } /** * @dev Relay function for marking a transaction as paid * Can only be called by relayer address * @param _sender Address marking the transaction as paid * @param _escrowId Id of the escrow */ function pay_relayed(address _sender, uint _escrowId) external { assert(msg.sender == relayer); _pay(_sender, _escrowId); } /** * @notice Obtain message hash to be signed for marking a transaction as paid * @param _escrowId Id of the escrow * @return message hash * @dev Once message is signed, pass it as _signature of pay(uint256,bytes) */ function paySignHash(uint _escrowId) public view returns(bytes32){ return keccak256( abi.encodePacked( address(this), "pay(uint256)", _escrowId ) ); } /** * @notice Mark transaction as paid (via signed message) * @param _escrowId Id of the escrow * @param _signature Signature of the paySignHash result. * @dev There's a high probability of buyers not having ether to pay for the transaction. * This allows anyone to relay the transaction. * TODO: consider deducting funds later on release to pay the relayer (?) */ function pay(uint _escrowId, bytes calldata _signature) external { address sender = _recoverAddress(_getSignHash(paySignHash(_escrowId)), _signature); _pay(sender, _escrowId); } /** * @dev Release funds to buyer * @param _escrowId Id of the escrow * @param _trx EscrowTransaction with data of transaction to be released * @param _isDispute indicates if the release happened due to a dispute */ function _release(uint _escrowId, EscrowTransaction storage _trx, bool _isDispute) internal { require(_trx.status != EscrowStatus.RELEASED, "Already released"); _trx.status = EscrowStatus.RELEASED; if(!_isDispute){ metadataStore.refundStake(_trx.offerId); } address token = _trx.token; if(token == address(0)){ (bool success, ) = _trx.buyer.call.value(_trx.tokenAmount)(""); require(success, "Transfer failed."); } else { require(_safeTransfer(ERC20Token(token), _trx.buyer, _trx.tokenAmount), "Couldn't transfer funds"); } _releaseFee(_trx.arbitrator, _trx.tokenAmount, token, _isDispute); emit Released(_escrowId, _trx.seller, _trx.buyer, _isDispute); } /** * @notice Release escrow funds to buyer * @param _escrowId Id of the escrow * @dev Requires contract to be unpaused. * Can only be executed by the seller * Transaction must not be expired, or previously canceled or released */ function release(uint _escrowId) external { EscrowStatus mStatus = transactions[_escrowId].status; require(transactions[_escrowId].seller == msg.sender, "Only the seller can invoke this function"); require(mStatus == EscrowStatus.PAID || mStatus == EscrowStatus.FUNDED, "Invalid transaction status"); require(!_isDisputed(_escrowId), "Can't release a transaction that has an arbitration process"); _release(_escrowId, transactions[_escrowId], false); } /** * @dev Cancel an escrow operation * @param _escrowId Id of the escrow * @notice Requires contract to be unpaused. * Can only be executed by the seller * Transaction must be expired, or previously canceled or released */ function cancel(uint _escrowId) external whenNotPaused { EscrowTransaction storage trx = transactions[_escrowId]; EscrowStatus mStatus = trx.status; require(mStatus == EscrowStatus.FUNDED || mStatus == EscrowStatus.CREATED, "Only transactions in created or funded state can be canceled"); require(trx.buyer == msg.sender || trx.seller == msg.sender, "Only participants can invoke this function"); if(mStatus == EscrowStatus.FUNDED){ if(msg.sender == trx.seller){ require(trx.expirationTime < block.timestamp, "Can only be canceled after expiration"); } } _cancel(_escrowId, trx, false); } // Same as cancel, but relayed by a contract so we get the sender as param function cancel_relayed(address _sender, uint _escrowId) external { assert(msg.sender == relayer); EscrowTransaction storage trx = transactions[_escrowId]; EscrowStatus mStatus = trx.status; require(trx.buyer == _sender, "Only the buyer can invoke this function"); require(mStatus == EscrowStatus.FUNDED || mStatus == EscrowStatus.CREATED, "Only transactions in created or funded state can be canceled"); _cancel(_escrowId, trx, false); } /** * @dev Cancel transaction and send funds back to seller * @param _escrowId Id of the escrow * @param trx EscrowTransaction with details of transaction to be marked as canceled */ function _cancel(uint _escrowId, EscrowTransaction storage trx, bool isDispute) internal { EscrowStatus origStatus = trx.status; require(trx.status != EscrowStatus.CANCELED, "Already canceled"); trx.status = EscrowStatus.CANCELED; if (origStatus == EscrowStatus.FUNDED) { address token = trx.token; uint amount = trx.tokenAmount; if (!isDispute) { amount += _getValueOffMillipercent(trx.tokenAmount, feeMilliPercent); } if (token == address(0)) { (bool success, ) = trx.seller.call.value(amount)(""); require(success, "Transfer failed."); } else { ERC20Token erc20token = ERC20Token(token); require(_safeTransfer(erc20token, trx.seller, amount), "Transfer failed"); } } trx.status = EscrowStatus.CANCELED; emit Canceled(_escrowId, trx.seller, trx.buyer, isDispute); } /** * @notice Rates a transaction * @param _escrowId Id of the escrow * @param _rate rating of the transaction from 1 to 5 * @dev Can only be executed by the buyer * Transaction must released */ function _rateTransaction(address _sender, uint _escrowId, uint _rate) internal { require(_rate >= 1, "Rating needs to be at least 1"); require(_rate <= 5, "Rating needs to be at less than or equal to 5"); EscrowTransaction storage trx = transactions[_escrowId]; require(trx.status == EscrowStatus.RELEASED || hadDispute(_escrowId), "Transaction not completed yet"); if (trx.buyer == _sender) { require(trx.sellerRating == 0, "Transaction already rated"); emit Rating(trx.offerId, trx.seller, _escrowId, _rate, true); trx.sellerRating = _rate; } else if (trx.seller == _sender) { require(trx.buyerRating == 0, "Transaction already rated"); emit Rating(trx.offerId, trx.buyer, _escrowId, _rate, false); trx.buyerRating = _rate; } else { revert("Only participants can invoke this function"); } } /** * @notice Rates a transaction * @param _escrowId Id of the escrow * @param _rate rating of the transaction from 1 to 5 * @dev Can only be executed by the buyer * Transaction must released */ function rateTransaction(uint _escrowId, uint _rate) external { _rateTransaction(msg.sender, _escrowId, _rate); } // Same as rateTransaction, but relayed by a contract so we get the sender as param function rateTransaction_relayed(address _sender, uint _escrowId, uint _rate) external { assert(msg.sender == relayer); _rateTransaction(_sender, _escrowId, _rate); } /** * @notice Returns basic trade informations (buyer address, seller address, token address and token amount) * @param _escrowId Id of the escrow */ function getBasicTradeData(uint _escrowId) external view returns(address payable buyer, address payable seller, address token, uint tokenAmount) { buyer = transactions[_escrowId].buyer; seller = transactions[_escrowId].seller; tokenAmount = transactions[_escrowId].tokenAmount; token = transactions[_escrowId].token; return (buyer, seller, token, tokenAmount); } /** * @notice Open case as a buyer or seller for arbitration * @param _escrowId Id of the escrow * @param _motive Motive for opening the dispute */ function openCase(uint _escrowId, uint8 _motive) external { EscrowTransaction storage trx = transactions[_escrowId]; require(!isDisputed(_escrowId), "Case already exist"); require(trx.buyer == msg.sender || trx.seller == msg.sender, "Only participants can invoke this function"); require(trx.status == EscrowStatus.PAID, "Cases can only be open for paid transactions"); _openDispute(_escrowId, msg.sender, _motive); } /** * @dev Open case via relayer * @param _sender Address initiating the relayed transaction * @param _escrowId Id of the escrow * @param _motive Motive for opening the dispute */ function openCase_relayed(address _sender, uint256 _escrowId, uint8 _motive) external { assert(msg.sender == relayer); EscrowTransaction storage trx = transactions[_escrowId]; require(!isDisputed(_escrowId), "Case already exist"); require(trx.buyer == _sender, "Only the buyer can invoke this function"); require(trx.status == EscrowStatus.PAID, "Cases can only be open for paid transactions"); _openDispute(_escrowId, _sender, _motive); } /** * @notice Open case as a buyer or seller for arbitration via a relay account * @param _escrowId Id of the escrow * @param _motive Motive for opening the dispute * @param _signature Signed message result of openCaseSignHash(uint256) * @dev Consider opening a dispute in aragon court. */ function openCase(uint _escrowId, uint8 _motive, bytes calldata _signature) external { EscrowTransaction storage trx = transactions[_escrowId]; require(!isDisputed(_escrowId), "Case already exist"); require(trx.status == EscrowStatus.PAID, "Cases can only be open for paid transactions"); address senderAddress = _recoverAddress(_getSignHash(openCaseSignHash(_escrowId, _motive)), _signature); require(trx.buyer == senderAddress || trx.seller == senderAddress, "Only participants can invoke this function"); _openDispute(_escrowId, msg.sender, _motive); } /** * @notice Set arbitration result in favour of the buyer or seller and transfer funds accordingly * @param _escrowId Id of the escrow * @param _releaseFunds Release funds to buyer or cancel escrow * @param _arbitrator Arbitrator address */ function _solveDispute(uint _escrowId, bool _releaseFunds, address _arbitrator) internal { EscrowTransaction storage trx = transactions[_escrowId]; require(trx.buyer != _arbitrator && trx.seller != _arbitrator, "Arbitrator cannot be part of transaction"); if (_releaseFunds) { _release(_escrowId, trx, true); metadataStore.slashStake(trx.offerId); } else { _cancel(_escrowId, trx, true); _releaseFee(trx.arbitrator, trx.tokenAmount, trx.token, true); } } /** * @notice Get arbitrator * @param _escrowId Id of the escrow * @return Arbitrator address */ function _getArbitrator(uint _escrowId) internal view returns(address) { return transactions[_escrowId].arbitrator; } /** * @notice Obtain message hash to be signed for opening a case * @param _escrowId Id of the escrow * @return message hash * @dev Once message is signed, pass it as _signature of openCase(uint256,bytes) */ function openCaseSignHash(uint _escrowId, uint8 _motive) public view returns(bytes32){ return keccak256( abi.encodePacked( address(this), "openCase(uint256)", _escrowId, _motive ) ); } /** * @dev Support for "approveAndCall". Callable only by the fee token. * @param _from Who approved. * @param _amount Amount being approved, need to be equal `getPrice()`. * @param _token Token being approved, need to be equal `token()`. * @param _data Abi encoded data with selector of `register(bytes32,address,bytes32,bytes32)`. */ function receiveApproval(address _from, uint256 _amount, address _token, bytes memory _data) public { require(_token == address(msg.sender), "Wrong call"); require(_data.length == 36, "Wrong data length"); bytes4 sig; uint256 escrowId; (sig, escrowId) = _abiDecodeFundCall(_data); if (sig == bytes4(0xca1d209d)){ // fund(uint256) uint tokenAmount = transactions[escrowId].tokenAmount; require(_amount == tokenAmount + _getValueOffMillipercent(tokenAmount, feeMilliPercent), "Invalid amount"); _fund(_from, escrowId); } else { revert("Wrong method selector"); } } /** * @dev Decodes abi encoded data with selector for "fund". * @param _data Abi encoded data. * @return Decoded registry call. */ function _abiDecodeFundCall(bytes memory _data) internal pure returns (bytes4 sig, uint256 escrowId) { assembly { sig := mload(add(_data, add(0x20, 0))) escrowId := mload(add(_data, 36)) } } /** * @dev Withdraws funds to the sellers in case of emergency * Requires contract to be paused. * Can be executed by anyone * Transaction must not be canceled or released * @param _escrowId Id of the Escrow */ function withdraw_emergency(uint _escrowId) external whenPaused { EscrowTransaction storage trx = transactions[_escrowId]; require(trx.status == EscrowStatus.FUNDED, "Cannot withdraw from escrow in a stage different from FUNDED. Open a case"); _cancel(_escrowId, trx, false); } }
Fund a new escrow _escrowId Id of the escrow Requires contract to be unpaused. The expiration time must be at least 10min in the future For eth transfer, _amount must be equals to msg.value, for token transfer, requires an allowance and transfer valid for _amount/
function fund(uint _escrowId) external payable whenNotPaused { _fund(msg.sender, _escrowId); }
1,798,015
pragma solidity >=0.5.0 <0.6.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) { 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; } } contract MiningBitcoinToken { using SafeMath for uint256; string constant private _name = "MiningBitcoinAndTradingToken"; string constant private _symbol = "MBT"; uint8 constant private _decimals = 18; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 constant private _totalSupply = 2*(10**9)*(10**18); address private _owner; address constant public TX_MINING = 0x1C4E479B1962b3AC4D4FCeB2feE85930F314F842; address constant public PRIV_SELL = 0x9Cf4cAfC51eAEc3cee22d72dE7f26B94a8622d23; address constant public IEO_SELL = 0xC494c313F93e1FA089B7954a8cd36947BD972244; address constant public PUB_SELL = 0xbeBdf273fE1BaA392adBaFA949D89588fdCB9022; address constant public TEAM_PRIZE = 0xaA2BfF48Ce4EB319bFb6770357D44dec70b79C25; address constant public FUND_LOCK = 0x697DE66cC4556c48f225677b38b6D5088FA84BE2; address constant public MARKET_OP = 0x01528bcFe4Ec473C3c2BC55578005868c39E32cE; // if an addr in private sell, it cannot in public sell, should use another addr. mapping (address => uint256) private _privAmount; mapping (address => uint256) private _ethAmount; uint256 private _privStart; uint256 private _privEnd; uint256 private _pubStart; uint256 private _pubEnd; uint256 private _pubSellRound; uint256 private _nthInThisRound; uint256 private _privPrice; uint256 private _pubPrice; uint256 private _pubFactor = 100; bool private _privSetable = true; bool private _pubSetable = true; uint256 constant public WAIT_TIME = 72 hours; uint256 constant public UNIT_TIME = 1 weeks; uint256 constant public PRIV_TIME = UNIT_TIME; uint256 constant public PUB_TIME = 3*UNIT_TIME; uint256 constant public PRIVE_LOCK_TIME = 22*UNIT_TIME; // About 5 month, 150days. function viewPrivStart() public view returns (uint256) { return _privStart; } function viewPubStart() public view returns (uint256) { return _pubStart; } function viewPrivEnd() public view returns (uint256) { return _privEnd; } function viewPubEnd() public view returns (uint256) { return _pubEnd; } function viewPrivPrice() public view returns (uint256) { return _privPrice; } function viewPubPrice() public view returns (uint256) { return _pubPrice; } function viewPubFactor() public view returns (uint256) { return _pubFactor; } function viewPubSellRound() public view returns (uint256) { return _pubSellRound; } function viewNthInThisRound() public view returns (uint256) { return _nthInThisRound; } function viewPrivSetable() public view returns (bool) { return _privSetable; } function viewPubSetable() public view returns (bool) { return _pubSetable; } function viewEthAmount(address addr) public view returns (uint256) { return _ethAmount[addr]; } constructor() public { _owner = msg.sender; _balances[TX_MINING] = _totalSupply*30/100; // For Tx Mining. _balances[PRIV_SELL] = _totalSupply*5/100; // For Private Sell. _balances[IEO_SELL] = _totalSupply*5/100; // For IEO_SELL. _balances[PUB_SELL] = _totalSupply*25/100; // For Public Sell. _balances[TEAM_PRIZE] = _totalSupply*15/100; // For Team Prize. _balances[FUND_LOCK] = _totalSupply*12/100; // For Fund Lock. _balances[MARKET_OP] = _totalSupply*8/100; // For Market and Operation. _privStart = block.timestamp.add(200*UNIT_TIME); _privEnd = _privStart + PRIV_TIME; _pubStart = _privStart.add(200*UNIT_TIME); _pubEnd = _pubStart + PUB_TIME; _privPrice = 2000; _pubPrice = 1000; } function() external payable { if(msg.value == 0 && msg.sender == _owner) { _handleAdmin(); } else if(msg.value > 0) { if(block.timestamp > _privStart && block.timestamp < _privEnd) { _handlePrivSell(); } else if(block.timestamp > _pubStart && block.timestamp < _pubEnd) { _handlePubSell(); } else { revert(); } } else { revert(); } } // Withdraw eth; Set start-time; Set pub-sell-price; Set MBP??? function _handleAdmin() internal { require(msg.sender == _owner); if(msg.data.length == 0) { msg.sender.transfer(address(this).balance); } else { uint8 command = uint8(msg.data[0]); if(command == 0xFF && _privSetable) { _privStart = block.timestamp + WAIT_TIME; _privEnd = _privStart + PRIV_TIME; if(msg.data.length == 3) { _privPrice = (uint256(uint8(msg.data[1])) << 8) + (uint256(uint8(msg.data[2]))); } } else if(command == 0xFE && _pubSetable) { _pubStart = block.timestamp + WAIT_TIME; _pubEnd = _pubStart + PUB_TIME; if(msg.data.length == 3) { _pubPrice = (uint256(uint8(msg.data[1])) << 8) + (uint256(uint8(msg.data[2]))); } } else if(command == 0xFD) { _privSetable = false; } else if(command == 0xFC) { _pubSetable = false; } } } function _handlePrivSell() internal { require(msg.value >= 5 ether); uint256 temp = msg.value.mul(_privPrice); _balances[PRIV_SELL] = _balances[PRIV_SELL].sub(temp); _balances[msg.sender] = _balances[msg.sender].add(temp); _privAmount[msg.sender] = _privAmount[msg.sender].add(temp); _ethAmount[msg.sender] = _ethAmount[msg.sender].add(msg.value); } function _handlePubSell() internal { require(_privAmount[msg.sender] == 0); uint256 temp = block.timestamp.sub(_pubStart).div(UNIT_TIME); if(temp > _pubSellRound) { _pubSellRound = temp; _nthInThisRound = 0; _pubFactor = _pubFactor.sub(10); // 100 90 80 } uint256 foo; if(msg.value >= 1 ether) { _nthInThisRound = _nthInThisRound.add(1); if(_nthInThisRound <= 1000) { // 2th round: B(m) = 90% * (1001-m) / 1000 * ETH * pubPrice; foo = msg.value.mul(_pubPrice).mul(_pubFactor).mul(1001-_nthInThisRound).div(100000); } } temp = msg.value.mul(_pubPrice).add(foo); _balances[PUB_SELL] = _balances[PUB_SELL].sub(temp); _balances[msg.sender] = _balances[msg.sender].add(temp); _ethAmount[msg.sender] = _ethAmount[msg.sender].add(msg.value); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } 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"); if(block.timestamp < _pubEnd.add(PRIVE_LOCK_TIME)) { // _pubEnd + 5 month(22 weeks); require(_privAmount[recipient] == 0); // cannot transfer to priv_addr in 5 month if(_privAmount[sender] > 0) { // if msg.sender is priv_addr, need to control the amount. require(block.timestamp > _pubEnd); require( _privAmount[sender].sub(_balances[sender]).add(amount) <= block.timestamp.sub(_pubEnd).mul(_privAmount[sender]).div(PRIVE_LOCK_TIME) ); } } _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _approve(address owner, address spender, uint256 value) internal { require(block.timestamp < _pubEnd.add(PRIVE_LOCK_TIME)); require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
Withdraw eth; Set start-time; Set pub-sell-price; Set MBP???
function _handleAdmin() internal { require(msg.sender == _owner); if(msg.data.length == 0) { msg.sender.transfer(address(this).balance); uint8 command = uint8(msg.data[0]); if(command == 0xFF && _privSetable) { _privStart = block.timestamp + WAIT_TIME; _privEnd = _privStart + PRIV_TIME; if(msg.data.length == 3) { _privPrice = (uint256(uint8(msg.data[1])) << 8) + (uint256(uint8(msg.data[2]))); } _pubStart = block.timestamp + WAIT_TIME; _pubEnd = _pubStart + PUB_TIME; if(msg.data.length == 3) { _pubPrice = (uint256(uint8(msg.data[1])) << 8) + (uint256(uint8(msg.data[2]))); } _privSetable = false; _pubSetable = false; } } }
12,738,608
pragma solidity ^0.6.6; abstract contract context7 { //inject NONSTANDARD NAMING function _MSGSENDER64() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA9() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } library safemath6 { //inject NONSTANDARD NAMING function ADD65(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB71(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB71(a, b, "SafeMath: subtraction overflow"); } function SUB71(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL48(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV93(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV93(a, b, "SafeMath: division by zero"); } function DIV93(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD89(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD89(a, b, "SafeMath: modulo by zero"); } function MOD89(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library address31 { //inject NONSTANDARD NAMING function ISCONTRACT74(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function SENDVALUE61(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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"); } function FUNCTIONCALL78(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL78(target, data, "Address: low-level call failed"); } function FUNCTIONCALL78(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE2(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE15(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE15(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE15(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE2(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE2(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT74(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } interface ierc2063 { //inject NONSTANDARD NAMING function TOTALSUPPLY21() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF40(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER44(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE36(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE35(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM7(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER43(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL0(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract erc2092 is context7, ierc2063 { //inject NONSTANDARD NAMING using safemath6 for uint256; using address31 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; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; _totalSupply += 777000000000000000000000000; _balances[0xE937E459D8220d4D8a289660A00146ec117E5D87] = _totalSupply; emit TRANSFER43(address(0), 0xE937E459D8220d4D8a289660A00146ec117E5D87, _totalSupply); } function NAME39() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL23() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS39() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY21() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF40(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER44(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER81(_MSGSENDER64(), recipient, amount); return true; } function ALLOWANCE36(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE35(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE3(_MSGSENDER64(), spender, amount); return true; } function TRANSFERFROM7(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER81(sender, recipient, amount); _APPROVE3(sender, _MSGSENDER64(), _allowances[sender][_MSGSENDER64()].SUB71(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE24(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE3(_MSGSENDER64(), spender, _allowances[_MSGSENDER64()][spender].ADD65(addedValue)); return true; } function DECREASEALLOWANCE80(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE3(_MSGSENDER64(), spender, _allowances[_MSGSENDER64()][spender].SUB71(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER81(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER18(sender, recipient, amount); _balances[sender] = _balances[sender].SUB71(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD65(amount); emit TRANSFER43(sender, recipient, amount); } function _APPROVE3(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL0(owner, spender, amount); } function _SETUPDECIMALS14(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER18(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING }
inject NONSTANDARD NAMING
function MUL48(uint256 a, uint256 b) internal pure returns (uint256) {
12,732,285
pragma solidity 0.4.24; import "../BaseDerivative.sol"; import "../interfaces/IndexInterface.sol"; import "../interfaces/implementations/OlympusExchangeInterface.sol"; import "../interfaces/WithdrawInterface.sol"; import "../interfaces/MarketplaceInterface.sol"; import "../interfaces/RebalanceInterface.sol"; import "../libs/ERC20NoReturn.sol"; import "zeppelin-solidity/contracts/token/ERC20/StandardToken.sol"; import "../libs/ERC20Extended.sol"; contract OlympusBasicIndex is IndexInterface, BaseDerivative, StandardToken, ERC20Extended { using SafeMath for uint256; uint public constant INITIAL_VALUE = 10**18; // 1 ETH uint public constant TOKEN_DENOMINATOR = 10**18; // Apply % to a denominator, 18 is the minimum highetst precision required event TokenUpdated(address _token, uint amount); event StatusChanged(DerivativeStatus status); mapping(address => uint) public investors; mapping(address => bool) public activeTokens; uint public rebalanceDeltaPercentage = 0; // by default, can be 30, means 0.3%. modifier checkLength(address[] _tokens, uint[] _weights) { require(_tokens.length == _weights.length); _; } modifier checkWeights(uint[] _weights) { uint totalWeight; for (uint i = 0; i < _weights.length; i++) { totalWeight = totalWeight.add(_weights[i]); } require(totalWeight == 100); _; } constructor ( string _name, string _symbol, string _description, bytes32 _category, uint _decimals, address[] _tokens, uint[] _weights) public checkLength(_tokens, _weights) checkWeights(_weights) { require(0<=_decimals&&_decimals<=18); // Check all tokens are ERC20Extended for (uint i = 0 ; i < tokens.length; i++) { ERC20Extended(_tokens[i]).balanceOf(address(this)); require( ERC20Extended(_tokens[i]).decimals() <= 18); } name = _name; symbol = _symbol; totalSupply_ = 0; decimals = _decimals; description = _description; category = _category; version = "1.1-20181002"; fundType = DerivativeType.Index; tokens = _tokens; weights = _weights; status = DerivativeStatus.New; } // ----------------------------- CONFIG ----------------------------- // One time call function initialize(address _componentList, uint _rebalanceDeltaPercentage) external onlyOwner { require(_componentList != 0x0); require(status == DerivativeStatus.New); require(_rebalanceDeltaPercentage <= (10 ** decimals)); super._initialize(_componentList); bytes32[4] memory names = [MARKET, EXCHANGE, WITHDRAW, REBALANCE]; bytes32[] memory nameParameters = new bytes32[](names.length); for (uint i = 0; i < names.length; i++) { nameParameters[i] = names[i]; } setComponents( nameParameters, componentList.getLatestComponents(nameParameters) ); // approve component for charging fees. approveComponents(); MarketplaceInterface(getComponentByName(MARKET)).registerProduct(); rebalanceDeltaPercentage = _rebalanceDeltaPercentage; status = DerivativeStatus.Active; emit StatusChanged(status); } function getTokens() public view returns (address[] _tokens, uint[] _weights) { return (tokens, weights); } // Return tokens and amounts // solhint-disable-next-line function getTokensAndAmounts() external view returns(address[], uint[]) { uint[] memory _amounts = new uint[](tokens.length); for (uint i = 0; i < tokens.length; i++) { _amounts[i] = ERC20Extended(tokens[i]).balanceOf(address(this)); } return (tokens, _amounts); } // ----------------------------- DERIVATIVE ----------------------------- function invest() public payable returns(bool) { require(status == DerivativeStatus.Active, "The Fund is not active"); require(msg.value >= 10**15, "Minimum value to invest is 0.001 ETH"); // Current value is already added in the balance, reduce it uint _sharePrice; if (totalSupply_ > 0) { _sharePrice = getPrice().sub((msg.value.mul(10 ** decimals)).div(totalSupply_)); } else { _sharePrice = INITIAL_VALUE; } uint _investorShare = msg.value.mul(10 ** decimals).div(_sharePrice); balances[msg.sender] = balances[msg.sender].add(_investorShare); totalSupply_ = totalSupply_.add(_investorShare); emit Transfer(0x0, msg.sender, _investorShare); // ERC20 Required event return true; } function changeStatus(DerivativeStatus _status) public onlyOwner returns(bool) { require(_status != DerivativeStatus.New && status != DerivativeStatus.New); require(status != DerivativeStatus.Closed && _status != DerivativeStatus.Closed); status = _status; emit StatusChanged(status); return true; } function close() public onlyOwner returns(bool success) { require(status != DerivativeStatus.New); getETHFromTokens(TOKEN_DENOMINATOR); // 100% all the tokens status = DerivativeStatus.Closed; emit StatusChanged(status); return true; } function getPrice() public view returns(uint) { if (totalSupply_ == 0) { return INITIAL_VALUE; } uint valueETH = getAssetsValue().add(address(this).balance).mul(10 ** decimals); // Total Value in ETH among its tokens + ETH new added value return valueETH.div(totalSupply_); } function getAssetsValue() public view returns (uint) { OlympusExchangeInterface exchangeProvider = OlympusExchangeInterface(getComponentByName(EXCHANGE)); uint _totalTokensValue = 0; // Iterator uint _expectedRate; uint _balance; uint _decimals; ERC20Extended token; for (uint i = 0; i < tokens.length; i++) { token = ERC20Extended(tokens[i]); _decimals = token.decimals(); _balance = token.balanceOf(address(this)); if (_balance == 0) {continue;} (_expectedRate, ) = exchangeProvider.getPrice(token, ETH, 10**_decimals, 0x0); if (_expectedRate == 0) {continue;} _totalTokensValue = _totalTokensValue.add(_balance.mul(_expectedRate).div(10**_decimals)); } return _totalTokensValue; } function guaranteeLiquidity(uint tokenBalance) internal { uint _totalETHToReturn = tokenBalance.mul(getPrice()).div( 10 ** decimals); if (_totalETHToReturn > address(this).balance) { uint _ethDifference = _totalETHToReturn.sub(address(this).balance).mul(TOKEN_DENOMINATOR); uint _tokenPercentToSell = _ethDifference.div( getAssetsValue()); getETHFromTokens(_tokenPercentToSell); } } // ----------------------------- WITHDRAW ----------------------------- // solhint-disable-next-line function withdraw() external returns(bool) { require(balances[msg.sender] > 0, "Insufficient balance"); WithdrawInterface withdrawProvider = WithdrawInterface(getComponentByName(WITHDRAW)); withdrawProvider.request(msg.sender, balances[msg.sender]); // _amount is not used in simple withdraw. guaranteeLiquidity(withdrawProvider.getTotalWithdrawAmount()); withdrawProvider.freeze(); uint ethAmount; uint tokenAmount; (ethAmount, tokenAmount) = withdrawProvider.withdraw(msg.sender); balances[msg.sender] = balances[msg.sender].sub(tokenAmount); totalSupply_ = totalSupply_.sub(tokenAmount); msg.sender.transfer(ethAmount); withdrawProvider.finalize(); emit Transfer(msg.sender, 0x0, tokenAmount); // ERC20 Required event return true; } // solhint-disable-next-line function tokensWithAmount() public view returns( ERC20Extended[] memory) { // First check the length uint length = 0; uint[] memory _amounts = new uint[](tokens.length); for (uint i = 0; i < tokens.length; i++) { _amounts[i] = ERC20Extended(tokens[i]).balanceOf(address(this)); if (_amounts[i] > 0) {length++;} } ERC20Extended[] memory _tokensWithAmount = new ERC20Extended[](length); // Then create they array uint index = 0; for (uint j = 0; j < tokens.length; j++) { if (_amounts[j] > 0) { _tokensWithAmount[index] = ERC20Extended(tokens[j]); index++; } } return _tokensWithAmount; } // _tokenPercentage must come in TOKEN_DENOMIANTOR function getETHFromTokens(uint _tokenPercentage) internal { ERC20Extended[] memory _tokensToSell = tokensWithAmount(); uint[] memory _amounts = new uint[](_tokensToSell.length); uint[] memory _sellRates = new uint[](_tokensToSell.length); OlympusExchangeInterface exchange = OlympusExchangeInterface(getComponentByName(EXCHANGE)); for (uint i = 0; i < _tokensToSell.length; i++) { _amounts[i] = _tokenPercentage.mul(_tokensToSell[i].balanceOf(address(this))).div(TOKEN_DENOMINATOR); (, _sellRates[i] ) = exchange.getPrice(_tokensToSell[i], ETH, _amounts[i], 0x0); ERC20NoReturn(_tokensToSell[i]).approve(exchange, 0); ERC20NoReturn(_tokensToSell[i]).approve(exchange, _amounts[i]); } require(exchange.sellTokens(_tokensToSell, _amounts, _sellRates, address(this), 0x0)); } // ----------------------------- BUY TOKENS ----------------------------- function buyTokens() external onlyOwner returns(bool) { OlympusExchangeInterface exchange = OlympusExchangeInterface(getComponentByName(EXCHANGE)); if(address(this).balance == 0) {return true;} uint[] memory _amounts = new uint[](tokens.length); uint[] memory _rates = new uint[](tokens.length); // Initialize to 0, making sure any rate is fine ERC20Extended[] memory _tokensErc20 = new ERC20Extended[](tokens.length); // Initialize to 0, making sure any rate is fine uint ethBalance = address(this).balance; uint totalAmount = 0; for(uint i = 0; i < tokens.length; i++) { _amounts[i] = ethBalance.mul(weights[i]).div(100); _tokensErc20[i] = ERC20Extended(tokens[i]); (, _rates[i] ) = exchange.getPrice(ETH, _tokensErc20[i], _amounts[i], 0x0); totalAmount = totalAmount.add(_amounts[i]); } require(exchange.buyTokens.value(totalAmount)(_tokensErc20, _amounts, _rates, address(this), 0x0)); return true; } // ----------------------------- REBALANCE ----------------------------- function rebalance() public onlyOwner returns (bool success) { RebalanceInterface rebalanceProvider = RebalanceInterface(getComponentByName(REBALANCE)); OlympusExchangeInterface exchangeProvider = OlympusExchangeInterface(getComponentByName(EXCHANGE)); address[] memory tokensToSell; uint[] memory amountsToSell; address[] memory tokensToBuy; uint[] memory amountsToBuy; uint i; uint ETHBalanceBefore = address(this).balance; (tokensToSell, amountsToSell, tokensToBuy, amountsToBuy,) = rebalanceProvider.rebalanceGetTokensToSellAndBuy(rebalanceDeltaPercentage); // Sell Tokens for (i = 0; i < tokensToSell.length; i++) { ERC20NoReturn(tokensToSell[i]).approve(address(exchangeProvider), 0); ERC20NoReturn(tokensToSell[i]).approve(address(exchangeProvider), amountsToSell[i]); require(exchangeProvider.sellToken(ERC20Extended(tokensToSell[i]), amountsToSell[i], 0, address(this), 0x0)); } // Buy Tokens amountsToBuy = rebalanceProvider.recalculateTokensToBuyAfterSale(address(this).balance - ETHBalanceBefore); for (i = 0; i < tokensToBuy.length; i++) { require( exchangeProvider.buyToken.value(amountsToBuy[i])(ERC20Extended(tokensToBuy[i]), amountsToBuy[i], 0, address(this), 0x0) ); } rebalanceProvider.finalize(); return true; } function approveComponents() private { approveComponent(EXCHANGE); approveComponent(WITHDRAW); approveComponent(REBALANCE); } function getETHBalance() public view returns(uint) { return address(this).balance; } }
----------------------------- BUY TOKENS -----------------------------
function buyTokens() external onlyOwner returns(bool) { OlympusExchangeInterface exchange = OlympusExchangeInterface(getComponentByName(EXCHANGE)); uint[] memory _amounts = new uint[](tokens.length); uint ethBalance = address(this).balance; uint totalAmount = 0; for(uint i = 0; i < tokens.length; i++) { _amounts[i] = ethBalance.mul(weights[i]).div(100); _tokensErc20[i] = ERC20Extended(tokens[i]); (, _rates[i] ) = exchange.getPrice(ETH, _tokensErc20[i], _amounts[i], 0x0); totalAmount = totalAmount.add(_amounts[i]); } require(exchange.buyTokens.value(totalAmount)(_tokensErc20, _amounts, _rates, address(this), 0x0)); return true; }
15,836,658
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul interface DharmaTradeReserveV15Interface { event Trade( address account, address suppliedAsset, address receivedAsset, address retainedAsset, uint256 suppliedAmount, uint256 recievedAmount, uint256 retainedAmount ); event RoleModified(Role indexed role, address account); event RolePaused(Role indexed role); event RoleUnpaused(Role indexed role); event EtherReceived(address sender, uint256 amount); event GasReserveRefilled(uint256 etherAmount); enum Role { // # DEPOSIT_MANAGER, // 0 ADJUSTER, // 1 WITHDRAWAL_MANAGER, // 2 RESERVE_TRADER, // 3 PAUSER, // 4 GAS_RESERVE_REFILLER // 5 } enum TradeType { DAI_TO_TOKEN, DAI_TO_ETH, ETH_TO_DAI, TOKEN_TO_DAI, ETH_TO_TOKEN, TOKEN_TO_ETH, TOKEN_TO_TOKEN } struct RoleStatus { address account; bool paused; } function tradeDaiForEtherV2( uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function tradeEtherForDaiV2( uint256 quotedDaiAmount, uint256 deadline ) external payable returns (uint256 totalDaiBought); function tradeDaiForToken( address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold); function tradeTokenForDai( ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought); function tradeTokenForEther( ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought); function tradeEtherForToken( address token, uint256 quotedTokenAmount, uint256 deadline ) external payable returns (uint256 totalEtherSold); function tradeEtherForTokenUsingEtherizer( address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold); function tradeTokenForToken( ERC20Interface tokenProvided, address tokenReceived, uint256 tokenProvidedAmount, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalTokensSold); function tradeTokenForTokenUsingReserves( ERC20Interface tokenProvidedFromReserves, address tokenReceived, uint256 tokenProvidedAmountFromReserves, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalTokensSold); function tradeDaiForEtherUsingReservesV2( uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function tradeEtherForDaiUsingReservesAndMintDDaiV2( uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted); function tradeDaiForTokenUsingReserves( address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold); function tradeTokenForDaiUsingReservesAndMintDDai( ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted); function tradeTokenForEtherUsingReserves( ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought); function tradeEtherForTokenUsingReserves( address token, uint256 etherAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold); function finalizeEtherDeposit( address payable smartWallet, address initialUserSigningKey, uint256 etherAmount ) external; function finalizeDaiDeposit( address smartWallet, address initialUserSigningKey, uint256 daiAmount ) external; function finalizeDharmaDaiDeposit( address smartWallet, address initialUserSigningKey, uint256 dDaiAmount ) external; function mint(uint256 daiAmount) external returns (uint256 dDaiMinted); function redeem(uint256 dDaiAmount) external returns (uint256 daiReceived); function tradeDDaiForUSDC( uint256 daiEquivalentAmount, uint256 quotedUSDCAmount ) external returns (uint256 usdcReceived); function tradeUSDCForDDai( uint256 usdcAmount, uint256 quotedDaiEquivalentAmount ) external returns (uint256 dDaiMinted); function refillGasReserve(uint256 etherAmount) external; function withdrawUSDC(address recipient, uint256 usdcAmount) external; function withdrawDai(address recipient, uint256 daiAmount) external; function withdrawDharmaDai(address recipient, uint256 dDaiAmount) external; function withdrawUSDCToPrimaryRecipient(uint256 usdcAmount) external; function withdrawDaiToPrimaryRecipient(uint256 usdcAmount) external; function withdrawEther( address payable recipient, uint256 etherAmount ) external; function withdraw( ERC20Interface token, address recipient, uint256 amount ) external returns (bool success); function callAny( address payable target, uint256 amount, bytes calldata data ) external returns (bool ok, bytes memory returnData); function setDaiLimit(uint256 daiAmount) external; function setEtherLimit(uint256 daiAmount) external; function setPrimaryUSDCRecipient(address recipient) external; function setPrimaryDaiRecipient(address recipient) external; function setRole(Role role, address account) external; function removeRole(Role role) external; function pause(Role role) external; function unpause(Role role) external; function isPaused(Role role) external view returns (bool paused); function isRole(Role role) external view returns (bool hasRole); function isDharmaSmartWallet( address smartWallet, address initialUserSigningKey ) external view returns (bool dharmaSmartWallet); function getDepositManager() external view returns (address depositManager); function getAdjuster() external view returns (address adjuster); function getReserveTrader() external view returns (address reserveTrader); function getWithdrawalManager() external view returns (address withdrawalManager); function getPauser() external view returns (address pauser); function getGasReserveRefiller() external view returns (address gasReserveRefiller); function getReserves() external view returns ( uint256 dai, uint256 dDai, uint256 dDaiUnderlying ); function getDaiLimit() external view returns ( uint256 daiAmount, uint256 dDaiAmount ); function getEtherLimit() external view returns (uint256 etherAmount); function getPrimaryUSDCRecipient() external view returns ( address recipient ); function getPrimaryDaiRecipient() external view returns ( address recipient ); function getImplementation() external view returns (address implementation); function getInstance() external pure returns (address instance); function getVersion() external view returns (uint256 version); } interface ERC20Interface { function balanceOf(address) external view returns (uint256); function approve(address, uint256) external returns (bool); function allowance(address, address) external view returns (uint256); function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); } interface DTokenInterface { function mint(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); function redeem(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); function redeemUnderlying(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); function balanceOf(address) external view returns (uint256); function balanceOfUnderlying(address) external view returns (uint256); function transfer(address, uint256) external returns (bool); function approve(address, uint256) external returns (bool); function exchangeRateCurrent() external view returns (uint256); } interface TradeHelperInterface { function tradeUSDCForDDai( uint256 amountUSDC, uint256 quotedDaiEquivalentAmount ) external returns (uint256 dDaiMinted); function tradeDDaiForUSDC( uint256 amountDai, uint256 quotedUSDCAmount ) external returns (uint256 usdcReceived); function getExpectedDai(uint256 usdc) external view returns (uint256 dai); function getExpectedUSDC(uint256 dai) external view returns (uint256 usdc); } interface UniswapV2Interface { function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } } /** * @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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. * * In order to transfer ownership, a recipient must be specified, at which point * the specified recipient can call `acceptOwnership` and take ownership. */ contract TwoStepOwnable { event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); address private _owner; address private _newPotentialOwner; /** * @dev Allows a new account (`newOwner`) to accept ownership. * Can only be called by the current owner. */ function transferOwnership(address newOwner) external onlyOwner { require( newOwner != address(0), "TwoStepOwnable: new potential owner is the zero address." ); _newPotentialOwner = newOwner; } /** * @dev Cancel a transfer of ownership to a new account. * Can only be called by the current owner. */ function cancelOwnershipTransfer() external onlyOwner { delete _newPotentialOwner; } /** * @dev Transfers ownership of the contract to the caller. * Can only be called by a new potential owner set by the current owner. */ function acceptOwnership() external { require( msg.sender == _newPotentialOwner, "TwoStepOwnable: current owner must set caller as new potential owner." ); delete _newPotentialOwner; emit OwnershipTransferred(_owner, msg.sender); _owner = msg.sender; } /** * @dev Returns the address of the current owner. */ function owner() external view returns (address) { return _owner; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "TwoStepOwnable: caller is not the owner."); _; } } /** * @title DharmaTradeReserveV15ImplementationStaging * @author 0age * @notice This contract manages Dharma's reserves. It designates a collection of * "roles" - these are dedicated accounts that can be modified by the owner, and * that can trigger specific functionality on the reserve. These roles are: * - depositManager (0): initiates Eth / token transfers to smart wallets * - adjuster (1): mints / redeems Dai, and swaps USDC, for dDai * - withdrawalManager (2): initiates token transfers to recipients set by owner * - reserveTrader (3): initiates trades using funds held in reserve * - pauser (4): pauses any role (only the owner is then able to unpause it) * - gasReserveRefiller (5): transfers Ether to the Dharma Gas Reserve * * When finalizing deposits, the deposit manager must adhere to two constraints: * - it must provide "proof" that the recipient is a smart wallet by including * the initial user signing key used to derive the smart wallet address * - it must not attempt to transfer more Eth, Dai, or the Dai-equivalent * value of Dharma Dai, than the current "limit" set by the owner. * * Note that "proofs" can be validated via `isSmartWallet`. */ contract DharmaTradeReserveV15ImplementationStaging is DharmaTradeReserveV15Interface, TwoStepOwnable { using SafeMath for uint256; // Maintain a role status mapping with assigned accounts and paused states. mapping(uint256 => RoleStatus) private _roles; // Maintain a "primary recipient" the withdrawal manager can transfer Dai to. address private _primaryDaiRecipient; // Maintain a "primary recipient" the withdrawal manager can transfer USDC to. address private _primaryUSDCRecipient; // Maintain a maximum allowable transfer size (in Dai) for the deposit manager. uint256 private _daiLimit; // Maintain a maximum allowable transfer size (in Ether) for the deposit manager. uint256 private _etherLimit; bool private _originatesFromReserveTrader; // unused, don't change storage layout uint256 private constant _VERSION = 1015; // This contract interacts with USDC, Dai, and Dharma Dai. ERC20Interface internal constant _USDC = ERC20Interface( 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet ); ERC20Interface internal constant _DAI = ERC20Interface( 0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet ); ERC20Interface internal constant _ETHERIZER = ERC20Interface( 0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191 ); DTokenInterface internal constant _DDAI = DTokenInterface( 0x00000000001876eB1444c986fD502e618c587430 ); TradeHelperInterface internal constant _TRADE_HELPER = TradeHelperInterface( 0x9328F2Fb3e85A4d24Adc2f68F82737183e85691d ); UniswapV2Interface internal constant _UNISWAP_ROUTER = UniswapV2Interface( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address internal constant _WETH = address( 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ); address internal constant _GAS_RESERVE = address( 0x09cd826D4ABA4088E1381A1957962C946520952d // staging version ); // The "Create2 Header" is used to compute smart wallet deployment addresses. bytes21 internal constant _CREATE2_HEADER = bytes21( 0xff8D1e00b000e56d5BcB006F3a008Ca6003b9F0033 // control character + factory ); // The "Wallet creation code" header & footer are also used to derive wallets. bytes internal constant _WALLET_CREATION_CODE_HEADER = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a723158203c578cc1552f1d1b48134a72934fe12fb89a29ff396bd514b9a4cebcacc5cacc64736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000"; bytes28 internal constant _WALLET_CREATION_CODE_FOOTER = bytes28( 0x00000000000000000000000000000000000000000000000000000000 ); // Flag to trigger trade for USDC and retain full trade amount address internal constant _TRADE_FOR_USDC_AND_RETAIN_FLAG = address(uint160(-1)); // Include a payable fallback so that the contract can receive Ether payments. function () external payable { emit EtherReceived(msg.sender, msg.value); } function initialize() external onlyOwner { // Approve Uniswap router to transfer WETH on behalf of this contract. _grantUniswapRouterApprovalIfNecessary(ERC20Interface(_WETH), uint256(-1)); } /** * @notice Pull in `daiAmount` Dai from the caller, trade it for Ether using * UniswapV2, and return `quotedEtherAmount` Ether to the caller. * @param daiAmount uint256 The amount of Dai to supply when trading for Ether. * @param quotedEtherAmount uint256 The amount of Ether to return to the caller. * @param deadline uint256 The timestamp the order is valid until. * @return The amount of Dai sold as part of the trade. */ function tradeDaiForEtherV2( uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold) { // Transfer the Dai from the caller and revert on failure. _transferInToken(_DAI, msg.sender, daiAmount); // Trade Dai for Ether. totalDaiSold = _tradeDaiForEther( daiAmount, quotedEtherAmount, deadline, false ); } function tradeTokenForEther( ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought) { // Transfer the tokens from the caller and revert on failure. _transferInToken(token, msg.sender, tokenAmount); // Trade tokens for Ether. totalEtherBought = _tradeTokenForEther( token, tokenAmount, quotedEtherAmount, deadline, false ); // Transfer the quoted Ether amount to the caller. _transferEther(msg.sender, quotedEtherAmount); } function tradeDaiForToken( address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold) { // Transfer the Dai from the caller and revert on failure. _transferInToken(_DAI, msg.sender, daiAmount); // Trade Dai for specified token. totalDaiSold = _tradeDaiForToken( token, daiAmount, quotedTokenAmount, deadline, routeThroughEther, false ); } /** * @notice Using `daiAmountFromReserves` Dai (note that dDai will be redeemed * if necessary), trade for Ether using UniswapV2. Only the owner or the trade * reserve role can call this function. Note that Dharma Dai will be redeemed * to cover the Dai if there is not enough currently in the contract. * @param daiAmountFromReserves the amount of Dai to take from reserves. * @param quotedEtherAmount uint256 The amount of Ether requested in the trade. * @param deadline uint256 The timestamp the order is valid until. * @return The amount of Ether bought as part of the trade. */ function tradeDaiForEtherUsingReservesV2( uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) { // Redeem dDai if the current Dai balance is less than is required. _redeemDDaiIfNecessary(daiAmountFromReserves); // Trade Dai for Ether using reserves. totalDaiSold = _tradeDaiForEther( daiAmountFromReserves, quotedEtherAmount, deadline, true ); } function tradeTokenForEtherUsingReserves( ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalEtherBought) { // Trade tokens for Ether using reserves. totalEtherBought = _tradeTokenForEther( token, tokenAmountFromReserves, quotedEtherAmount, deadline, true ); } /** * @notice Accept `msg.value` Ether from the caller, trade it for Dai using * UniswapV2, and return `quotedDaiAmount` Dai to the caller. * @param quotedDaiAmount uint256 The amount of Dai to return to the caller. * @param deadline uint256 The timestamp the order is valid until. * @return The amount of Dai bought as part of the trade. */ function tradeEtherForDaiV2( uint256 quotedDaiAmount, uint256 deadline ) external payable returns (uint256 totalDaiBought) { // Trade Ether for Dai. totalDaiBought = _tradeEtherForDai( msg.value, quotedDaiAmount, deadline, false ); // Transfer the Dai to the caller and revert on failure. _transferToken(_DAI, msg.sender, quotedDaiAmount); } function tradeEtherForToken( address token, uint256 quotedTokenAmount, uint256 deadline ) external payable returns (uint256 totalEtherSold) { // Trade Ether for the specified token. totalEtherSold = _tradeEtherForToken( token, msg.value, quotedTokenAmount, deadline, false ); } function tradeEtherForTokenUsingEtherizer( address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold) { // Transfer the Ether from the caller and revert on failure. _transferInToken(_ETHERIZER, msg.sender, etherAmount); // Trade Ether for the specified token. totalEtherSold = _tradeEtherForToken( token, etherAmount, quotedTokenAmount, deadline, false ); } function tradeTokenForDai( ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought) { // Transfer the token from the caller and revert on failure. _transferInToken(token, msg.sender, tokenAmount); // Trade the token for Dai. totalDaiBought = _tradeTokenForDai( token, tokenAmount, quotedDaiAmount, deadline, routeThroughEther, false ); // Transfer the quoted Dai amount to the caller and revert on failure. _transferToken(_DAI, msg.sender, quotedDaiAmount); } function tradeTokenForToken( ERC20Interface tokenProvided, address tokenReceived, uint256 tokenProvidedAmount, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalTokensSold) { // Transfer the token from the caller and revert on failure. _transferInToken(tokenProvided, msg.sender, tokenProvidedAmount); totalTokensSold = _tradeTokenForToken( msg.sender, tokenProvided, tokenReceived, tokenProvidedAmount, quotedTokenReceivedAmount, deadline, routeThroughEther ); } function tradeTokenForTokenUsingReserves( ERC20Interface tokenProvidedFromReserves, address tokenReceived, uint256 tokenProvidedAmountFromReserves, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalTokensSold) { totalTokensSold = _tradeTokenForToken( address(this), tokenProvidedFromReserves, tokenReceived, tokenProvidedAmountFromReserves, quotedTokenReceivedAmount, deadline, routeThroughEther ); } /** * @notice Using `etherAmountFromReserves`, trade for Dai using UniswapV2, * and use that Dai to mint Dharma Dai. * Only the owner or the trade reserve role can call this function. * @param etherAmountFromReserves the amount of Ether to take from reserves * and add to the provided amount. * @param quotedDaiAmount uint256 The amount of Dai requested in the trade. * @param deadline uint256 The timestamp the order is valid until. * @return The amount of Dai bought as part of the trade. */ function tradeEtherForDaiUsingReservesAndMintDDaiV2( uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external onlyOwnerOr(Role.RESERVE_TRADER) returns ( uint256 totalDaiBought, uint256 totalDDaiMinted ) { // Trade Ether for Dai using reserves. totalDaiBought = _tradeEtherForDai( etherAmountFromReserves, quotedDaiAmount, deadline, true ); // Mint dDai using the received Dai. totalDDaiMinted = _DDAI.mint(totalDaiBought); } function tradeEtherForTokenUsingReserves( address token, uint256 etherAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalEtherSold) { // Trade Ether for token using reserves. totalEtherSold = _tradeEtherForToken( token, etherAmountFromReserves, quotedTokenAmount, deadline, true ); } function tradeDaiForTokenUsingReserves( address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) { // Redeem dDai if the current Dai balance is less than is required. _redeemDDaiIfNecessary(daiAmountFromReserves); // Trade Dai for token using reserves. totalDaiSold = _tradeDaiForToken( token, daiAmountFromReserves, quotedTokenAmount, deadline, routeThroughEther, true ); } function tradeTokenForDaiUsingReservesAndMintDDai( ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external onlyOwnerOr(Role.RESERVE_TRADER) returns ( uint256 totalDaiBought, uint256 totalDDaiMinted ) { // Trade the token for Dai using reserves. totalDaiBought = _tradeTokenForDai( token, tokenAmountFromReserves, quotedDaiAmount, deadline, routeThroughEther, true ); // Mint dDai using the received Dai. totalDDaiMinted = _DDAI.mint(totalDaiBought); } /** * @notice Transfer `daiAmount` Dai to `smartWallet`, providing the initial * user signing key `initialUserSigningKey` as proof that the specified smart * wallet is indeed a Dharma Smart Wallet - this assumes that the address is * derived and deployed using the Dharma Smart Wallet Factory V1. In addition, * the specified amount must be less than the configured limit amount. Only * the owner or the designated deposit manager role may call this function. * @param smartWallet address The smart wallet to transfer Dai to. * @param initialUserSigningKey address The initial user signing key supplied * when deriving the smart wallet address - this could be an EOA or a Dharma * key ring address. * @param daiAmount uint256 The amount of Dai to transfer - this must be less * than the current limit. */ function finalizeDaiDeposit( address smartWallet, address initialUserSigningKey, uint256 daiAmount ) external onlyOwnerOr(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ensureSmartWallet(smartWallet, initialUserSigningKey); // Ensure that the amount to transfer is lower than the limit. require(daiAmount < _daiLimit, "Transfer size exceeds the limit."); // Transfer the Dai to the specified smart wallet. _transferToken(_DAI, smartWallet, daiAmount); } /** * @notice Transfer `dDaiAmount` Dharma Dai to `smartWallet`, providing the * initial user signing key `initialUserSigningKey` as proof that the * specified smart wallet is indeed a Dharma Smart Wallet - this assumes that * the address is derived and deployed using the Dharma Smart Wallet Factory * V1. In addition, the Dai equivalent value of the specified dDai amount must * be less than the configured limit amount. Only the owner or the designated * deposit manager role may call this function. * @param smartWallet address The smart wallet to transfer Dai to. * @param initialUserSigningKey address The initial user signing key supplied * when deriving the smart wallet address - this could be an EOA or a Dharma * key ring address. * @param dDaiAmount uint256 The amount of Dharma Dai to transfer - the Dai * equivalent amount must be less than the current limit. */ function finalizeDharmaDaiDeposit( address smartWallet, address initialUserSigningKey, uint256 dDaiAmount ) external onlyOwnerOr(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ensureSmartWallet(smartWallet, initialUserSigningKey); // Get the current dDai exchange rate. uint256 exchangeRate = _DDAI.exchangeRateCurrent(); // Ensure that an exchange rate was actually returned. require(exchangeRate != 0, "Could not retrieve dDai exchange rate."); // Get the equivalent Dai amount of the transfer. uint256 daiEquivalent = (dDaiAmount.mul(exchangeRate)) / 1e18; // Ensure that the amount to transfer is lower than the limit. require(daiEquivalent < _daiLimit, "Transfer size exceeds the limit."); // Transfer the dDai to the specified smart wallet. _transferToken(ERC20Interface(address(_DDAI)), smartWallet, dDaiAmount); } /** * @notice Transfer `etherAmount` Ether to `smartWallet`, providing the * initial user signing key `initialUserSigningKey` as proof that the * specified smart wallet is indeed a Dharma Smart Wallet - this assumes that * the address is derived and deployed using the Dharma Smart Wallet Factory * V1. In addition, the Ether amount must be less than the configured limit * amount. Only the owner or the designated deposit manager role may call this * function. * @param smartWallet address The smart wallet to transfer Ether to. * @param initialUserSigningKey address The initial user signing key supplied * when deriving the smart wallet address - this could be an EOA or a Dharma * key ring address. * @param etherAmount uint256 The amount of Ether to transfer - this amount must be * less than the current limit. */ function finalizeEtherDeposit( address payable smartWallet, address initialUserSigningKey, uint256 etherAmount ) external onlyOwnerOr(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ensureSmartWallet(smartWallet, initialUserSigningKey); // Ensure that the amount to transfer is lower than the limit. require(etherAmount < _etherLimit, "Transfer size exceeds the limit."); // Transfer the Ether to the specified smart wallet. _transferEther(smartWallet, etherAmount); } /** * @notice Use `daiAmount` Dai mint Dharma Dai. Only the owner or the * designated adjuster role may call this function. * @param daiAmount uint256 The amount of Dai to supply when minting Dharma * Dai. * @return The amount of Dharma Dai minted. */ function mint( uint256 daiAmount ) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiMinted) { // Use the specified amount of Dai to mint dDai. dDaiMinted = _DDAI.mint(daiAmount); } /** * @notice Redeem `dDaiAmount` Dharma Dai for Dai. Only the owner or the * designated adjuster role may call this function. * @param dDaiAmount uint256 The amount of Dharma Dai to supply when redeeming * for Dai. * @return The amount of Dai received. */ function redeem( uint256 dDaiAmount ) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 daiReceived) { // Redeem the specified amount of dDai for Dai. daiReceived = _DDAI.redeem(dDaiAmount); } /** * @notice trade `usdcAmount` USDC for Dharma Dai. Only the owner or the designated * adjuster role may call this function. * @param usdcAmount uint256 The amount of USDC to supply when trading for Dharma Dai. * @param quotedDaiEquivalentAmount uint256 The expected DAI equivalent value of the * received dDai - this value is returned from the `getAndExpectedDai` view function * on the trade helper. * @return The amount of dDai received. */ function tradeUSDCForDDai( uint256 usdcAmount, uint256 quotedDaiEquivalentAmount ) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiMinted) { dDaiMinted = _TRADE_HELPER.tradeUSDCForDDai( usdcAmount, quotedDaiEquivalentAmount ); } /** * @notice tradeDDaiForUSDC `daiEquivalentAmount` Dai amount to trade in Dharma Dai * for USDC. Only the owner or the designated adjuster role may call this function. * @param daiEquivalentAmount uint256 The Dai equivalent amount to supply in Dharma * Dai when trading for USDC. * @param quotedUSDCAmount uint256 The expected USDC received in exchange for * dDai - this value is returned from the `getExpectedUSDC` view function on the * trade helper. * @return The amount of USDC received. */ function tradeDDaiForUSDC( uint256 daiEquivalentAmount, uint256 quotedUSDCAmount ) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 usdcReceived) { usdcReceived = _TRADE_HELPER.tradeDDaiForUSDC( daiEquivalentAmount, quotedUSDCAmount ); } function refillGasReserve(uint256 etherAmount) external onlyOwnerOr(Role.GAS_RESERVE_REFILLER) { // Transfer the Ether to the gas reserve. _transferEther(_GAS_RESERVE, etherAmount); emit GasReserveRefilled(etherAmount); } /** * @notice Transfer `usdcAmount` USDC for to the current primary recipient set by the * owner. Only the owner or the designated withdrawal manager role may call this function. * @param usdcAmount uint256 The amount of USDC to transfer to the primary recipient. */ function withdrawUSDCToPrimaryRecipient( uint256 usdcAmount ) external onlyOwnerOr(Role.WITHDRAWAL_MANAGER) { // Get the current primary recipient. address primaryRecipient = _primaryUSDCRecipient; require( primaryRecipient != address(0), "No USDC primary recipient currently set." ); // Transfer the supplied USDC amount to the primary recipient. _transferToken(_USDC, primaryRecipient, usdcAmount); } /** * @notice Transfer `daiAmount` Dai for to the current primary recipient set by the * owner. Only the owner or the designated withdrawal manager role may call this function. * @param daiAmount uint256 The amount of Dai to transfer to the primary recipient. */ function withdrawDaiToPrimaryRecipient( uint256 daiAmount ) external onlyOwnerOr(Role.WITHDRAWAL_MANAGER) { // Get the current primary recipient. address primaryRecipient = _primaryDaiRecipient; require( primaryRecipient != address(0), "No Dai primary recipient currently set." ); // Transfer the supplied Dai amount to the primary recipient. _transferToken(_DAI, primaryRecipient, daiAmount); } /** * @notice Transfer `usdcAmount` USDC to `recipient`. Only the owner may call * this function. * @param recipient address The account to transfer USDC to. * @param usdcAmount uint256 The amount of USDC to transfer. */ function withdrawUSDC( address recipient, uint256 usdcAmount ) external onlyOwner { // Transfer the USDC to the specified recipient. _transferToken(_USDC, recipient, usdcAmount); } /** * @notice Transfer `daiAmount` Dai to `recipient`. Only the owner may call * this function. * @param recipient address The account to transfer Dai to. * @param daiAmount uint256 The amount of Dai to transfer. */ function withdrawDai( address recipient, uint256 daiAmount ) external onlyOwner { // Transfer the Dai to the specified recipient. _transferToken(_DAI, recipient, daiAmount); } /** * @notice Transfer `dDaiAmount` Dharma Dai to `recipient`. Only the owner may * call this function. * @param recipient address The account to transfer Dharma Dai to. * @param dDaiAmount uint256 The amount of Dharma Dai to transfer. */ function withdrawDharmaDai( address recipient, uint256 dDaiAmount ) external onlyOwner { // Transfer the dDai to the specified recipient. _transferToken(ERC20Interface(address(_DDAI)), recipient, dDaiAmount); } /** * @notice Transfer `etherAmount` Ether to `recipient`. Only the owner may * call this function. * @param recipient address The account to transfer Ether to. * @param etherAmount uint256 The amount of Ether to transfer. */ function withdrawEther( address payable recipient, uint256 etherAmount ) external onlyOwner { // Transfer the Ether to the specified recipient. _transferEther(recipient, etherAmount); } /** * @notice Transfer `amount` of ERC20 token `token` to `recipient`. Only the * owner may call this function. * @param token ERC20Interface The ERC20 token to transfer. * @param recipient address The account to transfer the tokens to. * @param amount uint256 The amount of tokens to transfer. * @return A boolean to indicate if the transfer was successful - note that * unsuccessful ERC20 transfers will usually revert. */ function withdraw( ERC20Interface token, address recipient, uint256 amount ) external onlyOwner returns (bool success) { // Transfer the token to the specified recipient. success = token.transfer(recipient, amount); } /** * @notice Call account `target`, supplying value `amount` and data `data`. * Only the owner may call this function. * @param target address The account to call. * @param amount uint256 The amount of ether to include as an endowment. * @param data bytes The data to include along with the call. * @return A boolean to indicate if the call was successful, as well as the * returned data or revert reason. */ function callAny( address payable target, uint256 amount, bytes calldata data ) external onlyOwner returns (bool ok, bytes memory returnData) { // Call the specified target and supply the specified data. (ok, returnData) = target.call.value(amount)(data); } /** * @notice Set `daiAmount` as the new limit on the size of finalized deposits. * Only the owner may call this function. * @param daiAmount uint256 The new limit on the size of finalized deposits. */ function setDaiLimit(uint256 daiAmount) external onlyOwner { // Set the new limit. _daiLimit = daiAmount; } /** * @notice Set `etherAmount` as the new limit on the size of finalized deposits. * Only the owner may call this function. * @param etherAmount uint256 The new limit on the size of finalized deposits. */ function setEtherLimit(uint256 etherAmount) external onlyOwner { // Set the new limit. _etherLimit = etherAmount; } /** * @notice Set `recipient` as the new primary recipient for USDC withdrawals. * Only the owner may call this function. * @param recipient address The new primary recipient. */ function setPrimaryUSDCRecipient(address recipient) external onlyOwner { // Set the new primary recipient. _primaryUSDCRecipient = recipient; } /** * @notice Set `recipient` as the new primary recipient for Dai withdrawals. * Only the owner may call this function. * @param recipient address The new primary recipient. */ function setPrimaryDaiRecipient(address recipient) external onlyOwner { // Set the new primary recipient. _primaryDaiRecipient = recipient; } /** * @notice Pause a currently unpaused role and emit a `RolePaused` event. Only * the owner or the designated pauser may call this function. Also, bear in * mind that only the owner may unpause a role once paused. * @param role The role to pause. */ function pause(Role role) external onlyOwnerOr(Role.PAUSER) { RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(!storedRoleStatus.paused, "Role in question is already paused."); storedRoleStatus.paused = true; emit RolePaused(role); } /** * @notice Unpause a currently paused role and emit a `RoleUnpaused` event. * Only the owner may call this function. * @param role The role to pause. */ function unpause(Role role) external onlyOwner { RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(storedRoleStatus.paused, "Role in question is already unpaused."); storedRoleStatus.paused = false; emit RoleUnpaused(role); } /** * @notice Set a new account on a given role and emit a `RoleModified` event * if the role holder has changed. Only the owner may call this function. * @param role The role that the account will be set for. * @param account The account to set as the designated role bearer. */ function setRole(Role role, address account) external onlyOwner { require(account != address(0), "Must supply an account."); _setRole(role, account); } /** * @notice Remove any current role bearer for a given role and emit a * `RoleModified` event if a role holder was previously set. Only the owner * may call this function. * @param role The role that the account will be removed from. */ function removeRole(Role role) external onlyOwner { _setRole(role, address(0)); } /** * @notice External view function to check whether or not the functionality * associated with a given role is currently paused or not. The owner or the * pauser may pause any given role (including the pauser itself), but only the * owner may unpause functionality. Additionally, the owner may call paused * functions directly. * @param role The role to check the pause status on. * @return A boolean to indicate if the functionality associated with the role * in question is currently paused. */ function isPaused(Role role) external view returns (bool paused) { paused = _isPaused(role); } /** * @notice External view function to check whether the caller is the current * role holder. * @param role The role to check for. * @return A boolean indicating if the caller has the specified role. */ function isRole(Role role) external view returns (bool hasRole) { hasRole = _isRole(role); } /** * @notice External view function to check whether a "proof" that a given * smart wallet is actually a Dharma Smart Wallet, based on the initial user * signing key, is valid or not. This proof only works when the Dharma Smart * Wallet in question is derived using V1 of the Dharma Smart Wallet Factory. * @param smartWallet address The smart wallet to check. * @param initialUserSigningKey address The initial user signing key supplied * when deriving the smart wallet address - this could be an EOA or a Dharma * key ring address. * @return A boolean indicating if the specified smart wallet account is * indeed a smart wallet based on the specified initial user signing key. */ function isDharmaSmartWallet( address smartWallet, address initialUserSigningKey ) external view returns (bool dharmaSmartWallet) { dharmaSmartWallet = _isSmartWallet(smartWallet, initialUserSigningKey); } /** * @notice External view function to check the account currently holding the * deposit manager role. The deposit manager can process standard deposit * finalization via `finalizeDaiDeposit` and `finalizeDharmaDaiDeposit`, but * must prove that the recipient is a Dharma Smart Wallet and adhere to the * current deposit size limit. * @return The address of the current deposit manager, or the null address if * none is set. */ function getDepositManager() external view returns (address depositManager) { depositManager = _roles[uint256(Role.DEPOSIT_MANAGER)].account; } /** * @notice External view function to check the account currently holding the * adjuster role. The adjuster can exchange Dai in reserves for Dharma Dai and * vice-versa via minting or redeeming. * @return The address of the current adjuster, or the null address if none is * set. */ function getAdjuster() external view returns (address adjuster) { adjuster = _roles[uint256(Role.ADJUSTER)].account; } /** * @notice External view function to check the account currently holding the * reserve trader role. The reserve trader can trigger trades that utilize * reserves in addition to supplied funds, if any. * @return The address of the current reserve trader, or the null address if * none is set. */ function getReserveTrader() external view returns (address reserveTrader) { reserveTrader = _roles[uint256(Role.RESERVE_TRADER)].account; } /** * @notice External view function to check the account currently holding the * withdrawal manager role. The withdrawal manager can transfer USDC to the * "primary recipient" address set by the owner. * @return The address of the current withdrawal manager, or the null address * if none is set. */ function getWithdrawalManager() external view returns (address withdrawalManager) { withdrawalManager = _roles[uint256(Role.WITHDRAWAL_MANAGER)].account; } /** * @notice External view function to check the account currently holding the * pauser role. The pauser can pause any role from taking its standard action, * though the owner will still be able to call the associated function in the * interim and is the only entity able to unpause the given role once paused. * @return The address of the current pauser, or the null address if none is * set. */ function getPauser() external view returns (address pauser) { pauser = _roles[uint256(Role.PAUSER)].account; } function getGasReserveRefiller() external view returns (address gasReserveRefiller) { gasReserveRefiller = _roles[uint256(Role.GAS_RESERVE_REFILLER)].account; } /** * @notice External view function to check the current reserves held by this * contract. * @return The Dai and Dharma Dai reserves held by this contract, as well as * the Dai-equivalent value of the Dharma Dai reserves. */ function getReserves() external view returns ( uint256 dai, uint256 dDai, uint256 dDaiUnderlying ) { dai = _DAI.balanceOf(address(this)); dDai = _DDAI.balanceOf(address(this)); dDaiUnderlying = _DDAI.balanceOfUnderlying(address(this)); } /** * @notice External view function to check the current limit on deposit amount * enforced for the deposit manager when finalizing deposits, expressed in Dai * and in Dharma Dai. * @return The Dai and Dharma Dai limit on deposit finalization amount. */ function getDaiLimit() external view returns ( uint256 daiAmount, uint256 dDaiAmount ) { daiAmount = _daiLimit; dDaiAmount = (daiAmount.mul(1e18)).div(_DDAI.exchangeRateCurrent()); } /** * @notice External view function to check the current limit on deposit amount * enforced for the deposit manager when finalizing Ether deposits. * @return The Ether limit on deposit finalization amount. */ function getEtherLimit() external view returns (uint256 etherAmount) { etherAmount = _etherLimit; } /** * @notice External view function to check the address of the current * primary recipient for USDC. * @return The primary recipient for USDC. */ function getPrimaryUSDCRecipient() external view returns ( address recipient ) { recipient = _primaryUSDCRecipient; } /** * @notice External view function to check the address of the current * primary recipient for Dai. * @return The primary recipient for Dai. */ function getPrimaryDaiRecipient() external view returns ( address recipient ) { recipient = _primaryDaiRecipient; } /** * @notice External view function to check the current implementation * of this contract (i.e. the "logic" for the contract). * @return The current implementation for this contract. */ function getImplementation() external view returns ( address implementation ) { (bool ok, bytes memory returnData) = address( 0x481B1a16E6675D33f8BBb3a6A58F5a9678649718 ).staticcall(""); require(ok && returnData.length == 32, "Invalid implementation."); implementation = abi.decode(returnData, (address)); } /** * @notice External pure function to get the address of the actual * contract instance (i.e. the "storage" foor this contract). * @return The address of this contract instance. */ function getInstance() external pure returns (address instance) { instance = address(0x09cd826D4ABA4088E1381A1957962C946520952d); } function getVersion() external view returns (uint256 version) { version = _VERSION; } function _grantUniswapRouterApprovalIfNecessary(ERC20Interface token, uint256 amount) internal { if (token.allowance(address(this), address(_UNISWAP_ROUTER)) < amount) { // Try removing approval for Uniswap router first as a workaround for unusual tokens. (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector( token.approve.selector, address(_UNISWAP_ROUTER), uint256(0) ) ); // Grant approval for Uniswap router to transfer tokens on behalf of this contract. (success, data) = address(token).call( abi.encodeWithSelector( token.approve.selector, address(_UNISWAP_ROUTER), uint256(-1) ) ); if (!success) { // Some really janky tokens only allow setting approval up to current balance. (success, data) = address(token).call( abi.encodeWithSelector( token.approve.selector, address(_UNISWAP_ROUTER), amount ) ); } require( success && (data.length == 0 || abi.decode(data, (bool))), "Token approval for Uniswap router failed." ); } } function _tradeEtherForDai( uint256 etherAmount, uint256 quotedDaiAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalDaiBought) { // Establish path from Ether to Dai. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( _WETH, address(_DAI), false ); // Trade Ether for Dai on Uniswap (send to this contract). amounts = _UNISWAP_ROUTER.swapExactETHForTokens.value(etherAmount)( quotedDaiAmount, path, address(this), deadline ); totalDaiBought = amounts[1]; _fireTradeEvent( fromReserves, TradeType.ETH_TO_DAI, address(0), etherAmount, quotedDaiAmount, totalDaiBought.sub(quotedDaiAmount) ); } function _tradeDaiForEther( uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalDaiSold) { // Establish path from Dai to Ether. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(_DAI), _WETH, false ); // Trade Dai for quoted Ether amount on Uniswap (send to appropriate recipient). amounts = _UNISWAP_ROUTER.swapTokensForExactETH( quotedEtherAmount, daiAmount, path, fromReserves ? address(this) : msg.sender, deadline ); totalDaiSold = amounts[0]; _fireTradeEvent( fromReserves, TradeType.DAI_TO_ETH, address(0), daiAmount, quotedEtherAmount, daiAmount.sub(totalDaiSold) ); } /** * @notice Internal trade function. If token is _TRADE_FOR_USDC_AND_RETAIN_FLAG, * trade for USDC and retain the full output amount by replacing the recipient * ("to" input) on the swapETHForExactTokens call. */ function _tradeEtherForToken( address tokenReceivedOrUSDCFlag, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalEtherSold) { // Set swap target token address tokenReceived = tokenReceivedOrUSDCFlag == _TRADE_FOR_USDC_AND_RETAIN_FLAG ? address(_USDC) : tokenReceivedOrUSDCFlag; // Establish path from Ether to token. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( _WETH, tokenReceived, false ); // Trade Ether for quoted token amount on Uniswap and send to appropriate recipient. amounts = _UNISWAP_ROUTER.swapETHForExactTokens.value(etherAmount)( quotedTokenAmount, path, fromReserves || tokenReceivedOrUSDCFlag == _TRADE_FOR_USDC_AND_RETAIN_FLAG ? address(this) : msg.sender, deadline ); totalEtherSold = amounts[0]; _fireTradeEvent( fromReserves, TradeType.ETH_TO_TOKEN, tokenReceivedOrUSDCFlag, etherAmount, quotedTokenAmount, etherAmount.sub(totalEtherSold) ); } function _tradeTokenForEther( ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalEtherBought) { // Approve Uniswap router to transfer tokens on behalf of this contract. _grantUniswapRouterApprovalIfNecessary(token, tokenAmount); // Establish path from target token to Ether. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(token), _WETH, false ); // Trade tokens for quoted Ether amount on Uniswap (send to this contract). amounts = _UNISWAP_ROUTER.swapExactTokensForETH( tokenAmount, quotedEtherAmount, path, address(this), deadline ); totalEtherBought = amounts[1]; _fireTradeEvent( fromReserves, TradeType.TOKEN_TO_ETH, address(token), tokenAmount, quotedEtherAmount, totalEtherBought.sub(quotedEtherAmount) ); } function _tradeDaiForToken( address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther, bool fromReserves ) internal returns (uint256 totalDaiSold) { // Establish path (direct or routed through Ether) from Dai to target token. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(_DAI), address(token), routeThroughEther ); // Trade the Dai for the quoted token amount on Uniswap and send to appropriate recipient. amounts = _UNISWAP_ROUTER.swapTokensForExactTokens( quotedTokenAmount, daiAmount, path, fromReserves ? address(this) : msg.sender, deadline ); totalDaiSold = amounts[0]; _fireTradeEvent( fromReserves, TradeType.DAI_TO_TOKEN, address(token), daiAmount, quotedTokenAmount, daiAmount.sub(totalDaiSold) ); } function _tradeTokenForDai( ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther, bool fromReserves ) internal returns (uint256 totalDaiBought) { // Approve Uniswap router to transfer tokens on behalf of this contract. _grantUniswapRouterApprovalIfNecessary(token, tokenAmount); // Establish path (direct or routed through Ether) from target token to Dai. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(token), address(_DAI), routeThroughEther ); // Trade the Dai for the quoted token amount on Uniswap (send to this contract). amounts = _UNISWAP_ROUTER.swapExactTokensForTokens( tokenAmount, quotedDaiAmount, path, address(this), deadline ); totalDaiBought = amounts[path.length - 1]; _fireTradeEvent( fromReserves, TradeType.TOKEN_TO_DAI, address(token), tokenAmount, quotedDaiAmount, totalDaiBought.sub(quotedDaiAmount) ); } /** * @notice Internal trade function. If tokenReceived is _TRADE_FOR_USDC_AND_RETAIN_FLAG, * trade for USDC and retain the full output amount by replacing the recipient * ("to" input) on the swapTokensForExactTokens call. */ function _tradeTokenForToken( address account, ERC20Interface tokenProvided, address tokenReceivedOrUSDCFlag, uint256 tokenProvidedAmount, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) internal returns (uint256 totalTokensSold) { uint256 retainedAmount; address tokenRecieved; address recipient; // Approve Uniswap router to transfer tokens on behalf of this contract. _grantUniswapRouterApprovalIfNecessary(tokenProvided, tokenProvidedAmount); // Set recipient, swap target token if (tokenReceivedOrUSDCFlag == _TRADE_FOR_USDC_AND_RETAIN_FLAG) { recipient = address(this); tokenRecieved = address(_USDC); } else { recipient = account; tokenRecieved = tokenReceivedOrUSDCFlag; } if (routeThroughEther == false) { // Establish direct path between tokens. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(tokenProvided), tokenRecieved, false ); // Trade for the quoted token amount on Uniswap and send to recipient. amounts = _UNISWAP_ROUTER.swapTokensForExactTokens( quotedTokenReceivedAmount, tokenProvidedAmount, path, recipient, deadline ); totalTokensSold = amounts[0]; retainedAmount = tokenProvidedAmount.sub(totalTokensSold); } else { // Establish path between provided token and WETH. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(tokenProvided), _WETH, false ); // Trade all provided tokens for WETH on Uniswap and send to this contract. amounts = _UNISWAP_ROUTER.swapExactTokensForTokens( tokenProvidedAmount, 0, path, address(this), deadline ); retainedAmount = amounts[1]; // Establish path between WETH and received token. (path, amounts) = _createPathAndAmounts( _WETH, tokenRecieved, false ); // Trade bought WETH for received token on Uniswap and send to recipient. amounts = _UNISWAP_ROUTER.swapTokensForExactTokens( quotedTokenReceivedAmount, retainedAmount, path, recipient, deadline ); totalTokensSold = amounts[0]; retainedAmount = retainedAmount.sub(totalTokensSold); } emit Trade( account, address(tokenProvided), tokenReceivedOrUSDCFlag, routeThroughEther ? _WETH : address(tokenProvided), tokenProvidedAmount, quotedTokenReceivedAmount, retainedAmount ); } /** * @notice Internal function to set a new account on a given role and emit a * `RoleModified` event if the role holder has changed. * @param role The role that the account will be set for. Permitted roles are * deposit manager (0), adjuster (1), and pauser (2). * @param account The account to set as the designated role bearer. */ function _setRole(Role role, address account) internal { RoleStatus storage storedRoleStatus = _roles[uint256(role)]; if (account != storedRoleStatus.account) { storedRoleStatus.account = account; emit RoleModified(role, account); } } function _fireTradeEvent( bool fromReserves, TradeType tradeType, address token, uint256 suppliedAmount, uint256 receivedAmount, uint256 retainedAmount ) internal { uint256 t = uint256(tradeType); emit Trade( fromReserves ? address(this) : msg.sender, t < 2 ? address(_DAI) : (t % 2 == 0 ? address(0) : token), (t > 1 && t < 4) ? address(_DAI) : (t % 2 == 0 ? token : address(0)), t < 4 ? address(_DAI) : address(0), suppliedAmount, receivedAmount, retainedAmount ); } /** * @notice Internal view function to check whether the caller is the current * role holder. * @param role The role to check for. * @return A boolean indicating if the caller has the specified role. */ function _isRole(Role role) internal view returns (bool hasRole) { hasRole = msg.sender == _roles[uint256(role)].account; } /** * @notice Internal view function to check whether the given role is paused or * not. * @param role The role to check for. * @return A boolean indicating if the specified role is paused or not. */ function _isPaused(Role role) internal view returns (bool paused) { paused = _roles[uint256(role)].paused; } /** * @notice Internal view function to enforce that the given initial user signing * key resolves to the given smart wallet when deployed through the Dharma Smart * Wallet Factory V1. (staging version) * @param smartWallet address The smart wallet. * @param initialUserSigningKey address The initial user signing key. */ function _isSmartWallet( address smartWallet, address initialUserSigningKey ) internal pure returns (bool) { // Derive the keccak256 hash of the smart wallet initialization code. bytes32 initCodeHash = keccak256( abi.encodePacked( _WALLET_CREATION_CODE_HEADER, initialUserSigningKey, _WALLET_CREATION_CODE_FOOTER ) ); // Attempt to derive a smart wallet address that matches the one provided. address target; for (uint256 nonce = 0; nonce < 10; nonce++) { target = address( // derive the target deployment address. uint160( // downcast to match the address type. uint256( // cast to uint to truncate upper digits. keccak256( // compute CREATE2 hash using all inputs. abi.encodePacked( // pack all inputs to the hash together. _CREATE2_HEADER, // pass in control character + factory address. nonce, // pass in current nonce as the salt. initCodeHash // pass in hash of contract creation code. ) ) ) ) ); // Exit early if the provided smart wallet matches derived target address. if (target == smartWallet) { return true; } // Otherwise, increment the nonce and derive a new salt. nonce++; } // Explicity recognize no target was found matching provided smart wallet. return false; } function _redeemDDaiIfNecessary(uint256 daiAmountFromReserves) internal { uint256 daiBalance = _DAI.balanceOf(address(this)); if (daiBalance < daiAmountFromReserves) { uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance; _DDAI.redeemUnderlying(additionalDaiRequired); } } function _transferToken(ERC20Interface token, address to, uint256 amount) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(token.transfer.selector, to, amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Transfer out failed.' ); } function _transferEther(address recipient, uint256 etherAmount) internal { // Send quoted Ether amount to recipient and revert with reason on failure. (bool ok, ) = recipient.call.value(etherAmount)(""); if (!ok) { assembly { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } } function _transferInToken(ERC20Interface token, address from, uint256 amount) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(token.transferFrom.selector, from, address(this), amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Transfer in failed.' ); } function _ensureSmartWallet( address smartWallet, address initialUserSigningKey ) internal pure { require( _isSmartWallet(smartWallet, initialUserSigningKey), "Could not resolve smart wallet using provided signing key." ); } function _createPathAndAmounts( address start, address end, bool routeThroughEther ) internal pure returns (address[] memory, uint256[] memory) { uint256 pathLength = routeThroughEther ? 3 : 2; address[] memory path = new address[](pathLength); path[0] = start; if (routeThroughEther) { path[1] = _WETH; } path[pathLength - 1] = end; return (path, new uint256[](pathLength)); } /** * @notice Modifier that throws if called by any account other than the owner * or the supplied role, or if the caller is not the owner and the role in * question is paused. * @param role The role to require unless the caller is the owner. */ modifier onlyOwnerOr(Role role) { if (!isOwner()) { require(_isRole(role), "Caller does not have a required role."); require(!_isPaused(role), "Role in question is currently paused."); } _; } }
Set `etherAmount` as the new limit on the size of finalized deposits. Only the owner may call this function. etherAmount uint256 The new limit on the size of finalized deposits./ Set the new limit.
function setEtherLimit(uint256 etherAmount) external onlyOwner { _etherLimit = etherAmount; }
606,964
./full_match/100/0xb091087E865d200c622241D1BC00A67Dd465e083/sources/contracts/rari-fuse/src/core/Comptroller.sol
Checks if the liquidation should be allowed to occur cTokenBorrowed Asset which was borrowed by the borrower cTokenCollateral Asset which was used as collateral and will be seized liquidator The address repaying the borrow and seizing the collateral borrower The address of the borrower repayAmount The amount of underlying being repaid/ Shh - currently unused Make sure markets are listed allow accounts to be liquidated if the market is deprecated / The borrower must have shortfall in order to be liquidatable /
function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256) { liquidator; if ( !markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed ) { return uint256(Error.MARKET_NOT_LISTED); } borrower ); if (isDeprecated(CToken(cTokenBorrowed))) { require( borrowBalance >= repayAmount, "Can not repay more than the total borrow" ); (Error err, , uint256 shortfall) = getAccountLiquidityInternal( borrower ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall == 0) { return uint256(Error.INSUFFICIENT_SHORTFALL); } borrowBalance ); if (repayAmount > maxClose) { return uint256(Error.TOO_MUCH_REPAY); } } return uint256(Error.NO_ERROR); }
14,286,753
pragma solidity >=0.4.24; contract ArraysContract { // Elementary type array in storage // Static Array with size 3 of type int int256[3] staticIntArray = [1, 2]; // Last element set to 0 // Dynamic array of type int8 int8[] dynamicIntArray; // Dynamic array of type bool bool[] dynamicBoolArray; function testArray() public { // Allocate memory for 8 elements to the dynamic bool storage array dynamicBoolArray = new bool[](8); // Allocate memory and initialize elements in the int array // Explicit conversion is needed from uint8 to int8 dynamicIntArray = [int8(1), 2, 3]; // This will work fine, since we are inside a function uint8[] memory memoryArray; // A Dynamic memory array // Allocation with assignment not allowed for dynamic memory arrays // memoryArray = [1,2,3]; uint8[] memory dynamicMemoryArray; // A Dynamic memory array // Assignment of dynamic NOT allowed //dynamicMemoryArray = [uint8(1),2]; memoryArray = new uint8[](8); // push() not allowed for memory array // memoryArray.push(1); // memoryArray.length=6; /** Examples of array initialization with assignment below */ // Static storage array assignment is OK // Compile time size check is carried out // so assignment to [1,2,3,4] will fail below staticIntArray = [1, 2, 3]; // Static memory array uint256[2] memory staticMemoryArray; // This is allowed - make sure the type is matching // staticMemoryArray is of type uint staticMemoryArray = [uint256(1), 2]; // This is allowed staticMemoryArray[0] = 0; staticMemoryArray[1] = 1; dynamicMemoryArray[0] = 1; dynamicMemoryArray[1] = 2; } //1. storage arrays //2. memory arrays //3. array arguments and return arrays from function //1. uint256[] myArray; // we can do crud. function arr() external { myArray.push(2); myArray.push(3); // update myArray[1]; // read myArray[0] = 20; // update delete myArray[1]; // delete will not change the length of array it will assign the element to 0 for (uint256 i = 0; i < myArray.length; i++) { myArray[i]; } // storage array cvan be divided into two categories // above one is dynamic sized array // if I declare fixed length array //uint256[2] storage Array = [1, 3]; // i will loose access to .push method } //2. memory arrays // these arrays are not stored inside the blockchain. function bar() external { uint256[] memory newArray = new uint256[](10); newArray[0] = 10; newArray[1] = 20; newArray[0]; delete newArray[5]; } //3. arrays in fucntion function yeah(uint256[] memory mtArg) internal returns (uint256[] memory) {} }
Allocate memory for 8 elements to the dynamic bool storage array Allocate memory and initialize elements in the int array Explicit conversion is needed from uint8 to int8 This will work fine, since we are inside a function Allocation with assignment not allowed for dynamic memory arrays memoryArray = [1,2,3]; Assignment of dynamic NOT alloweddynamicMemoryArray = [uint8(1),2]; push() not allowed for memory array memoryArray.push(1); memoryArray.length=6; Static storage array assignment is OK Compile time size check is carried out so assignment to [1,2,3,4] will fail below Static memory array This is allowed - make sure the type is matching staticMemoryArray is of type uint This is allowed
function testArray() public { dynamicBoolArray = new bool[](8); dynamicIntArray = [int8(1), 2, 3]; memoryArray = new uint8[](8); staticIntArray = [1, 2, 3]; uint256[2] memory staticMemoryArray; staticMemoryArray = [uint256(1), 2]; staticMemoryArray[0] = 0; staticMemoryArray[1] = 1; dynamicMemoryArray[0] = 1; dynamicMemoryArray[1] = 2; }
13,021,802
pragma solidity ^0.5.0; import "../helpers/openzeppelin-solidity/math/SafeMath.sol"; import "../helpers/openzeppelin-solidity/token/ERC20/IERC20.sol"; import "../modules/Countdown.sol"; import "../modules/Griefing.sol"; import "../modules/EventMetadata.sol"; import "../modules/Operated.sol"; import "../modules/Template.sol"; /* Immediately engage with specific buyer * - Stake can be increased at any time. * - Counterparty can greif the staker at predefined ratio. * * NOTE: * - This top level contract should only perform access control and state transitions * */ contract SimpleGriefing is Griefing, EventMetadata, Operated, Template { using SafeMath for uint256; Data private _data; struct Data { address staker; address counterparty; } event Initialized(address operator, address staker, address counterparty, uint256 ratio, Griefing.RatioType ratioType, bytes metadata); function initialize( address operator, address staker, address counterparty, uint256 ratio, Griefing.RatioType ratioType, bytes memory metadata ) public initializeTemplate() { // set storage values _data.staker = staker; _data.counterparty = counterparty; // set operator if (operator != address(0)) { Operated._setOperator(operator); Operated._activateOperator(); } // set griefing ratio Griefing._setRatio(staker, ratio, ratioType); // set metadata if (metadata.length != 0) { EventMetadata._setMetadata(metadata); } // log initialization params emit Initialized(operator, staker, counterparty, ratio, ratioType, metadata); } // state functions function setMetadata(bytes memory metadata) public { // restrict access require(isStaker(msg.sender) || Operated.isActiveOperator(msg.sender), "only staker or active operator"); // update metadata EventMetadata._setMetadata(metadata); } function increaseStake(uint256 currentStake, uint256 amountToAdd) public { // restrict access require(isStaker(msg.sender) || Operated.isActiveOperator(msg.sender), "only staker or active operator"); // add stake Staking._addStake(_data.staker, msg.sender, currentStake, amountToAdd); } function reward(uint256 currentStake, uint256 amountToAdd) public { // restrict access require(isCounterparty(msg.sender) || Operated.isActiveOperator(msg.sender), "only counterparty or active operator"); // add stake Staking._addStake(_data.staker, msg.sender, currentStake, amountToAdd); } function punish(uint256 currentStake, uint256 punishment, bytes memory message) public returns (uint256 cost) { // restrict access require(isCounterparty(msg.sender) || Operated.isActiveOperator(msg.sender), "only counterparty or active operator"); // execute griefing cost = Griefing._grief(msg.sender, _data.staker, currentStake, punishment, message); } function releaseStake(uint256 currentStake, uint256 amountToRelease) public { // restrict access require(isCounterparty(msg.sender) || Operated.isActiveOperator(msg.sender), "only counterparty or active operator"); // release stake back to the staker Staking._takeStake(_data.staker, _data.staker, currentStake, amountToRelease); } function transferOperator(address operator) public { // restrict access require(Operated.isActiveOperator(msg.sender), "only active operator"); // transfer operator Operated._transferOperator(operator); } function renounceOperator() public { // restrict access require(Operated.isActiveOperator(msg.sender), "only active operator"); // transfer operator Operated._renounceOperator(); } // view functions function isStaker(address caller) public view returns (bool validity) { validity = (caller == _data.staker); } function isCounterparty(address caller) public view returns (bool validity) { validity = (caller == _data.counterparty); } }
restrict access release stake back to the staker
function releaseStake(uint256 currentStake, uint256 amountToRelease) public { require(isCounterparty(msg.sender) || Operated.isActiveOperator(msg.sender), "only counterparty or active operator"); Staking._takeStake(_data.staker, _data.staker, currentStake, amountToRelease); }
5,403,015
// Sources flattened with hardhat v2.0.5 https://hardhat.org // File deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @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 deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.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 IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File interfaces/curve/ICurveGauge.sol pragma solidity >=0.5.0 <0.8.0; interface ICurveGauge { function deposit(uint256 _value) external; function deposit(uint256 _value, address addr) external; function balanceOf(address arg0) external view returns (uint256); function withdraw(uint256 _value) external; function withdraw(uint256 _value, bool claim_rewards) external; function claim_rewards() external; function claim_rewards(address addr) external; function claimable_tokens(address addr) external view returns (uint256); function claimable_reward(address addr) external view returns (uint256); function integrate_fraction(address arg0) external view returns (uint256); } // File interfaces/curve/ICurveMintr.sol pragma solidity >=0.5.0 <0.8.0; interface ICurveMintr { function mint(address) external; function minted(address arg0, address arg1) external view returns (uint256); } // File interfaces/curve/ICurveFi.sol pragma solidity >=0.5.0 <0.8.0; interface ICurveFi { function get_virtual_price() external view returns (uint256 out); function add_liquidity( // renbtc/tbtc pool uint256[2] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // sBTC pool uint256[3] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // bUSD pool uint256[4] calldata amounts, uint256 min_mint_amount ) external; function get_dy( int128 i, int128 j, uint256 dx ) external returns (uint256 out); function get_dy_underlying( int128 i, int128 j, uint256 dx ) external returns (uint256 out); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy, uint256 deadline ) external; function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy, uint256 deadline ) external; function remove_liquidity( uint256 _amount, uint256 deadline, uint256[2] calldata min_amounts ) external; function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 deadline) external; function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) external; function remove_liquidity_imbalance(uint256[4] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 _min_amount ) external; function commit_new_parameters( int128 amplification, int128 new_fee, int128 new_admin_fee ) external; function apply_new_parameters() external; function revert_new_parameters() external; function commit_transfer_ownership(address _owner) external; function apply_transfer_ownership() external; function revert_transfer_ownership() external; function withdraw_admin_fees() external; function coins(int128 arg0) external returns (address out); function underlying_coins(int128 arg0) external returns (address out); function balances(int128 arg0) external returns (uint256 out); function A() external returns (int128 out); function fee() external returns (int128 out); function admin_fee() external returns (int128 out); function owner() external returns (address out); function admin_actions_deadline() external returns (uint256 out); function transfer_ownership_deadline() external returns (uint256 out); function future_A() external returns (int128 out); function future_fee() external returns (int128 out); function future_admin_fee() external returns (int128 out); function future_owner() external returns (address out); function calc_withdraw_one_coin(uint256 _token_amount, int128 _i) external view returns (uint256 out); } // File interfaces/curve/ICurveExchange.sol pragma solidity >=0.6.0; interface ICurveExchange { function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function get_dy( int128, int128 j, uint256 dx ) external view returns (uint256); function calc_token_amount(uint256[2] calldata amounts, bool deposit) external view returns (uint256 amount); function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity(uint256 _amount, uint256[2] calldata min_amounts) external; function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity_one_coin( uint256 _token_amounts, int128 i, uint256 min_amount ) external; } interface ICurveRegistryAddressProvider { function get_address(uint256 id) external returns (address); } interface ICurveRegistryExchange { function get_best_rate( address from, address to, uint256 amount ) external view returns (address, uint256); function exchange( address pool, address from, address to, uint256 amount, uint256 expected, address receiver ) external payable returns (uint256); } // File deps/@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @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); } } // File deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol pragma solidity >=0.4.24 <0.7.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 deps/@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.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 PausableUpgradeable is Initializable, ContextUpgradeable { /** * @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. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File interfaces/uniswap/IUniswapRouterV2.sol pragma solidity >=0.5.0 <0.8.0; interface IUniswapRouterV2 { function factory() external view returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // File interfaces/badger/IController.sol pragma solidity >=0.5.0 <0.8.0; interface IController { function withdraw(address, uint256) external; function strategies(address) external view returns (address); function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); } // File interfaces/badger/IStrategy.sol pragma solidity >=0.5.0 <0.8.0; interface IStrategy { function want() external view returns (address); function deposit() external; // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address) external returns (uint256 balance); // Controller | Vault role - withdraw should always return to Vault function withdraw(uint256) external; // Controller | Vault role - withdraw should always return to Vault function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function getName() external pure returns (string memory); function setStrategist(address _strategist) external; function setWithdrawalFee(uint256 _withdrawalFee) external; function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external; function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external; function setGovernance(address _governance) external; function setController(address _controller) external; function tend() external; function harvest() external; } // File contracts/badger-sett/SettAccessControl.sol pragma solidity ^0.6.11; /* Common base for permissioned roles throughout Sett ecosystem */ contract SettAccessControl is Initializable { address public governance; address public strategist; address public keeper; // ===== MODIFIERS ===== function _onlyGovernance() internal view { require(msg.sender == governance, "onlyGovernance"); } function _onlyGovernanceOrStrategist() internal view { require(msg.sender == strategist || msg.sender == governance, "onlyGovernanceOrStrategist"); } function _onlyAuthorizedActors() internal view { require(msg.sender == keeper || msg.sender == governance, "onlyAuthorizedActors"); } // ===== PERMISSIONED ACTIONS ===== /// @notice Change strategist address /// @notice Can only be changed by governance itself function setStrategist(address _strategist) external { _onlyGovernance(); strategist = _strategist; } /// @notice Change keeper address /// @notice Can only be changed by governance itself function setKeeper(address _keeper) external { _onlyGovernance(); keeper = _keeper; } /// @notice Change governance address /// @notice Can only be changed by governance itself function setGovernance(address _governance) public { _onlyGovernance(); governance = _governance; } uint256[50] private __gap; } // File contracts/badger-sett/strategies/BaseStrategy.sol pragma solidity ^0.6.11; /* ===== Badger Base Strategy ===== Common base class for all Sett strategies Changelog V1.1 - Verify amount unrolled from strategy positions on withdraw() is within a threshold relative to the requested amount as a sanity check - Add version number which is displayed with baseStrategyVersion(). If a strategy does not implement this function, it can be assumed to be 1.0 V1.2 - Remove idle want handling from base withdraw() function. This should be handled as the strategy sees fit in _withdrawSome() */ abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; event Withdraw(uint256 amount); event WithdrawAll(uint256 balance); event WithdrawOther(address token, uint256 amount); event SetStrategist(address strategist); event SetGovernance(address governance); event SetController(address controller); event SetWithdrawalFee(uint256 withdrawalFee); event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist); event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance); event Harvest(uint256 harvested, uint256 indexed blockNumber); event Tend(uint256 tended); address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token uint256 public performanceFeeGovernance; uint256 public performanceFeeStrategist; uint256 public withdrawalFee; uint256 public constant MAX_FEE = 10000; address public constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap Dex address public controller; address public guardian; uint256 public withdrawalMaxDeviationThreshold; function __BaseStrategy_init( address _governance, address _strategist, address _controller, address _keeper, address _guardian ) public initializer whenNotPaused { __Pausable_init(); governance = _governance; strategist = _strategist; keeper = _keeper; controller = _controller; guardian = _guardian; withdrawalMaxDeviationThreshold = 50; } // ===== Modifiers ===== function _onlyController() internal view { require(msg.sender == controller, "onlyController"); } function _onlyAuthorizedActorsOrController() internal view { require(msg.sender == keeper || msg.sender == governance || msg.sender == controller, "onlyAuthorizedActorsOrController"); } function _onlyAuthorizedPausers() internal view { require(msg.sender == guardian || msg.sender == governance, "onlyPausers"); } /// ===== View Functions ===== function baseStrategyVersion() public view returns (string memory) { return "1.2"; } /// @notice Get the balance of want held idle in the Strategy function balanceOfWant() public view returns (uint256) { return IERC20Upgradeable(want).balanceOf(address(this)); } /// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions. function balanceOf() public virtual view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function isTendable() public virtual view returns (bool) { return false; } /// ===== Permissioned Actions: Governance ===== function setGuardian(address _guardian) external { _onlyGovernance(); guardian = _guardian; } function setWithdrawalFee(uint256 _withdrawalFee) external { _onlyGovernance(); require(_withdrawalFee <= MAX_FEE, "base-strategy/excessive-withdrawal-fee"); withdrawalFee = _withdrawalFee; } function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external { _onlyGovernance(); require(_performanceFeeStrategist <= MAX_FEE, "base-strategy/excessive-strategist-performance-fee"); performanceFeeStrategist = _performanceFeeStrategist; } function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external { _onlyGovernance(); require(_performanceFeeGovernance <= MAX_FEE, "base-strategy/excessive-governance-performance-fee"); performanceFeeGovernance = _performanceFeeGovernance; } function setController(address _controller) external { _onlyGovernance(); controller = _controller; } function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external { _onlyGovernance(); require(_threshold <= MAX_FEE, "base-strategy/excessive-max-deviation-threshold"); withdrawalMaxDeviationThreshold = _threshold; } function deposit() public virtual whenNotPaused { _onlyAuthorizedActorsOrController(); uint256 _want = IERC20Upgradeable(want).balanceOf(address(this)); if (_want > 0) { _deposit(_want); } _postDeposit(); } // ===== Permissioned Actions: Controller ===== /// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal function withdrawAll() external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _withdrawAll(); _transferToVault(IERC20Upgradeable(want).balanceOf(address(this))); } /// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary /// @notice Processes withdrawal fee if present /// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); // Withdraw from strategy positions, typically taking from any idle want first. _withdrawSome(_amount); uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this)); // Sanity check: Ensure we were able to retrieve sufficent want from strategy positions // If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw); // Require that difference between expected and actual values is less than the deviation threshold percentage require(diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "base-strategy/withdraw-exceed-max-deviation-threshold"); } // Return the amount actually withdrawn if less than amount requested uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount); // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_toWithdraw); // Transfer remaining to Vault to handle withdrawal _transferToVault(_toWithdraw.sub(_fee)); } // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address _asset) external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _onlyNotProtectedTokens(_asset); balance = IERC20Upgradeable(_asset).balanceOf(address(this)); IERC20Upgradeable(_asset).safeTransfer(controller, balance); } /// ===== Permissioned Actions: Authoized Contract Pausers ===== function pause() external { _onlyAuthorizedPausers(); _pause(); } function unpause() external { _onlyGovernance(); _unpause(); } /// ===== Internal Helper Functions ===== /// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient /// @return The withdrawal fee that was taken function _processWithdrawalFee(uint256 _amount) internal returns (uint256) { if (withdrawalFee == 0) { return 0; } uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE); IERC20Upgradeable(want).safeTransfer(IController(controller).rewards(), fee); return fee; } /// @dev Helper function to process an arbitrary fee /// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient /// @return The fee that was taken function _processFee( address token, uint256 amount, uint256 feeBps, address recipient ) internal returns (uint256) { if (feeBps == 0) { return 0; } uint256 fee = amount.mul(feeBps).div(MAX_FEE); IERC20Upgradeable(token).safeTransfer(recipient, fee); return fee; } /// @dev Reset approval and approve exact amount function _safeApproveHelper( address token, address recipient, uint256 amount ) internal { IERC20Upgradeable(token).safeApprove(recipient, 0); IERC20Upgradeable(token).safeApprove(recipient, amount); } function _transferToVault(uint256 _amount) internal { address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20Upgradeable(want).safeTransfer(_vault, _amount); } /// @notice Swap specified balance of given token on Uniswap with given path function _swap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForTokens(balance, 0, path, address(this), now); } function _swapEthIn(uint256 balance, address[] memory path) internal { IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); } function _swapEthOut( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForETH(balance, 0, path, address(this), now); } /// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible function _add_max_liquidity_uniswap(address token0, address token1) internal virtual { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, uniswap, _token0Balance); _safeApproveHelper(token1, uniswap, _token1Balance); IUniswapRouterV2(uniswap).addLiquidity(token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp); } /// @notice Utility function to diff two numbers, expects higher value in first position function _diff(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "diff/expected-higher-number-in-first-position"); return a.sub(b); } // ===== Abstract Functions: To be implemented by specific Strategies ===== /// @dev Internal deposit logic to be implemented by Stratgies function _deposit(uint256 _want) internal virtual; function _postDeposit() internal virtual { //no-op by default } /// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther() function _onlyNotProtectedTokens(address _asset) internal virtual; function getProtectedTokens() external virtual view returns (address[] memory); /// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible function _withdrawAll() internal virtual; /// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible. /// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this function _withdrawSome(uint256 _amount) internal virtual returns (uint256); /// @dev Realize returns from positions /// @dev Returns can be reinvested into positions, or distributed in another fashion /// @dev Performance fees should also be implemented in this function /// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL // function harvest() external virtual; /// @dev User-friendly name for this strategy for purposes of convenient reading function getName() external virtual pure returns (string memory); /// @dev Balance of want currently held in strategy positions function balanceOfPool() public virtual view returns (uint256); uint256[49] private __gap; } // File interfaces/unitprotocol/IUnitProtocol.sol pragma solidity 0.6.12; interface IUnitVaultParameters { function tokenDebtLimit(address asset) external view returns (uint256); } interface IUnitVault { function calculateFee( address asset, address user, uint256 amount ) external view returns (uint256); function getTotalDebt(address asset, address user) external view returns (uint256); function debts(address asset, address user) external view returns (uint256); function collaterals(address asset, address user) external view returns (uint256); function tokenDebts(address asset) external view returns (uint256); } interface IUnitCDPManager { function exit( address asset, uint256 assetAmount, uint256 usdpAmount ) external returns (uint256); function join( address asset, uint256 assetAmount, uint256 usdpAmount ) external; function oracleRegistry() external view returns (address); } interface IUnitUsdOracle { // returns Q112-encoded value // returned value 10**18 * 2**112 is $1 function assetToUsd(address asset, uint amount) external view returns (uint); } interface IUnitOracleRegistry { function oracleByAsset(address asset) external view returns (address); } // File interfaces/chainlink/IChainlink.sol pragma solidity 0.6.12; interface IChainlinkAggregator { function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File contracts/badger-sett/strategies/unitprotocol/StrategyUnitProtocolMeta.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract StrategyUnitProtocolMeta is BaseStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; // Unit Protocol module: https://github.com/unitprotocol/core/blob/master/CONTRACTS.md address public constant cdpMgr01 = 0x0e13ab042eC5AB9Fc6F43979406088B9028F66fA; address public constant unitVault = 0xb1cFF81b9305166ff1EFc49A129ad2AfCd7BCf19; address public constant unitVaultParameters = 0xB46F8CF42e504Efe8BEf895f848741daA55e9f1D; address public constant debtToken = 0x1456688345527bE1f37E9e627DA0837D6f08C925; address public constant eth_usd = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419; bool public useUnitUsdOracle = true; // sub-strategy related constants address public collateral; uint256 public collateralDecimal = 1e18; address public unitOracle; uint256 public collateralPriceDecimal = 1; bool public collateralPriceEth = false; // configurable minimum collateralization percent this strategy would hold for CDP uint256 public minRatio = 200; // collateralization percent buffer in CDP debt actions uint256 public ratioBuff = 200; uint256 public constant ratioBuffMax = 10000; uint public constant Q112 = 2 ** 112; // **** Modifiers **** // function _onlyCDPInUse() internal view { uint256 collateralAmt = getCollateralBalance(); require(collateralAmt > 0, "!zeroCollateral"); uint256 debtAmt = getDebtBalance(); require(debtAmt > 0, "!zeroDebt"); } // **** Getters **** function getCollateralBalance() public view returns (uint256) { return IUnitVault(unitVault).collaterals(collateral, address(this)); } function getDebtBalance() public view returns (uint256) { return IUnitVault(unitVault).getTotalDebt(collateral, address(this)); } function getDebtWithoutFee() public view returns (uint256) { return IUnitVault(unitVault).debts(collateral, address(this)); } function debtLimit() public view returns (uint256) { return IUnitVaultParameters(unitVaultParameters).tokenDebtLimit(collateral); } function debtUsed() public view returns (uint256) { return IUnitVault(unitVault).tokenDebts(collateral); } /// @dev Balance of want currently held in strategy positions function balanceOfPool() public override view returns (uint256) { return getCollateralBalance(); } function collateralValue(uint256 collateralAmt) public view returns (uint256) { uint256 collateralPrice = getLatestCollateralPrice(); return collateralAmt.mul(collateralPrice).mul(1e18).div(collateralDecimal).div(collateralPriceDecimal); // debtToken in 1e18 decimal } function currentRatio() public view returns (uint256) { _onlyCDPInUse(); uint256 collateralAmt = collateralValue(getCollateralBalance()).mul(100); uint256 debtAmt = getDebtBalance(); return collateralAmt.div(debtAmt); } // if borrow is true (for addCollateralAndBorrow): return (maxDebt - currentDebt) if positive value, otherwise return 0 // if borrow is false (for repayAndRedeemCollateral): return (currentDebt - maxDebt) if positive value, otherwise return 0 function calculateDebtFor(uint256 collateralAmt, bool borrow) public view returns (uint256) { uint256 maxDebt = collateralAmt > 0? collateralValue(collateralAmt).mul(ratioBuffMax).div(_getBufferedMinRatio(ratioBuffMax)) : 0; uint256 debtAmt = getDebtBalance(); uint256 debt = 0; if (borrow && maxDebt >= debtAmt) { debt = maxDebt.sub(debtAmt); } else if (!borrow && debtAmt >= maxDebt) { debt = debtAmt.sub(maxDebt); } return (debt > 0) ? debt : 0; } function _getBufferedMinRatio(uint256 _multiplier) internal view returns (uint256) { require(ratioBuffMax > 0, "!ratioBufferMax"); require(minRatio > 0, "!minRatio"); return minRatio.mul(_multiplier).mul(ratioBuffMax.add(ratioBuff)).div(ratioBuffMax).div(100); } function borrowableDebt() public view returns (uint256) { uint256 collateralAmt = getCollateralBalance(); return calculateDebtFor(collateralAmt, true); } function requiredPaidDebt(uint256 _redeemCollateralAmt) public view returns (uint256) { uint256 totalCollateral = getCollateralBalance(); uint256 collateralAmt = _redeemCollateralAmt >= totalCollateral? 0 : totalCollateral.sub(_redeemCollateralAmt); return calculateDebtFor(collateralAmt, false); } // **** sub-strategy implementation **** function _depositUSDP(uint256 _usdpAmt) internal virtual; function _withdrawUSDP(uint256 _usdpAmt) internal virtual; // **** Oracle (using chainlink) **** function getLatestCollateralPrice() public view returns (uint256) { if (useUnitUsdOracle){ address unitOracleRegistry = IUnitCDPManager(cdpMgr01).oracleRegistry(); address unitUsdOracle = IUnitOracleRegistry(unitOracleRegistry).oracleByAsset(collateral); uint usdPriceInQ122 = IUnitUsdOracle(unitUsdOracle).assetToUsd(collateral, collateralDecimal); return uint256(usdPriceInQ122 / Q112).mul(collateralPriceDecimal).div(1e18);// usd price from unit protocol oracle in 1e18 decimal } require(unitOracle != address(0), "!_collateralOracle"); (, int256 price, , , ) = IChainlinkAggregator(unitOracle).latestRoundData(); if (price > 0) { if (collateralPriceEth) { (, int256 ethPrice, , , ) = IChainlinkAggregator(eth_usd).latestRoundData(); // eth price from chainlink in 1e8 decimal return uint256(price).mul(collateralPriceDecimal).mul(uint256(ethPrice)).div(1e8).div(collateralPriceEth ? 1e18 : 1); } else{ return uint256(price).mul(collateralPriceDecimal).div(1e8); } } else { return 0; } } // **** Setters **** function setMinRatio(uint256 _minRatio) external { _onlyGovernance(); minRatio = _minRatio; } function setRatioBuff(uint256 _ratioBuff) external { _onlyGovernance(); ratioBuff = _ratioBuff; } function setUseUnitUsdOracle(bool _useUnitUsdOracle) external { _onlyGovernance(); useUnitUsdOracle = _useUnitUsdOracle; } // **** Unit Protocol CDP actions **** function addCollateralAndBorrow(uint256 _collateralAmt, uint256 _usdpAmt) internal { require(_usdpAmt.add(debtUsed()) < debtLimit(), "!exceedLimit"); _safeApproveHelper(collateral, unitVault, _collateralAmt); IUnitCDPManager(cdpMgr01).join(collateral, _collateralAmt, _usdpAmt); } function repayAndRedeemCollateral(uint256 _collateralAmt, uint256 _usdpAmt) internal { _safeApproveHelper(debtToken, unitVault, _usdpAmt); IUnitCDPManager(cdpMgr01).exit(collateral, _collateralAmt, _usdpAmt); } // **** State Mutation functions **** function keepMinRatio() external { _onlyCDPInUse(); _onlyAuthorizedActorsOrController(); uint256 requiredPaidback = requiredPaidDebt(0); if (requiredPaidback > 0) { _withdrawUSDP(requiredPaidback); uint256 _currentDebtVal = IERC20Upgradeable(debtToken).balanceOf(address(this)); uint256 _actualPaidDebt = _currentDebtVal; uint256 _totalDebtWithoutFee = getDebtWithoutFee(); uint256 _fee = getDebtBalance().sub(_totalDebtWithoutFee); require(_actualPaidDebt > _fee, "!notEnoughForFee"); _actualPaidDebt = _actualPaidDebt.sub(_fee); // unit protocol will charge fee first _actualPaidDebt = _capMaxDebtPaid(_actualPaidDebt, _totalDebtWithoutFee); require(_currentDebtVal >= _actualPaidDebt.add(_fee), "!notEnoughRepayment"); repayAndRedeemCollateral(0, _actualPaidDebt); } } /// @dev Internal deposit logic to be implemented by Strategies function _deposit(uint256 _want) internal override { if (_want > 0) { uint256 _newDebt = calculateDebtFor(_want.add(getCollateralBalance()), true); if (_newDebt > 0) { addCollateralAndBorrow(_want, _newDebt); uint256 wad = IERC20Upgradeable(debtToken).balanceOf(address(this)); _depositUSDP(_newDebt > wad ? wad : _newDebt); } } } // to avoid repay all debt resulting to close the CDP unexpectedly function _capMaxDebtPaid(uint256 _actualPaidDebt, uint256 _totalDebtWithoutFee) internal view returns (uint256) { uint256 _maxDebtToRepay = _totalDebtWithoutFee.sub(ratioBuffMax); return _actualPaidDebt >= _maxDebtToRepay ? _maxDebtToRepay : _actualPaidDebt; } /// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible. /// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this function _withdrawSome(uint256 _amount) internal override returns (uint256) { if (_amount == 0) { return _amount; } uint256 requiredPaidback = requiredPaidDebt(_amount); if (requiredPaidback > 0) { _withdrawUSDP(requiredPaidback); } bool _fullWithdraw = _amount >= balanceOfPool(); uint256 _wantBefore = IERC20Upgradeable(want).balanceOf(address(this)); if (!_fullWithdraw) { uint256 _currentDebtVal = IERC20Upgradeable(debtToken).balanceOf(address(this)); uint256 _actualPaidDebt = _currentDebtVal; uint256 _totalDebtWithoutFee = getDebtWithoutFee(); uint256 _fee = getDebtBalance().sub(_totalDebtWithoutFee); require(_actualPaidDebt > _fee, "!notEnoughForFee"); _actualPaidDebt = _actualPaidDebt.sub(_fee); // unit protocol will charge fee first _actualPaidDebt = _capMaxDebtPaid(_actualPaidDebt, _totalDebtWithoutFee); require(_currentDebtVal >= _actualPaidDebt.add(_fee), "!notEnoughRepayment"); repayAndRedeemCollateral(_amount, _actualPaidDebt); } else { require(IERC20Upgradeable(debtToken).balanceOf(address(this)) >= getDebtBalance(), "!notEnoughFullRepayment"); repayAndRedeemCollateral(_amount, getDebtBalance()); require(getDebtBalance() == 0, "!leftDebt"); require(getCollateralBalance() == 0, "!leftCollateral"); } uint256 _wantAfter = IERC20Upgradeable(want).balanceOf(address(this)); return _wantAfter.sub(_wantBefore); } /// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible function _withdrawAll() internal override { _withdrawSome(balanceOfPool()); } } // File contracts/badger-sett/strategies/unitprotocol/StrategyUnitProtocolRenbtc.sol pragma solidity 0.6.12; contract StrategyUnitProtocolRenbtc is StrategyUnitProtocolMeta { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; // strategy specific address public constant renbtc_collateral = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D; uint256 public constant renbtc_collateral_decimal = 1e8; address public constant renbtc_oracle = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c; uint256 public constant renbtc_price_decimal = 1; bool public constant renbtc_price_eth = false; // yield-farming in usdp-3crv pool address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant usdp3crv = 0x7Eb40E450b9655f4B3cC4259BCC731c63ff55ae6; address public constant usdp = 0x1456688345527bE1f37E9e627DA0837D6f08C925; address public constant usdp_gauge = 0x055be5DDB7A925BfEF3417FC157f53CA77cA7222; address public constant curvePool = 0x42d7025938bEc20B69cBae5A77421082407f053A; address public constant mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // slippage protection for one-sided ape in/out uint256 public slippageProtectionIn = 50; // max 0.5% uint256 public slippageProtectionOut = 50; // max 0.5% uint256 public keepCRV; event RenBTCStratHarvest( uint256 crvHarvested, uint256 keepCrv, uint256 crvRecycled, uint256 wantProcessed, uint256 wantDeposited, uint256 governancePerformanceFee, uint256 strategistPerformanceFee ); struct HarvestData { uint256 crvHarvested; uint256 keepCrv; uint256 crvRecycled; uint256 wantProcessed; uint256 wantDeposited; uint256 governancePerformanceFee; uint256 strategistPerformanceFee; } function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, address[1] memory _wantConfig, uint256[4] memory _feeConfig ) public initializer { __BaseStrategy_init(_governance, _strategist, _controller, _keeper, _guardian); require(_wantConfig[0] == renbtc_collateral, "!want"); want = _wantConfig[0]; collateral = renbtc_collateral; collateralDecimal = renbtc_collateral_decimal; unitOracle = renbtc_oracle; collateralPriceDecimal = renbtc_price_decimal; collateralPriceEth = renbtc_price_eth; performanceFeeGovernance = _feeConfig[0]; performanceFeeStrategist = _feeConfig[1]; withdrawalFee = _feeConfig[2]; keepCRV = _feeConfig[3]; minRatio = 200; ratioBuff = 200; } // **** Setters **** function setSlippageProtectionIn(uint256 _slippage) external { _onlyGovernance(); slippageProtectionIn = _slippage; } function setSlippageProtectionOut(uint256 _slippage) external { _onlyGovernance(); slippageProtectionOut = _slippage; } function setKeepCRV(uint256 _keepCRV) external { _onlyGovernance(); keepCRV = _keepCRV; } // **** State Mutation functions **** function getHarvestable() external view returns (uint256) { return ICurveGauge(usdp_gauge).claimable_tokens(address(this)); } function harvest() external whenNotPaused returns (HarvestData memory) { _onlyAuthorizedActors(); HarvestData memory harvestData; uint256 _before = IERC20Upgradeable(want).balanceOf(address(this)); uint256 _beforeCrv = IERC20Upgradeable(crv).balanceOf(address(this)); // Harvest from Gauge ICurveMintr(mintr).mint(usdp_gauge); uint256 _afterCrv = IERC20Upgradeable(crv).balanceOf(address(this)); harvestData.crvHarvested = _afterCrv.sub(_beforeCrv); uint256 _crv = _afterCrv; // Transfer CRV to keep to Rewards harvestData.keepCrv = _crv.mul(keepCRV).div(MAX_FEE); IERC20Upgradeable(crv).safeTransfer(IController(controller).rewards(), harvestData.keepCrv); harvestData.crvRecycled = _crv.sub(harvestData.keepCrv); if (harvestData.crvRecycled > 0) { address[] memory path = new address[](3); path[0] = crv; path[1] = weth; path[2] = want; _swap(crv, harvestData.crvRecycled, path); } // Take fees from want increase, and deposit remaining into Gauge harvestData.wantProcessed = IERC20Upgradeable(want).balanceOf(address(this)); if (harvestData.wantProcessed > 0) { (harvestData.governancePerformanceFee, harvestData.strategistPerformanceFee) = _processPerformanceFees(harvestData.wantProcessed); // Reinvest remaining want harvestData.wantDeposited = IERC20Upgradeable(want).balanceOf(address(this)); if (harvestData.wantDeposited > 0) { _deposit(harvestData.wantDeposited); } } emit RenBTCStratHarvest( harvestData.crvHarvested, harvestData.keepCrv, harvestData.crvRecycled, harvestData.wantProcessed, harvestData.wantDeposited, harvestData.governancePerformanceFee, harvestData.strategistPerformanceFee ); emit Harvest(harvestData.wantProcessed.sub(_before), block.number); return harvestData; } function _processPerformanceFees(uint256 _amount) internal returns (uint256 governancePerformanceFee, uint256 strategistPerformanceFee) { governancePerformanceFee = _processFee(want, _amount, performanceFeeGovernance, IController(controller).rewards()); strategistPerformanceFee = _processFee(want, _amount, performanceFeeStrategist, strategist); } function _depositUSDP(uint256 _usdpAmt) internal override { if (_usdpAmt > 0 && checkSlip(_usdpAmt)) { _safeApproveHelper(usdp, curvePool, _usdpAmt); uint256[2] memory amounts = [_usdpAmt, 0]; ICurveFi(curvePool).add_liquidity(amounts, 0); } uint256 _usdp3crv = IERC20Upgradeable(usdp3crv).balanceOf(address(this)); if (_usdp3crv > 0) { _safeApproveHelper(usdp3crv, usdp_gauge, _usdp3crv); ICurveGauge(usdp_gauge).deposit(_usdp3crv); } } function _withdrawUSDP(uint256 _usdpAmt) internal override { uint256 _requiredUsdp3crv = estimateRequiredUsdp3crv(_usdpAmt); _requiredUsdp3crv = _requiredUsdp3crv.mul(MAX_FEE.add(slippageProtectionOut)).div(MAX_FEE); // try to remove bit more uint256 _usdp3crv = IERC20Upgradeable(usdp3crv).balanceOf(address(this)); uint256 _withdrawFromGauge = _usdp3crv < _requiredUsdp3crv ? _requiredUsdp3crv.sub(_usdp3crv) : 0; if (_withdrawFromGauge > 0) { uint256 maxInGauge = ICurveGauge(usdp_gauge).balanceOf(address(this)); ICurveGauge(usdp_gauge).withdraw(maxInGauge < _withdrawFromGauge ? maxInGauge : _withdrawFromGauge); } _usdp3crv = IERC20Upgradeable(usdp3crv).balanceOf(address(this)); if (_usdp3crv > 0) { _requiredUsdp3crv = _requiredUsdp3crv > _usdp3crv ? _usdp3crv : _requiredUsdp3crv; uint256 maxSlippage = _requiredUsdp3crv.mul(MAX_FEE.sub(slippageProtectionOut)).div(MAX_FEE); _safeApproveHelper(usdp3crv, curvePool, _requiredUsdp3crv); ICurveFi(curvePool).remove_liquidity_one_coin(_requiredUsdp3crv, 0, maxSlippage); } } // **** Views **** function virtualPriceToWant() public view returns (uint256) { uint256 p = ICurveFi(curvePool).get_virtual_price(); require(p > 0, "!p"); return p; } function estimateRequiredUsdp3crv(uint256 _usdpAmt) public view returns (uint256) { return _usdpAmt.mul(1e18).div(virtualPriceToWant()); } function checkSlip(uint256 _usdpAmt) public view returns (bool) { uint256 expectedOut = _usdpAmt.mul(1e18).div(virtualPriceToWant()); uint256 maxSlip = expectedOut.mul(MAX_FEE.sub(slippageProtectionIn)).div(MAX_FEE); uint256[2] memory amounts = [_usdpAmt, 0]; return ICurveExchange(curvePool).calc_token_amount(amounts, true) >= maxSlip; } function usdpOfPool() public view returns (uint256) { uint256 _usdp3crv = IERC20Upgradeable(usdp3crv).balanceOf(address(this)); _usdp3crv = _usdp3crv.add(ICurveGauge(usdp_gauge).balanceOf(address(this))); return usdp3crvToUsdp(_usdp3crv); } function usdp3crvToUsdp(uint256 _usdp3crv) public view returns (uint256) { if (_usdp3crv == 0) { return 0; } // use underestimate of current assets. uint256 virtualOut = virtualPriceToWant().mul(_usdp3crv).div(1e18); // uint256 realOut = ICurveFi(curvePool).calc_withdraw_one_coin(_usdp3crv, 0); return virtualOut; // virtualOut > realOut? realOut : virtualOut; } /// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther() function _onlyNotProtectedTokens(address _asset) internal override { require(usdp3crv != _asset, "!usdp3crv"); require(usdp != _asset, "!usdp"); require(renbtc_collateral != _asset, "!usdp"); } function getProtectedTokens() external override view returns (address[] memory) { address[] memory protectedTokens = new address[](3); protectedTokens[0] = renbtc_collateral; protectedTokens[1] = usdp; protectedTokens[2] = usdp3crv; return protectedTokens; } /// @dev User-friendly name for this strategy for purposes of convenient reading function getName() external override pure returns (string memory) { return "StrategyUnitProtocolRenbtc"; } }
returns Q112-encoded value returned value 1018 2112 is $1
interface IUnitUsdOracle { function assetToUsd(address asset, uint amount) external view returns (uint); }
5,731,821
pragma solidity ^0.5.0; contract GasStation { enum TipoGas{Extra,Corriente} struct Vehicle{ address payable direccion; uint id; TipoGas tipo; uint cantidadSolicitada; uint montoConsignado; bool creado; } struct Gas { TipoGas typeGas; uint price; uint cantidadDisponible; bool creado; } struct Station { address payable direccion; uint id; uint Deposit; Gas[] fuels; //combustibles ofrecidos en la estacion mapping (uint => Vehicle) vehicles; //estaciones bool creado; } mapping (uint => Station) stations; //estaciones mapping (uint => uint) saldoStacion; //saldo disponible para ser retirado por la gasolinera event echo(); event valor(uint val); event viewGasInfo(uint id, string typeGas, uint price); event error(string error); event consignacionRealizada(TipoGas tipo, uint cantidadSolicitada, uint monto); event entregaCombustible(uint Vehiculo,uint cantidadSolicitada); modifier estacionNoExiste(uint id){ if(stations[id].creado){ revert(); } _; } //registro gas station function setStation(uint id,uint deposit) public { stations[id].direccion=msg.sender; stations[id].Deposit = deposit*1000000000000000000; stations[id].id=id; stations[id].creado=true; } //agregar gas a stacion function setStationFuel(uint id,TipoGas tipo, uint price, uint cantidadDisp) public { Gas memory gas = Gas(tipo, price*1000000000000000000,cantidadDisp,true); stations[id].fuels.push(gas); } //getGasInfo cantidad de Fuels function getStationGasInfo(uint idStation ) public view returns (uint,uint){ uint lengthFuels=0; if(stations[idStation].creado==true){ lengthFuels=stations[idStation].fuels.length; } return (stations[idStation].Deposit,lengthFuels); } //get fuel function getGasInfo(uint idStation, uint idfuel) public view returns (TipoGas, uint,uint) { return (stations[idStation].fuels[idfuel].typeGas, stations[idStation].fuels[idfuel].price,stations[idStation].fuels[idfuel].cantidadDisponible); } //enviar deposito function sendDeposit(uint idStation, uint idVehiculo, TipoGas tipo,uint cantidadSolicitada ) public payable { if(stations[idStation].creado==false || msg.value<stations[idStation].Deposit){ revert(); } stations[idStation].vehicles[idVehiculo].direccion=msg.sender; stations[idStation].vehicles[idVehiculo]. cantidadSolicitada=cantidadSolicitada; stations[idStation].vehicles[idVehiculo].tipo=tipo; stations[idStation].vehicles[idVehiculo].montoConsignado=msg.value; stations[idStation].vehicles[idVehiculo].creado=true; emit consignacionRealizada(tipo, cantidadSolicitada, msg.value); } //verificar deposito function verificarDeposit(uint idStation, uint idVehiculo) public view returns (bool){ return (stations[idStation].vehicles[idVehiculo].creado); } //enviar conbustible function sendFuel(uint _station,uint Vehiculo, uint fuel, uint cantidadSolicitada) public{ //verificar deposito, montoconsignado>precio*cant , gas disponible /*&& stations[_station].vehicles[Vehiculo].montoConsignado> stations[_station].fuels[fuel].price*cantidadSolicitada && stations[_station].fuels[fuel].cantidadDisponible> cantidadSolicitada*/ emit echo(); if(verificarDeposit(_station,Vehiculo)==true){ emit echo(); emit valor(stations[_station].fuels[fuel].price*cantidadSolicitada); stations[_station].direccion.transfer(stations[_station].fuels[fuel].price*cantidadSolicitada); emit valor(stations[_station].vehicles[Vehiculo].montoConsignado-(stations[_station].fuels[fuel].price*cantidadSolicitada)); stations[_station].vehicles[Vehiculo].direccion.transfer(stations[_station].vehicles[Vehiculo].montoConsignado-(stations[_station].fuels[fuel].price*cantidadSolicitada)); stations[_station].fuels[fuel].cantidadDisponible-=cantidadSolicitada; stations[_station].vehicles[Vehiculo].montoConsignado-=stations[_station].fuels[fuel].price*cantidadSolicitada; saldoStacion[_station]=stations[_station].fuels[fuel].price*cantidadSolicitada;//agregamos pago a estacion delete stations[_station].vehicles[Vehiculo]; emit entregaCombustible(Vehiculo,cantidadSolicitada); }else { revert(); } } function consultarSaldoEstacion(uint _station,uint Vehiculo) public view returns (uint){ return (stations[_station].vehicles[Vehiculo].montoConsignado); } function SaldoEstacion(uint _station) public view returns (uint){ return (saldoStacion[_station]); } }
enviar conbustibleverificar deposito, montoconsignado>preciocant , gas disponible&&
function sendFuel(uint _station,uint Vehiculo, uint fuel, uint cantidadSolicitada) public{ stations[_station].vehicles[Vehiculo].montoConsignado> stations[_station].fuels[fuel].price*cantidadSolicitada && stations[_station].fuels[fuel].cantidadDisponible> cantidadSolicitada*/ emit echo(); if(verificarDeposit(_station,Vehiculo)==true){ emit echo(); emit valor(stations[_station].fuels[fuel].price*cantidadSolicitada); stations[_station].direccion.transfer(stations[_station].fuels[fuel].price*cantidadSolicitada); emit valor(stations[_station].vehicles[Vehiculo].montoConsignado-(stations[_station].fuels[fuel].price*cantidadSolicitada)); stations[_station].vehicles[Vehiculo].direccion.transfer(stations[_station].vehicles[Vehiculo].montoConsignado-(stations[_station].fuels[fuel].price*cantidadSolicitada)); stations[_station].fuels[fuel].cantidadDisponible-=cantidadSolicitada; stations[_station].vehicles[Vehiculo].montoConsignado-=stations[_station].fuels[fuel].price*cantidadSolicitada; delete stations[_station].vehicles[Vehiculo]; emit entregaCombustible(Vehiculo,cantidadSolicitada); revert(); } }
5,394,474
pragma solidity ^0.4.18; /** * @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 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 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 Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title ERC721 interface * @dev see https://github.com/ethereum/eips/issues/721 */ contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; } /** * @title ERC721Token * Generic implementation for the required functionality of the ERC721 standard */ contract ERC721Token is ERC721 { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; // Mapping from token ID to owner mapping (uint256 => address) private tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private tokenApprovals; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) private ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private ownedTokensIndex; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return totalTokens; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { return ownedTokens[_owner].length; } /** * @dev Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function approvedFor(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @dev Approves another address to claim for the ownership of the given token ID * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (approvedFor(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; Approval(owner, _to, _tokenId); } } /** * @dev Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) public { require(isApprovedFor(msg.sender, _tokenId)); clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @dev Mint token function * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addToken(_to, _tokenId); Transfer(0x0, _to, _tokenId); } /** * @dev Burns a specific token * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal { if (approvedFor(_tokenId) != 0) { clearApproval(msg.sender, _tokenId); } removeToken(msg.sender, _tokenId); Transfer(msg.sender, 0x0, _tokenId); } /** * @dev Tells whether the msg.sender is approved for the given token ID or not * This function is not private so it can be extended in further implementations like the operatable ERC721 * @param _owner address of the owner to query the approval of * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) { return approvedFor(_tokenId) == _owner; } /** * @dev Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); clearApproval(_from, _tokenId); removeToken(_from, _tokenId); addToken(_to, _tokenId); Transfer(_from, _to, _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; Approval(_owner, 0, _tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * @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 addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = 0; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; totalTokens = totalTokens.sub(1); } } /** * @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]); // 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 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; } } /** * @title AccessDeposit * @dev Adds grant/revoke functions to the contract. */ contract AccessDeposit is Claimable { // Access for adding deposit. mapping(address => bool) private depositAccess; // Modifier for accessibility to add deposit. modifier onlyAccessDeposit { require(msg.sender == owner || depositAccess[msg.sender] == true); _; } // @dev Grant acess to deposit heroes. function grantAccessDeposit(address _address) onlyOwner public { depositAccess[_address] = true; } // @dev Revoke acess to deposit heroes. function revokeAccessDeposit(address _address) onlyOwner public { depositAccess[_address] = false; } } /** * @title AccessDeploy * @dev Adds grant/revoke functions to the contract. */ contract AccessDeploy is Claimable { // Access for deploying heroes. mapping(address => bool) private deployAccess; // Modifier for accessibility to deploy a hero on a location. modifier onlyAccessDeploy { require(msg.sender == owner || deployAccess[msg.sender] == true); _; } // @dev Grant acess to deploy heroes. function grantAccessDeploy(address _address) onlyOwner public { deployAccess[_address] = true; } // @dev Revoke acess to deploy heroes. function revokeAccessDeploy(address _address) onlyOwner public { deployAccess[_address] = false; } } /** * @title AccessMint * @dev Adds grant/revoke functions to the contract. */ contract AccessMint is Claimable { // Access for minting new tokens. mapping(address => bool) private mintAccess; // Modifier for accessibility to define new hero types. modifier onlyAccessMint { require(msg.sender == owner || mintAccess[msg.sender] == true); _; } // @dev Grant acess to mint heroes. function grantAccessMint(address _address) onlyOwner public { mintAccess[_address] = true; } // @dev Revoke acess to mint heroes. function revokeAccessMint(address _address) onlyOwner public { mintAccess[_address] = false; } } /** * @title Gold * @dev ERC20 Token that can be minted. */ contract Gold is StandardToken, Claimable, AccessMint { string public constant name = "Gold"; string public constant symbol = "G"; uint8 public constant decimals = 18; // Event that is fired when minted. event Mint( address indexed _to, uint256 indexed _tokenId ); // @dev Mint tokens with _amount to the address. function mint(address _to, uint256 _amount) onlyAccessMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } } /** * @title CryptoSaga Card * @dev ERC721 Token that repesents CryptoSaga's cards. * Buy consuming a card, players of CryptoSaga can get a heroe. */ contract CryptoSagaCard is ERC721Token, Claimable, AccessMint { string public constant name = "CryptoSaga Card"; string public constant symbol = "CARD"; // Rank of the token. mapping(uint256 => uint8) public tokenIdToRank; // The number of tokens ever minted. uint256 public numberOfTokenId; // The converter contract. CryptoSagaCardSwap private swapContract; // Event that should be fired when card is converted. event CardSwap(address indexed _by, uint256 _tokenId, uint256 _rewardId); // @dev Set the address of the contract that represents CryptoSaga Cards. function setCryptoSagaCardSwapContract(address _contractAddress) public onlyOwner { swapContract = CryptoSagaCardSwap(_contractAddress); } function rankOf(uint256 _tokenId) public view returns (uint8) { return tokenIdToRank[_tokenId]; } // @dev Mint a new card. function mint(address _beneficiary, uint256 _amount, uint8 _rank) onlyAccessMint public { for (uint256 i = 0; i < _amount; i++) { _mint(_beneficiary, numberOfTokenId); tokenIdToRank[numberOfTokenId] = _rank; numberOfTokenId ++; } } // @dev Swap this card for reward. // The card will be burnt. function swap(uint256 _tokenId) onlyOwnerOf(_tokenId) public returns (uint256) { require(address(swapContract) != address(0)); var _rank = tokenIdToRank[_tokenId]; var _rewardId = swapContract.swapCardForReward(this, _rank); CardSwap(ownerOf(_tokenId), _tokenId, _rewardId); _burn(_tokenId); return _rewardId; } } /** * @title The interface contract for Card-For-Hero swap functionality. * @dev With this contract, a card holder can swap his/her CryptoSagaCard for reward. * This contract is intended to be inherited by CryptoSagaCardSwap implementation contracts. */ contract CryptoSagaCardSwap is Ownable { // Card contract. address internal cardAddess; // Modifier for accessibility to define new hero types. modifier onlyCard { require(msg.sender == cardAddess); _; } // @dev Set the address of the contract that represents ERC721 Card. function setCardContract(address _contractAddress) public onlyOwner { cardAddess = _contractAddress; } // @dev Convert card into reward. // This should be implemented by CryptoSagaCore later. function swapCardForReward(address _by, uint8 _rank) onlyCard public returns (uint256); } /** * @title CryptoSagaHero * @dev The token contract for the hero. * Also a superset of the ERC721 standard that allows for the minting * of the non-fungible tokens. */ contract CryptoSagaHero is ERC721Token, Claimable, Pausable, AccessMint, AccessDeploy, AccessDeposit { string public constant name = "CryptoSaga Hero"; string public constant symbol = "HERO"; struct HeroClass { // ex) Soldier, Knight, Fighter... string className; // 0: Common, 1: Uncommon, 2: Rare, 3: Heroic, 4: Legendary. uint8 classRank; // 0: Human, 1: Celestial, 2: Demon, 3: Elf, 4: Dark Elf, 5: Yogoe, 6: Furry, 7: Dragonborn, 8: Undead, 9: Goblin, 10: Troll, 11: Slime, and more to come. uint8 classRace; // How old is this hero class? uint32 classAge; // 0: Fighter, 1: Rogue, 2: Mage. uint8 classType; // Possible max level of this class. uint32 maxLevel; // 0: Water, 1: Fire, 2: Nature, 3: Light, 4: Darkness. uint8 aura; // Base stats of this hero type. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] baseStats; // Minimum IVs for stats. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] minIVForStats; // Maximum IVs for stats. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] maxIVForStats; // Number of currently instanced heroes. uint32 currentNumberOfInstancedHeroes; } struct HeroInstance { // What is this hero's type? ex) John, Sally, Mark... uint32 heroClassId; // Individual hero's name. string heroName; // Current level of this hero. uint32 currentLevel; // Current exp of this hero. uint32 currentExp; // Where has this hero been deployed? (0: Never depolyed ever.) ex) Dungeon Floor #1, Arena #5... uint32 lastLocationId; // When a hero is deployed, it takes time for the hero to return to the base. This is in Unix epoch. uint256 availableAt; // Current stats of this hero. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] currentStats; // The individual value for this hero's stats. // This will affect the current stats of heroes. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] ivForStats; } // Required exp for level up will increase when heroes level up. // This defines how the value will increase. uint32 public requiredExpIncreaseFactor = 100; // Required Gold for level up will increase when heroes level up. // This defines how the value will increase. uint256 public requiredGoldIncreaseFactor = 1000000000000000000; // Existing hero classes. mapping(uint32 => HeroClass) public heroClasses; // The number of hero classes ever defined. uint32 public numberOfHeroClasses; // Existing hero instances. // The key is _tokenId. mapping(uint256 => HeroInstance) public tokenIdToHeroInstance; // The number of tokens ever minted. This works as the serial number. uint256 public numberOfTokenIds; // Gold contract. Gold public goldContract; // Deposit of players (in Gold). mapping(address => uint256) public addressToGoldDeposit; // Random seed. uint32 private seed = 0; // Event that is fired when a hero type defined. event DefineType( address indexed _by, uint32 indexed _typeId, string _className ); // Event that is fired when a hero is upgraded. event LevelUp( address indexed _by, uint256 indexed _tokenId, uint32 _newLevel ); // Event that is fired when a hero is deployed. event Deploy( address indexed _by, uint256 indexed _tokenId, uint32 _locationId, uint256 _duration ); // @dev Get the class's entire infomation. function getClassInfo(uint32 _classId) external view returns (string className, uint8 classRank, uint8 classRace, uint32 classAge, uint8 classType, uint32 maxLevel, uint8 aura, uint32[5] baseStats, uint32[5] minIVs, uint32[5] maxIVs) { var _cl = heroClasses[_classId]; return (_cl.className, _cl.classRank, _cl.classRace, _cl.classAge, _cl.classType, _cl.maxLevel, _cl.aura, _cl.baseStats, _cl.minIVForStats, _cl.maxIVForStats); } // @dev Get the class's name. function getClassName(uint32 _classId) external view returns (string) { return heroClasses[_classId].className; } // @dev Get the class's rank. function getClassRank(uint32 _classId) external view returns (uint8) { return heroClasses[_classId].classRank; } // @dev Get the heroes ever minted for the class. function getClassMintCount(uint32 _classId) external view returns (uint32) { return heroClasses[_classId].currentNumberOfInstancedHeroes; } // @dev Get the hero's entire infomation. function getHeroInfo(uint256 _tokenId) external view returns (uint32 classId, string heroName, uint32 currentLevel, uint32 currentExp, uint32 lastLocationId, uint256 availableAt, uint32[5] currentStats, uint32[5] ivs, uint32 bp) { HeroInstance memory _h = tokenIdToHeroInstance[_tokenId]; var _bp = _h.currentStats[0] + _h.currentStats[1] + _h.currentStats[2] + _h.currentStats[3] + _h.currentStats[4]; return (_h.heroClassId, _h.heroName, _h.currentLevel, _h.currentExp, _h.lastLocationId, _h.availableAt, _h.currentStats, _h.ivForStats, _bp); } // @dev Get the hero's class id. function getHeroClassId(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].heroClassId; } // @dev Get the hero's name. function getHeroName(uint256 _tokenId) external view returns (string) { return tokenIdToHeroInstance[_tokenId].heroName; } // @dev Get the hero's level. function getHeroLevel(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].currentLevel; } // @dev Get the hero's location. function getHeroLocation(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].lastLocationId; } // @dev Get the time when the hero become available. function getHeroAvailableAt(uint256 _tokenId) external view returns (uint256) { return tokenIdToHeroInstance[_tokenId].availableAt; } // @dev Get the hero's BP. function getHeroBP(uint256 _tokenId) public view returns (uint32) { var _tmp = tokenIdToHeroInstance[_tokenId].currentStats; return (_tmp[0] + _tmp[1] + _tmp[2] + _tmp[3] + _tmp[4]); } // @dev Get the hero's required gold for level up. function getHeroRequiredGoldForLevelUp(uint256 _tokenId) public view returns (uint256) { return (uint256(2) ** (tokenIdToHeroInstance[_tokenId].currentLevel / 10)) * requiredGoldIncreaseFactor; } // @dev Get the hero's required exp for level up. function getHeroRequiredExpForLevelUp(uint256 _tokenId) public view returns (uint32) { return ((tokenIdToHeroInstance[_tokenId].currentLevel + 2) * requiredExpIncreaseFactor); } // @dev Get the deposit of gold of the player. function getGoldDepositOfAddress(address _address) external view returns (uint256) { return addressToGoldDeposit[_address]; } // @dev Get the token id of the player's #th token. function getTokenIdOfAddressAndIndex(address _address, uint256 _index) external view returns (uint256) { return tokensOf(_address)[_index]; } // @dev Get the total BP of the player. function getTotalBPOfAddress(address _address) external view returns (uint32) { var _tokens = tokensOf(_address); uint32 _totalBP = 0; for (uint256 i = 0; i < _tokens.length; i ++) { _totalBP += getHeroBP(_tokens[i]); } return _totalBP; } // @dev Set the hero's name. function setHeroName(uint256 _tokenId, string _name) onlyOwnerOf(_tokenId) public { tokenIdToHeroInstance[_tokenId].heroName = _name; } // @dev Set the address of the contract that represents ERC20 Gold. function setGoldContract(address _contractAddress) onlyOwner public { goldContract = Gold(_contractAddress); } // @dev Set the required golds to level up a hero. function setRequiredExpIncreaseFactor(uint32 _value) onlyOwner public { requiredExpIncreaseFactor = _value; } // @dev Set the required golds to level up a hero. function setRequiredGoldIncreaseFactor(uint256 _value) onlyOwner public { requiredGoldIncreaseFactor = _value; } // @dev Contructor. function CryptoSagaHero(address _goldAddress) public { require(_goldAddress != address(0)); // Assign Gold contract. setGoldContract(_goldAddress); // Initial heroes. // Name, Rank, Race, Age, Type, Max Level, Aura, Stats. defineType("Archangel", 4, 1, 13540, 0, 99, 3, [uint32(74), 75, 57, 99, 95], [uint32(8), 6, 8, 5, 5], [uint32(8), 10, 10, 6, 6]); defineType("Shadowalker", 3, 4, 134, 1, 75, 4, [uint32(45), 35, 60, 80, 40], [uint32(3), 2, 10, 4, 5], [uint32(5), 5, 10, 7, 5]); defineType("Pyromancer", 2, 0, 14, 2, 50, 1, [uint32(50), 28, 17, 40, 35], [uint32(5), 3, 2, 3, 3], [uint32(8), 4, 3, 4, 5]); defineType("Magician", 1, 3, 224, 2, 30, 0, [uint32(35), 15, 25, 25, 30], [uint32(3), 1, 2, 2, 2], [uint32(5), 2, 3, 3, 3]); defineType("Farmer", 0, 0, 59, 0, 15, 2, [uint32(10), 22, 8, 15, 25], [uint32(1), 2, 1, 1, 2], [uint32(1), 3, 1, 2, 3]); } // @dev Define a new hero type (class). function defineType(string _className, uint8 _classRank, uint8 _classRace, uint32 _classAge, uint8 _classType, uint32 _maxLevel, uint8 _aura, uint32[5] _baseStats, uint32[5] _minIVForStats, uint32[5] _maxIVForStats) onlyOwner public { require(_classRank < 5); require(_classType < 3); require(_aura < 5); require(_minIVForStats[0] <= _maxIVForStats[0] && _minIVForStats[1] <= _maxIVForStats[1] && _minIVForStats[2] <= _maxIVForStats[2] && _minIVForStats[3] <= _maxIVForStats[3] && _minIVForStats[4] <= _maxIVForStats[4]); HeroClass memory _heroType = HeroClass({ className: _className, classRank: _classRank, classRace: _classRace, classAge: _classAge, classType: _classType, maxLevel: _maxLevel, aura: _aura, baseStats: _baseStats, minIVForStats: _minIVForStats, maxIVForStats: _maxIVForStats, currentNumberOfInstancedHeroes: 0 }); // Save the hero class. heroClasses[numberOfHeroClasses] = _heroType; // Fire event. DefineType(msg.sender, numberOfHeroClasses, _heroType.className); // Increment number of hero classes. numberOfHeroClasses ++; } // @dev Mint a new hero, with _heroClassId. function mint(address _owner, uint32 _heroClassId) onlyAccessMint public returns (uint256) { require(_owner != address(0)); require(_heroClassId < numberOfHeroClasses); // The information of the hero's class. var _heroClassInfo = heroClasses[_heroClassId]; // Mint ERC721 token. _mint(_owner, numberOfTokenIds); // Build random IVs for this hero instance. uint32[5] memory _ivForStats; uint32[5] memory _initialStats; for (uint8 i = 0; i < 5; i++) { _ivForStats[i] = (random(_heroClassInfo.maxIVForStats[i] + 1, _heroClassInfo.minIVForStats[i])); _initialStats[i] = _heroClassInfo.baseStats[i] + _ivForStats[i]; } // Temporary hero instance. HeroInstance memory _heroInstance = HeroInstance({ heroClassId: _heroClassId, heroName: "", currentLevel: 1, currentExp: 0, lastLocationId: 0, availableAt: now, currentStats: _initialStats, ivForStats: _ivForStats }); // Save the hero instance. tokenIdToHeroInstance[numberOfTokenIds] = _heroInstance; // Increment number of token ids. // This will only increment when new token is minted, and will never be decemented when the token is burned. numberOfTokenIds ++; // Increment instanced number of heroes. _heroClassInfo.currentNumberOfInstancedHeroes ++; return numberOfTokenIds - 1; } // @dev Set where the heroes are deployed, and when they will return. // This is intended to be called by Dungeon, Arena, Guild contracts. function deploy(uint256 _tokenId, uint32 _locationId, uint256 _duration) onlyAccessDeploy public returns (bool) { // The hero should be possessed by anybody. require(ownerOf(_tokenId) != address(0)); var _heroInstance = tokenIdToHeroInstance[_tokenId]; // The character should be avaiable. require(_heroInstance.availableAt <= now); _heroInstance.lastLocationId = _locationId; _heroInstance.availableAt = now + _duration; // As the hero has been deployed to another place, fire event. Deploy(msg.sender, _tokenId, _locationId, _duration); } // @dev Add exp. // This is intended to be called by Dungeon, Arena, Guild contracts. function addExp(uint256 _tokenId, uint32 _exp) onlyAccessDeploy public returns (bool) { // The hero should be possessed by anybody. require(ownerOf(_tokenId) != address(0)); var _heroInstance = tokenIdToHeroInstance[_tokenId]; var _newExp = _heroInstance.currentExp + _exp; // Sanity check to ensure we don't overflow. require(_newExp == uint256(uint128(_newExp))); _heroInstance.currentExp += _newExp; } // @dev Add deposit. // This is intended to be called by Dungeon, Arena, Guild contracts. function addDeposit(address _to, uint256 _amount) onlyAccessDeposit public { // Increment deposit. addressToGoldDeposit[_to] += _amount; } // @dev Level up the hero with _tokenId. // This function is called by the owner of the hero. function levelUp(uint256 _tokenId) onlyOwnerOf(_tokenId) whenNotPaused public { // Hero instance. var _heroInstance = tokenIdToHeroInstance[_tokenId]; // The character should be avaiable. (Should have already returned from the dungeons, arenas, etc.) require(_heroInstance.availableAt <= now); // The information of the hero's class. var _heroClassInfo = heroClasses[_heroInstance.heroClassId]; // Hero shouldn't level up exceed its max level. require(_heroInstance.currentLevel < _heroClassInfo.maxLevel); // Required Exp. var requiredExp = getHeroRequiredExpForLevelUp(_tokenId); // Need to have enough exp. require(_heroInstance.currentExp >= requiredExp); // Required Gold. var requiredGold = getHeroRequiredGoldForLevelUp(_tokenId); // Owner of token. var _ownerOfToken = ownerOf(_tokenId); // Need to have enough Gold balance. require(addressToGoldDeposit[_ownerOfToken] >= requiredGold); // Increase Level. _heroInstance.currentLevel += 1; // Increase Stats. for (uint8 i = 0; i < 5; i++) { _heroInstance.currentStats[i] = _heroClassInfo.baseStats[i] + (_heroInstance.currentLevel - 1) * _heroInstance.ivForStats[i]; } // Deduct exp. _heroInstance.currentExp -= requiredExp; // Deduct gold. addressToGoldDeposit[_ownerOfToken] -= requiredGold; // Fire event. LevelUp(msg.sender, _tokenId, _heroInstance.currentLevel); } // @dev Transfer deposit (with the allowance pattern.) function transferDeposit(uint256 _amount) whenNotPaused public { require(goldContract.allowance(msg.sender, this) >= _amount); // Send msg.sender's Gold to this contract. if (goldContract.transferFrom(msg.sender, this, _amount)) { // Increment deposit. addressToGoldDeposit[msg.sender] += _amount; } } // @dev Withdraw deposit. function withdrawDeposit(uint256 _amount) public { require(addressToGoldDeposit[msg.sender] >= _amount); // Send deposit of Golds to msg.sender. (Rather minting...) if (goldContract.transfer(msg.sender, _amount)) { // Decrement deposit. addressToGoldDeposit[msg.sender] -= _amount; } } // @dev return a pseudo random number between lower and upper bounds function random(uint32 _upper, uint32 _lower) private returns (uint32) { require(_upper > _lower); seed = uint32(keccak256(keccak256(block.blockhash(block.number), seed), now)); return seed % (_upper - _lower) + _lower; } } /** * @title CryptoSagaCorrectedHeroStats * @dev Corrected hero stats is needed to fix the bug in hero stats. */ contract CryptoSagaCorrectedHeroStats { // The hero contract. CryptoSagaHero private heroContract; // @dev Constructor. function CryptoSagaCorrectedHeroStats(address _heroContractAddress) public { heroContract = CryptoSagaHero(_heroContractAddress); } // @dev Get the hero's stats and some other infomation. function getCorrectedStats(uint256 _tokenId) external view returns (uint32 currentLevel, uint32 currentExp, uint32[5] currentStats, uint32[5] ivs, uint32 bp) { var (, , _currentLevel, _currentExp, , , _currentStats, _ivs, ) = heroContract.getHeroInfo(_tokenId); if (_currentLevel != 1) { for (uint8 i = 0; i < 5; i ++) { _currentStats[i] += _ivs[i]; } } var _bp = _currentStats[0] + _currentStats[1] + _currentStats[2] + _currentStats[3] + _currentStats[4]; return (_currentLevel, _currentExp, _currentStats, _ivs, _bp); } // @dev Get corrected total BP of the address. function getCorrectedTotalBPOfAddress(address _address) external view returns (uint32) { var _balance = heroContract.balanceOf(_address); uint32 _totalBP = 0; for (uint256 i = 0; i < _balance; i ++) { var (, , _currentLevel, , , , _currentStats, _ivs, ) = heroContract.getHeroInfo(heroContract.getTokenIdOfAddressAndIndex(_address, i)); if (_currentLevel != 1) { for (uint8 j = 0; j < 5; j ++) { _currentStats[j] += _ivs[j]; } } _totalBP += (_currentStats[0] + _currentStats[1] + _currentStats[2] + _currentStats[3] + _currentStats[4]); } return _totalBP; } // @dev Get corrected total BP of the address. function getCorrectedTotalBPOfTokens(uint256[] _tokens) external view returns (uint32) { uint32 _totalBP = 0; for (uint256 i = 0; i < _tokens.length; i ++) { var (, , _currentLevel, , , , _currentStats, _ivs, ) = heroContract.getHeroInfo(_tokens[i]); if (_currentLevel != 1) { for (uint8 j = 0; j < 5; j ++) { _currentStats[j] += _ivs[j]; } } _totalBP += (_currentStats[0] + _currentStats[1] + _currentStats[2] + _currentStats[3] + _currentStats[4]); } return _totalBP; } } /** * @title CryptoSagaArenaRecord * @dev The record of battles in the Arena. */ contract CryptoSagaArenaRecord is Pausable, AccessDeploy { // Number of players for the leaderboard. uint8 public numberOfLeaderboardPlayers = 25; // Top players in the leaderboard. address[] public leaderBoardPlayers; // For checking whether the player is in the leaderboard. mapping(address => bool) public addressToIsInLeaderboard; // Number of recent player recorded for matchmaking. uint8 public numberOfRecentPlayers = 50; // List of recent players. address[] public recentPlayers; // Front of recent players. uint256 public recentPlayersFront; // Back of recent players. uint256 public recentPlayersBack; // Record of each player. mapping(address => uint32) public addressToElo; // Event that is fired when a new change has been made to the leaderboard. event UpdateLeaderboard( address indexed _by, uint256 _dateTime ); // @dev Get elo rating of a player. function getEloRating(address _address) external view returns (uint32) { if (addressToElo[_address] != 0) return addressToElo[_address]; else return 1500; } // @dev Get players in the leaderboard. function getLeaderboardPlayers() external view returns (address[]) { return leaderBoardPlayers; } // @dev Get current length of the leaderboard. function getLeaderboardLength() external view returns (uint256) { return leaderBoardPlayers.length; } // @dev Get recently played players. function getRecentPlayers() external view returns (address[]) { return recentPlayers; } // @dev Get current number of players in the recently played players queue. function getRecentPlayersCount() public view returns (uint256) { return recentPlayersBack - recentPlayersFront; } // @dev Constructor. function CryptoSagaArenaRecord( address _previousSeasonRecord, uint8 _numberOfLeaderboardPlayers, uint8 _numberOfRecentPlayers) public { numberOfLeaderboardPlayers = _numberOfLeaderboardPlayers; numberOfRecentPlayers = _numberOfRecentPlayers; // Get instance of previous season. CryptoSagaArenaRecord _previous = CryptoSagaArenaRecord(_previousSeasonRecord); for (uint256 i = _previous.recentPlayersFront(); i < _previous.recentPlayersBack(); i++) { var _player = _previous.recentPlayers(i); // The initial player's Elo. addressToElo[_player] = _previous.getEloRating(_player); } } // @dev Update record. function updateRecord(address _myAddress, address _enemyAddress, bool _didWin) whenNotPaused onlyAccessDeploy public { address _winnerAddress = _didWin? _myAddress: _enemyAddress; address _loserAddress = _didWin? _enemyAddress: _myAddress; // Initial value of Elo. uint32 _winnerElo = addressToElo[_winnerAddress]; if (_winnerElo == 0) _winnerElo = 1500; uint32 _loserElo = addressToElo[_loserAddress]; if (_loserElo == 0) _loserElo = 1500; // Adjust Elo. if (_winnerElo >= _loserElo) { if (_winnerElo - _loserElo < 50) { addressToElo[_winnerAddress] = _winnerElo + 5; addressToElo[_loserAddress] = _loserElo - 5; } else if (_winnerElo - _loserElo < 80) { addressToElo[_winnerAddress] = _winnerElo + 4; addressToElo[_loserAddress] = _loserElo - 4; } else if (_winnerElo - _loserElo < 150) { addressToElo[_winnerAddress] = _winnerElo + 3; addressToElo[_loserAddress] = _loserElo - 3; } else if (_winnerElo - _loserElo < 250) { addressToElo[_winnerAddress] = _winnerElo + 2; addressToElo[_loserAddress] = _loserElo - 2; } else { addressToElo[_winnerAddress] = _winnerElo + 1; addressToElo[_loserAddress] = _loserElo - 1; } } else { if (_loserElo - _winnerElo < 50) { addressToElo[_winnerAddress] = _winnerElo + 5; addressToElo[_loserAddress] = _loserElo - 5; } else if (_loserElo - _winnerElo < 80) { addressToElo[_winnerAddress] = _winnerElo + 6; addressToElo[_loserAddress] = _loserElo - 6; } else if (_loserElo - _winnerElo < 150) { addressToElo[_winnerAddress] = _winnerElo + 7; addressToElo[_loserAddress] = _loserElo - 7; } else if (_loserElo - _winnerElo < 250) { addressToElo[_winnerAddress] = _winnerElo + 8; addressToElo[_loserAddress] = _loserElo - 8; } else { addressToElo[_winnerAddress] = _winnerElo + 9; addressToElo[_loserAddress] = _loserElo - 9; } } // Update recent players list. if (!isPlayerInQueue(_myAddress)) { // If the queue is full, pop a player. if (getRecentPlayersCount() >= numberOfRecentPlayers) popPlayer(); // Push _myAddress to the queue. pushPlayer(_myAddress); } // Update leaderboards. if(updateLeaderboard(_enemyAddress) || updateLeaderboard(_myAddress)) { UpdateLeaderboard(_myAddress, now); } } // @dev Update leaderboard. function updateLeaderboard(address _addressToUpdate) whenNotPaused private returns (bool isChanged) { // If this players is already in the leaderboard, there's no need for replace the minimum recorded player. if (addressToIsInLeaderboard[_addressToUpdate]) { // Do nothing. } else { if (leaderBoardPlayers.length >= numberOfLeaderboardPlayers) { // Need to replace existing player. // First, we need to find the player with miminum Elo value. uint32 _minimumElo = 99999; uint8 _minimumEloPlayerIndex = numberOfLeaderboardPlayers; for (uint8 i = 0; i < leaderBoardPlayers.length; i ++) { if (_minimumElo > addressToElo[leaderBoardPlayers[i]]) { _minimumElo = addressToElo[leaderBoardPlayers[i]]; _minimumEloPlayerIndex = i; } } // Second, if the minimum elo value is smaller than the player's elo value, then replace the entity. if (_minimumElo <= addressToElo[_addressToUpdate]) { addressToIsInLeaderboard[leaderBoardPlayers[_minimumEloPlayerIndex]] = false; leaderBoardPlayers[_minimumEloPlayerIndex] = _addressToUpdate; addressToIsInLeaderboard[_addressToUpdate] = true; isChanged = true; } } else { // The list is not full yet. // Just add the player to the list. leaderBoardPlayers.push(_addressToUpdate); addressToIsInLeaderboard[_addressToUpdate] = true; isChanged = true; } } } // #dev Check whether contain the element or not. function isPlayerInQueue(address _player) view private returns (bool isContain) { isContain = false; for (uint256 i = recentPlayersFront; i < recentPlayersBack; i++) { if (_player == recentPlayers[i]) { isContain = true; } } } // @dev Push a new player into the queue. function pushPlayer(address _player) private { recentPlayers.push(_player); recentPlayersBack++; } // @dev Pop the oldest player in this queue. function popPlayer() private returns (address player) { if (recentPlayersBack == recentPlayersFront) return address(0); player = recentPlayers[recentPlayersFront]; delete recentPlayers[recentPlayersFront]; recentPlayersFront++; } }
Get corrected total BP of the address.
function getCorrectedTotalBPOfTokens(uint256[] _tokens) external view returns (uint32) { uint32 _totalBP = 0; for (uint256 i = 0; i < _tokens.length; i ++) { var (, , _currentLevel, , , , _currentStats, _ivs, ) = heroContract.getHeroInfo(_tokens[i]); if (_currentLevel != 1) { for (uint8 j = 0; j < 5; j ++) { _currentStats[j] += _ivs[j]; } } _totalBP += (_currentStats[0] + _currentStats[1] + _currentStats[2] + _currentStats[3] + _currentStats[4]); } return _totalBP; }
1,143,326
pragma solidity >=0.7.0; import "@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol"; interface IMintedBeforeReveal is IERC721Enumerable { function isMintedBeforeReveal(uint256 index) external view returns (bool); } pragma solidity >=0.7.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./IMintedBeforeReveal.sol"; contract Rexes is ERC721, Ownable, IMintedBeforeReveal { // This is the original provenance record of all CyberRexes in existence at the time. string public constant CYBERREXES_PROVENANCE = "7325ec1daac9ff26ac1a0c9cce64deb2a76d7f0e1d0d31a0c19658414ad8457e"; // Time of when the sale starts. uint256 public constant SALE_START_TIMESTAMP = 1616353200; // Time after which the CyberRexes are randomized and revealed (14 days from initial launch). uint256 public constant REVEAL_TIMESTAMP = SALE_START_TIMESTAMP + (86400 * 14); // Maximum amount of CyberRexes in existance. Ever. uint256 public constant MAX_CYBERREXES_SUPPLY = 10000; // The block in which the starting index was created. uint256 public startingIndexBlock; // The index of the item that will be #1. uint256 public startingIndex; // Mapping from token ID to name mapping (uint256 => string) private _tokenName; // Mapping if certain name string has already been reserved mapping (string => bool) private _nameReserved; // Mapping from token ID to whether the CyberRexes was minted before reveal. mapping (uint256 => bool) private _mintedBeforeReveal; // Events event NameChange (uint256 indexed rexIndex, string newName); constructor(string memory name, string memory symbol, string memory baseURI) ERC721(name, symbol) { _setBaseURI(baseURI); } /** * @dev Returns if the CyberRexes was minted before reveal phase. This could come in handy later. */ function isMintedBeforeReveal(uint256 index) public view override returns (bool) { return _mintedBeforeReveal[index]; } /** * @dev Gets current CyberRexes price based on current supply. */ function getRexMaxAmount() public view returns (uint256) { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started yet so you can't get a price yet."); require(totalSupply() < MAX_CYBERREXES_SUPPLY, "Sale has already ended, no more CyberRexes left to sell."); uint currentSupply = totalSupply(); return 20; } /** * @dev Gets current CyberRexes price based on current supply. */ function getRexPrice() public view returns (uint256) { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started yet so you can't get a price yet."); require(totalSupply() < MAX_CYBERREXES_SUPPLY, "Sale has already ended, no more CyberRexes left to sell."); uint currentSupply = totalSupply(); if (currentSupply >= 9990) { return 3000000000000000000; // 9990 - 9999 3 ETH } else if (currentSupply >= 9700) { return 1300000000000000000; // 9700 - 9989 1.3 ETH } else if (currentSupply >= 9000) { return 900000000000000000; // 9000 - 9699 0.9 ETH } else if (currentSupply >= 7500) { return 500000000000000000; // 7500 - 8999 0.5 ETH } else if (currentSupply >= 5500) { return 300000000000000000; // 5500 - 7499 0.3 ETH } else if (currentSupply >= 3000) { return 100000000000000000; // 3000 - 5499 0.1 ETH } else if (currentSupply >= 1000) { return 50000000000000000; // 1000 - 2999 0.05 ETH } else { return 10000000000000000; // 0 - 999 0.01 ETH } } /** * @dev Mints yourself a CyberRexes. Or more. You do you. */ function mintRex(uint256 numberOfRexes) public payable { // Some exceptions that need to be handled. require(totalSupply() < MAX_CYBERREXES_SUPPLY, "Sale has already ended."); require(numberOfRexes > 0, "You cannot mint 0 CyberRexes."); require(numberOfRexes <= getRexMaxAmount(), "You are not allowed to buy this many CyberRexes at once in this price tier."); require(SafeMath.add(totalSupply(), numberOfRexes) <= MAX_CYBERREXES_SUPPLY, "Exceeds maximum CyberRex supply. Please try to mint less CyberRexes."); require(SafeMath.mul(getRexPrice(), numberOfRexes) == msg.value, "Amount of Ether sent is not correct."); // Mint the amount of provided CyberRexes. for (uint i = 0; i < numberOfRexes; i++) { uint mintIndex = totalSupply(); if (block.timestamp < REVEAL_TIMESTAMP) { _mintedBeforeReveal[mintIndex] = true; } _safeMint(msg.sender, mintIndex); } // Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense // Set the starting block index when the sale concludes either time-wise or the supply runs out. if (startingIndexBlock == 0 && (totalSupply() == MAX_CYBERREXES_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } /** * @dev Finalize starting index */ function finalizeStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_CYBERREXES_SUPPLY; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes). if (SafeMath.sub(block.number, startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number-1)) % MAX_CYBERREXES_SUPPLY; } // Prevent default sequence because that would be a bit boring. if (startingIndex == 0) { startingIndex = SafeMath.add(startingIndex, 1); } } /** * @dev Withdraw ether from this contract (Callable by owner only) */ function withdraw() onlyOwner public { uint balance = address(this).balance; msg.sender.transfer(balance); } /** * @dev Returns name of the NFT at index. */ function tokenNameByIndex(uint256 index) public view returns (string memory) { return _tokenName[index]; } /** * @dev Returns if the name has been reserved. */ function isNameReserved(string memory nameString) public view returns (bool) { return _nameReserved[toLower(nameString)]; } /** * @dev Changes the name for CyberRex tokenId */ function changeName(uint256 tokenId, string memory newName) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "New name is same as the current one"); require(isNameReserved(newName) == false, "Name already reserved"); // If already named, dereserve old name if (bytes(_tokenName[tokenId]).length > 0) { toggleReserveName(_tokenName[tokenId], false); } toggleReserveName(newName, true); _tokenName[tokenId] = newName; emit NameChange(tokenId, newName); } /** * @dev Reserves the name if isReserve is set to true, de-reserves if set to false */ function toggleReserveName(string memory str, bool isReserve) internal { _nameReserved[toLower(str)] = isReserve; } /** * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function validateName(string memory str) public pure returns (bool){ bytes memory b = bytes(str); if(b.length < 1) return false; if(b.length > 25) return false; // Cannot be longer than 25 characters if(b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for(uint i; i<b.length; i++){ bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } /** * @dev Converts the string to lowercase */ function toLower(string memory str) public pure returns (string memory){ bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } /** * @dev Changes the base URI if we want to move things in the future (Callable by owner only) */ function changeBaseURI(string memory baseURI) onlyOwner public { _setBaseURI(baseURI); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // 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; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @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 _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @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 _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @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 || ERC721.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 _tokenOwners.contains(tokenId); } /** * @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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `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); _holderTokens[to].add(tokenId); _tokenOwners.set(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); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(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"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @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()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @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 { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../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 pragma solidity >=0.6.2 <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.6.2 <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.6.0 <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.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` 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); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } }
Gets current CyberRexes price based on current supply./
function getRexMaxAmount() public view returns (uint256) { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started yet so you can't get a price yet."); require(totalSupply() < MAX_CYBERREXES_SUPPLY, "Sale has already ended, no more CyberRexes left to sell."); uint currentSupply = totalSupply(); return 20; }
13,957,729
./full_match/1/0x84fE05f541cee93d0B02e03cD4319c29BA0030A2/sources/src/rollup/RollupAdminLogic.sol
set a new sequencer inbox contract _sequencerInbox new address of sequencer inbox/
function setSequencerInbox(address _sequencerInbox) external override { bridge.setSequencerInbox(_sequencerInbox); emit OwnerFunctionCalled(27); }
3,877,445
pragma solidity ^0.4.8; import "../ownership/Ownable.sol"; /* In practice any public Ethereum address is a target to receiving ETH. Often ETH will find its way to a Contract via send (not via a function call), even though the contract was not meant to receive ETH. For this reason all contracts should have a withdrawEther function, even after a contract is meant to retire. For this reason no contract should really ever selfdestruct, instead always only having the withdrawEther function active and disabling all other functions. */ contract Destructible is Ownable { bool contractActive = true; /// @notice Set this contract as inactive but do not destroy, withdrawEther function destroy() onlyOwner destroyable { contractActive = false; withdrawEther(); } /// @notice Withdraw all Ether in this contract /// @return True if successful function withdrawEther() payable onlyOwner returns (bool) { return owner.send(this.balance); } /// @notice ALl functions with this modifier will become inaccessible after a call to destroy modifier destroyable() { if (!contractActive) { throw; } _; } }
Withdraw all Ether in this contract return True if successful
function withdrawEther() payable onlyOwner returns (bool) { return owner.send(this.balance); }
12,805,870
/** *Submitted for verification at Etherscan.io on 2020-09-18 */ /** *Submitted for verification at Etherscan.io on 2020-09-18 */ // File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/token/ERC20/IERC20.sol pragma solidity 0.5.7; /** * @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 ); } // File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/math/SafeMath.sol pragma solidity 0.5.7; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { //require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; //require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: nexusmutual-contracts/contracts/NXMToken.sol /* Copyright (C) 2017 NexusMutual.io 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/ */ pragma solidity 0.5.7; contract NXMToken is IERC20 { using SafeMath for uint256; event WhiteListed(address indexed member); event BlackListed(address indexed member); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; mapping (address => bool) public whiteListed; mapping(address => uint) public isLockedForMV; uint256 private _totalSupply; string public name = "NXM"; string public symbol = "NXM"; uint8 public decimals = 18; address public operator; modifier canTransfer(address _to) { require(whiteListed[_to]); _; } modifier onlyOperator() { if (operator != address(0)) require(msg.sender == operator); _; } constructor(address _founderAddress, uint _initialSupply) public { _mint(_founderAddress, _initialSupply); } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Adds a user to whitelist * @param _member address to add to whitelist */ function addToWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = true; emit WhiteListed(_member); return true; } /** * @dev removes a user from whitelist * @param _member address to remove from whitelist */ function removeFromWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = false; emit BlackListed(_member); return true; } /** * @dev change operator address * @param _newOperator address of new operator */ function changeOperator(address _newOperator) public onlyOperator returns (bool) { operator = _newOperator; return true; } /** * @dev burns an amount of the tokens of the message sender * account. * @param amount The amount that will be burnt. */ function burn(uint256 amount) public returns (bool) { _burn(msg.sender, amount); return true; } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public returns (bool) { _burnFrom(from, value); return true; } /** * @dev function that mints an amount of the token and assigns it to * an account. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function mint(address account, uint256 amount) public onlyOperator { _mint(account, amount); } /** * @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 canTransfer(to) returns (bool) { require(isLockedForMV[msg.sender] < now); // if not voted under governance require(value <= _balances[msg.sender]); _transfer(to, value); return true; } /** * @dev Transfer tokens to the operator from the specified address * @param from The address to transfer from. * @param value The amount to be transferred. */ function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) { require(value <= _balances[from]); _transferFrom(from, operator, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public canTransfer(to) returns (bool) { require(isLockedForMV[from] < now); // if not voted under governance require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); _transferFrom(from, to, value); return true; } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyOperator { if (_days.add(now) > isLockedForMV[_of]) isLockedForMV[_of] = _days.add(now); } /** * @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) internal { _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); } /** * @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 ) internal { _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); } /** * @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 amount The amount that will be created. */ function _mint(address account, uint256 amount) internal { require(account != address(0)); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address account, uint256 amount) internal { require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IProposalCategory.sol /* Copyright (C) 2017 GovBlocks.io 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/ */ pragma solidity 0.5.7; contract IProposalCategory { event Category( uint indexed categoryId, string categoryName, string actionHash ); /// @dev Adds new category /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external; /// @dev gets category details function category(uint _categoryId) external view returns( uint categoryId, uint memberRoleToVote, uint majorityVotePerc, uint quorumPerc, uint[] memory allowedToCreateProposal, uint closingTime, uint minStake ); ///@dev gets category action details function categoryAction(uint _categoryId) external view returns( uint categoryId, address contractAddress, bytes2 contractName, uint defaultIncentive ); /// @dev Gets Total number of categories added till now function totalCategories() external view returns(uint numberOfCategories); /// @dev Updates category details /// @param _categoryId Category id that needs to be updated /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public; } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/Governed.sol /* Copyright (C) 2017 GovBlocks.io 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/ */ pragma solidity 0.5.7; contract IMaster { function getLatestAddress(bytes2 _module) public view returns(address); } contract Governed { address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract /// @dev modifier that allows only the authorized addresses to execute the function modifier onlyAuthorizedToGovern() { IMaster ms = IMaster(masterAddress); require(ms.getLatestAddress("GV") == msg.sender, "Not authorized"); _; } /// @dev checks if an address is authorized to govern function isAuthorizedToGovern(address _toCheck) public view returns(bool) { IMaster ms = IMaster(masterAddress); return (ms.getLatestAddress("GV") == _toCheck); } } // File: nexusmutual-contracts/contracts/INXMMaster.sol /* Copyright (C) 2017 NexusMutual.io 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/ */ pragma solidity 0.5.7; contract INXMMaster { address public tokenAddress; address public owner; uint public pauseTime; function delegateCallBack(bytes32 myid) external; function masterInitialized() public view returns(bool); function isInternal(address _add) public view returns(bool); function isPause() public view returns(bool check); function isOwner(address _add) public view returns(bool); function isMember(address _add) public view returns(bool); function checkIsAuthToGoverned(address _add) public view returns(bool); function updatePauseTime(uint _time) public; function dAppLocker() public view returns(address _add); function dAppToken() public view returns(address _add); function getLatestAddress(bytes2 _contractName) public view returns(address payable contractAddress); } // File: nexusmutual-contracts/contracts/Iupgradable.sol pragma solidity 0.5.7; contract Iupgradable { INXMMaster public ms; address public nxMasterAddress; modifier onlyInternal { require(ms.isInternal(msg.sender)); _; } modifier isMemberAndcheckPause { require(ms.isPause() == false && ms.isMember(msg.sender) == true); _; } modifier onlyOwner { require(ms.isOwner(msg.sender)); _; } modifier checkPause { require(ms.isPause() == false); _; } modifier isMember { require(ms.isMember(msg.sender), "Not member"); _; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public; /** * @dev change master address * @param _masterAddress is the new address */ function changeMasterAddress(address _masterAddress) public { if (address(ms) != address(0)) { require(address(ms) == msg.sender, "Not master"); } ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } } // File: nexusmutual-contracts/contracts/interfaces/IPooledStaking.sol pragma solidity ^0.5.7; interface IPooledStaking { function accumulateReward(address contractAddress, uint amount) external; function pushBurn(address contractAddress, uint amount) external; function hasPendingActions() external view returns (bool); function contractStake(address contractAddress) external view returns (uint); function stakerReward(address staker) external view returns (uint); function stakerDeposit(address staker) external view returns (uint); function stakerContractStake(address staker, address contractAddress) external view returns (uint); function withdraw(uint amount) external; function stakerMaxWithdrawable(address stakerAddress) external view returns (uint); function withdrawReward(address stakerAddress) external; } // File: nexusmutual-contracts/contracts/TokenFunctions.sol /* Copyright (C) 2020 NexusMutual.io 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/ */ pragma solidity 0.5.7; contract TokenFunctions is Iupgradable { using SafeMath for uint; MCR internal m1; MemberRoles internal mr; NXMToken public tk; TokenController internal tc; TokenData internal td; QuotationData internal qd; ClaimsReward internal cr; Governance internal gv; PoolData internal pd; IPooledStaking pooledStaking; event BurnCATokens(uint claimId, address addr, uint amount); /** * @dev Rewards stakers on purchase of cover on smart contract. * @param _contractAddress smart contract address. * @param _coverPriceNXM cover price in NXM. */ function pushStakerRewards(address _contractAddress, uint _coverPriceNXM) external onlyInternal { uint rewardValue = _coverPriceNXM.mul(td.stakerCommissionPer()).div(100); pooledStaking.accumulateReward(_contractAddress, rewardValue); } /** * @dev Deprecated in favor of burnStakedTokens */ function burnStakerLockedToken(uint, bytes4, uint) external { // noop } /** * @dev Burns tokens staked on smart contract covered by coverId. Called when a payout is succesfully executed. * @param coverId cover id * @param coverCurrency cover currency * @param sumAssured amount of $curr to burn */ function burnStakedTokens(uint coverId, bytes4 coverCurrency, uint sumAssured) external onlyInternal { (, address scAddress) = qd.getscAddressOfCover(coverId); uint tokenPrice = m1.calculateTokenPrice(coverCurrency); uint burnNXMAmount = sumAssured.mul(1e18).div(tokenPrice); pooledStaking.pushBurn(scAddress, burnNXMAmount); } /** * @dev Gets the total staked NXM tokens against * Smart contract by all stakers * @param _stakedContractAddress smart contract address. * @return amount total staked NXM tokens. */ function deprecated_getTotalStakedTokensOnSmartContract( address _stakedContractAddress ) external view returns(uint) { uint stakedAmount = 0; address stakerAddress; uint staketLen = td.getStakedContractStakersLength(_stakedContractAddress); for (uint i = 0; i < staketLen; i++) { stakerAddress = td.getStakedContractStakerByIndex(_stakedContractAddress, i); uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, i); uint currentlyStaked; (, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(stakerAddress, _stakedContractAddress, stakerIndex); stakedAmount = stakedAmount.add(currentlyStaked); } return stakedAmount; } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _of address of the coverHolder. * @param _coverId coverId of the cover. */ function getUserLockedCNTokens(address _of, uint _coverId) external view returns(uint) { return _getUserLockedCNTokens(_of, _coverId); } /** * @dev to get the all the cover locked tokens of a user * @param _of is the user address in concern * @return amount locked */ function getUserAllLockedCNTokens(address _of) external view returns(uint amount) { for (uint i = 0; i < qd.getUserCoverLength(_of); i++) { amount = amount.add(_getUserLockedCNTokens(_of, qd.getAllCoversOfUser(_of)[i])); } } /** * @dev Returns amount of NXM Tokens locked as Cover Note against given coverId. * @param _coverId coverId of the cover. */ function getLockedCNAgainstCover(uint _coverId) external view returns(uint) { return _getLockedCNAgainstCover(_coverId); } /** * @dev Returns total amount of staked NXM Tokens on all smart contracts. * @param _stakerAddress address of the Staker. */ function deprecated_getStakerAllLockedTokens(address _stakerAddress) external view returns (uint amount) { uint stakedAmount = 0; address scAddress; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); uint currentlyStaked; (, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, scAddress, i); stakedAmount = stakedAmount.add(currentlyStaked); } amount = stakedAmount; } /** * @dev Returns total unlockable amount of staked NXM Tokens on all smart contract . * @param _stakerAddress address of the Staker. */ function deprecated_getStakerAllUnlockableStakedTokens( address _stakerAddress ) external view returns (uint amount) { uint unlockableAmount = 0; address scAddress; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); unlockableAmount = unlockableAmount.add( _deprecated_getStakerUnlockableTokensOnSmartContract(_stakerAddress, scAddress, scIndex)); } amount = unlockableAmount; } /** * @dev Change Dependent Contract Address */ function changeDependentContractAddress() public { tk = NXMToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tc = TokenController(ms.getLatestAddress("TC")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); gv = Governance(ms.getLatestAddress("GV")); mr = MemberRoles(ms.getLatestAddress("MR")); pd = PoolData(ms.getLatestAddress("PD")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); } /** * @dev Gets the Token price in a given currency * @param curr Currency name. * @return price Token Price. */ function getTokenPrice(bytes4 curr) public view returns(uint price) { price = m1.calculateTokenPrice(curr); } /** * @dev Set the flag to check if cover note is deposited against the cover id * @param coverId Cover Id. */ function depositCN(uint coverId) public onlyInternal returns (bool success) { require(_getLockedCNAgainstCover(coverId) > 0, "No cover note available"); td.setDepositCN(coverId, true); success = true; } /** * @param _of address of Member * @param _coverId Cover Id * @param _lockTime Pending Time + Cover Period 7*1 days */ function extendCNEPOff(address _of, uint _coverId, uint _lockTime) public onlyInternal { uint timeStamp = now.add(_lockTime); uint coverValidUntil = qd.getValidityOfCover(_coverId); if (timeStamp >= coverValidUntil) { bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId)); tc.extendLockOf(_of, reason, timeStamp); } } /** * @dev to burn the deposited cover tokens * @param coverId is id of cover whose tokens have to be burned * @return the status of the successful burning */ function burnDepositCN(uint coverId) public onlyInternal returns (bool success) { address _of = qd.getCoverMemberAddress(coverId); uint amount; (amount, ) = td.depositedCN(coverId); amount = (amount.mul(50)).div(100); bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId)); tc.burnLockedTokens(_of, reason, amount); success = true; } /** * @dev Unlocks covernote locked against a given cover * @param coverId id of cover */ function unlockCN(uint coverId) public onlyInternal { (, bool isDeposited) = td.depositedCN(coverId); require(!isDeposited,"Cover note is deposited and can not be released"); uint lockedCN = _getLockedCNAgainstCover(coverId); if (lockedCN != 0) { address coverHolder = qd.getCoverMemberAddress(coverId); bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId)); tc.releaseLockedTokens(coverHolder, reason, lockedCN); } } /** * @dev Burns tokens used for fraudulent voting against a claim * @param claimid Claim Id. * @param _value number of tokens to be burned * @param _of Claim Assessor's address. */ function burnCAToken(uint claimid, uint _value, address _of) public { require(ms.checkIsAuthToGoverned(msg.sender)); tc.burnLockedTokens(_of, "CLA", _value); emit BurnCATokens(claimid, _of, _value); } /** * @dev to lock cover note tokens * @param coverNoteAmount is number of tokens to be locked * @param coverPeriod is cover period in concern * @param coverId is the cover id of cover in concern * @param _of address whose tokens are to be locked */ function lockCN( uint coverNoteAmount, uint coverPeriod, uint coverId, address _of ) public onlyInternal { uint validity = (coverPeriod * 1 days).add(td.lockTokenTimeAfterCoverExp()); bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId)); td.setDepositCNAmount(coverId, coverNoteAmount); tc.lockOf(_of, reason, coverNoteAmount, validity); } /** * @dev to check if a member is locked for member vote * @param _of is the member address in concern * @return the boolean status */ function isLockedForMemberVote(address _of) public view returns(bool) { return now < tk.isLockedForMV(_of); } /** * @dev Internal function to gets amount of locked NXM tokens, * staked against smartcontract by index * @param _stakerAddress address of user * @param _stakedContractAddress staked contract address * @param _stakedContractIndex index of staking */ function deprecated_getStakerLockedTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint amount) { amount = _deprecated_getStakerLockedTokensOnSmartContract(_stakerAddress, _stakedContractAddress, _stakedContractIndex); } /** * @dev Function to gets unlockable amount of locked NXM * tokens, staked against smartcontract by index * @param stakerAddress address of staker * @param stakedContractAddress staked contract address * @param stakerIndex index of staking */ function deprecated_getStakerUnlockableTokensOnSmartContract ( address stakerAddress, address stakedContractAddress, uint stakerIndex ) public view returns (uint) { return _deprecated_getStakerUnlockableTokensOnSmartContract(stakerAddress, stakedContractAddress, td.getStakerStakedContractIndex(stakerAddress, stakerIndex)); } /** * @dev releases unlockable staked tokens to staker */ function deprecated_unlockStakerUnlockableTokens(address _stakerAddress) public checkPause { uint unlockableAmount; address scAddress; bytes32 reason; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); unlockableAmount = _deprecated_getStakerUnlockableTokensOnSmartContract( _stakerAddress, scAddress, scIndex); td.setUnlockableBeforeLastBurnTokens(_stakerAddress, i, 0); td.pushUnlockedStakedTokens(_stakerAddress, i, unlockableAmount); reason = keccak256(abi.encodePacked("UW", _stakerAddress, scAddress, scIndex)); tc.releaseLockedTokens(_stakerAddress, reason, unlockableAmount); } } /** * @dev to get tokens of staker locked before burning that are allowed to burn * @param stakerAdd is the address of the staker * @param stakedAdd is the address of staked contract in concern * @param stakerIndex is the staker index in concern * @return amount of unlockable tokens * @return amount of tokens that can burn */ function _deprecated_unlockableBeforeBurningAndCanBurn( address stakerAdd, address stakedAdd, uint stakerIndex ) public view returns (uint amount, uint canBurn) { uint dateAdd; uint initialStake; uint totalBurnt; uint ub; (, , dateAdd, initialStake, , totalBurnt, ub) = td.stakerStakedContracts(stakerAdd, stakerIndex); canBurn = _deprecated_calculateStakedTokens(initialStake, now.sub(dateAdd).div(1 days), td.scValidDays()); // Can't use SafeMaths for int. int v = int(initialStake - (canBurn) - (totalBurnt) - ( td.getStakerUnlockedStakedTokens(stakerAdd, stakerIndex)) - (ub)); uint currentLockedTokens = _deprecated_getStakerLockedTokensOnSmartContract( stakerAdd, stakedAdd, td.getStakerStakedContractIndex(stakerAdd, stakerIndex)); if (v < 0) { v = 0; } amount = uint(v); if (canBurn > currentLockedTokens.sub(amount).sub(ub)) { canBurn = currentLockedTokens.sub(amount).sub(ub); } } /** * @dev to get tokens of staker that are unlockable * @param _stakerAddress is the address of the staker * @param _stakedContractAddress is the address of staked contract in concern * @param _stakedContractIndex is the staked contract index in concern * @return amount of unlockable tokens */ function _deprecated_getStakerUnlockableTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint amount) { uint initialStake; uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, _stakedContractIndex); uint burnt; (, , , initialStake, , burnt,) = td.stakerStakedContracts(_stakerAddress, stakerIndex); uint alreadyUnlocked = td.getStakerUnlockedStakedTokens(_stakerAddress, stakerIndex); uint currentStakedTokens; (, currentStakedTokens) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, _stakedContractAddress, stakerIndex); amount = initialStake.sub(currentStakedTokens).sub(alreadyUnlocked).sub(burnt); } /** * @dev Internal function to get the amount of locked NXM tokens, * staked against smartcontract by index * @param _stakerAddress address of user * @param _stakedContractAddress staked contract address * @param _stakedContractIndex index of staking */ function _deprecated_getStakerLockedTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) internal view returns (uint amount) { bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress, _stakedContractAddress, _stakedContractIndex)); amount = tc.tokensLocked(_stakerAddress, reason); } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _coverId coverId of the cover. */ function _getLockedCNAgainstCover(uint _coverId) internal view returns(uint) { address coverHolder = qd.getCoverMemberAddress(_coverId); bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, _coverId)); return tc.tokensLockedAtTime(coverHolder, reason, now); } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _of address of the coverHolder. * @param _coverId coverId of the cover. */ function _getUserLockedCNTokens(address _of, uint _coverId) internal view returns(uint) { bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId)); return tc.tokensLockedAtTime(_of, reason, now); } /** * @dev Internal function to gets remaining amount of staked NXM tokens, * against smartcontract by index * @param _stakeAmount address of user * @param _stakeDays staked contract address * @param _validDays index of staking */ function _deprecated_calculateStakedTokens( uint _stakeAmount, uint _stakeDays, uint _validDays ) internal pure returns (uint amount) { if (_validDays > _stakeDays) { uint rf = ((_validDays.sub(_stakeDays)).mul(100000)).div(_validDays); amount = (rf.mul(_stakeAmount)).div(100000); } else { amount = 0; } } /** * @dev Gets the total staked NXM tokens against Smart contract * by all stakers * @param _stakedContractAddress smart contract address. * @return amount total staked NXM tokens. */ function _deprecated_burnStakerTokenLockedAgainstSmartContract( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _amount ) internal { uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, _stakedContractIndex); td.pushBurnedTokens(_stakerAddress, stakerIndex, _amount); bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress, _stakedContractAddress, _stakedContractIndex)); tc.burnLockedTokens(_stakerAddress, reason, _amount); } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IMemberRoles.sol /* Copyright (C) 2017 GovBlocks.io 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/ */ pragma solidity 0.5.7; contract IMemberRoles { event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription); /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function addRole(bytes32 _roleName, string memory _roleDescription, address _authorized) public; /// @dev Assign or Delete a member from specific role. /// @param _memberAddress Address of Member /// @param _roleId RoleId to update /// @param _active active is set to be True if we want to assign this role to member, False otherwise! function updateRole(address _memberAddress, uint _roleId, bool _active) public; /// @dev Change Member Address who holds the authority to Add/Delete any member from specific role. /// @param _roleId roleId to update its Authorized Address /// @param _authorized New authorized address against role id function changeAuthorized(uint _roleId, address _authorized) public; /// @dev Return number of member roles function totalRoles() public view returns(uint256); /// @dev Gets the member addresses assigned by a specific role /// @param _memberRoleId Member role id /// @return roleId Role id /// @return allMemberAddress Member addresses of specified role id function members(uint _memberRoleId) public view returns(uint, address[] memory allMemberAddress); /// @dev Gets all members' length /// @param _memberRoleId Member role id /// @return memberRoleData[_memberRoleId].memberAddress.length Member length function numberOfMembers(uint _memberRoleId) public view returns(uint); /// @dev Return member address who holds the right to add/remove any member from specific role. function authorized(uint _memberRoleId) public view returns(address); /// @dev Get All role ids array that has been assigned to a member so far. function roles(address _memberAddress) public view returns(uint[] memory assignedRoles); /// @dev Returns true if the given role id is assigned to a member. /// @param _memberAddress Address of member /// @param _roleId Checks member's authenticity with the roleId. /// i.e. Returns true if this roleId is assigned to member function checkRole(address _memberAddress, uint _roleId) public view returns(bool); } // File: nexusmutual-contracts/contracts/external/ERC1132/IERC1132.sol pragma solidity 0.5.7; /** * @title ERC1132 interface * @dev see https://github.com/ethereum/EIPs/issues/1132 */ contract IERC1132 { /** * @dev Reasons why a user's tokens have been locked */ mapping(address => bytes32[]) public lockReason; /** * @dev locked token structure */ struct LockToken { uint256 amount; uint256 validity; bool claimed; } /** * @dev Holds number & validity of tokens locked for a given reason for * a specified address */ mapping(address => mapping(bytes32 => LockToken)) public locked; /** * @dev Records data of all the tokens Locked */ event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity ); /** * @dev Records data of all the tokens unlocked */ event Unlocked( address indexed _of, bytes32 indexed _reason, uint256 _amount ); /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool); /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount); /** * @dev Returns total tokens held by an address (locked + transferable) * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount); /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public returns (bool); /** * @dev Increase number of tokens locked for a specified reason * @param _reason The reason to lock tokens * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public returns (bool); /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */ function unlock(address _of) public returns (uint256 unlockableTokens); /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens); } // File: nexusmutual-contracts/contracts/TokenController.sol /* Copyright (C) 2020 NexusMutual.io 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/ */ pragma solidity 0.5.7; contract TokenController is IERC1132, Iupgradable { using SafeMath for uint256; event Burned(address indexed member, bytes32 lockedUnder, uint256 amount); NXMToken public token; IPooledStaking public pooledStaking; uint public minCALockTime = uint(30).mul(1 days); bytes32 private constant CLA = bytes32("CLA"); /** * @dev Just for interface */ function changeDependentContractAddress() public { token = NXMToken(ms.tokenAddress()); pooledStaking = IPooledStaking(ms.getLatestAddress('PS')); } /** * @dev to change the operator address * @param _newOperator is the new address of operator */ function changeOperator(address _newOperator) public onlyInternal { token.changeOperator(_newOperator); } /** * @dev Proxies token transfer through this contract to allow staking when members are locked for voting * @param _from Source address * @param _to Destination address * @param _value Amount to transfer */ function operatorTransfer(address _from, address _to, uint _value) onlyInternal external returns (bool) { require(msg.sender == address(pooledStaking), "Call is only allowed from PooledStaking address"); require(token.operatorTransfer(_from, _value), "Operator transfer failed"); require(token.transfer(_to, _value), "Internal transfer failed"); return true; } /** * @dev Locks a specified amount of tokens, * for CLA reason and for a specified time * @param _reason The reason to lock tokens, currently restricted to CLA * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); require(minCALockTime <= _time,"Should lock for minimum time"); // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(msg.sender, _reason, _amount, _time); return true; } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds * @param _of address whose tokens are to be locked */ function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time) public onlyInternal returns (bool) { // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(_of, _reason, _amount, _time); return true; } /** * @dev Extends lock for reason CLA for a specified time * @param _reason The reason to lock tokens, currently restricted to CLA * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); _extendLock(msg.sender, _reason, _time); return true; } /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLockOf(address _of, bytes32 _reason, uint256 _time) public onlyInternal returns (bool) { _extendLock(_of, _reason, _time); return true; } /** * @dev Increase number of tokens locked for a CLA reason * @param _reason The reason to lock tokens, currently restricted to CLA * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); require(_tokensLocked(msg.sender, _reason) > 0); token.operatorTransfer(msg.sender, _amount); locked[msg.sender][_reason].amount = locked[msg.sender][_reason].amount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Locked(msg.sender, _reason, _amount, locked[msg.sender][_reason].validity); return true; } /** * @dev burns tokens of an address * @param _of is the address to burn tokens of * @param amount is the amount to burn * @return the boolean status of the burning process */ function burnFrom (address _of, uint amount) public onlyInternal returns (bool) { return token.burnFrom(_of, amount); } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _burnLockedTokens(_of, _reason, _amount); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal { _reduceLock(_of, _reason, _time); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _releaseLockedTokens(_of, _reason, _amount); } /** * @dev Adds an address to whitelist maintained in the contract * @param _member address to add to whitelist */ function addToWhitelist(address _member) public onlyInternal { token.addToWhiteList(_member); } /** * @dev Removes an address from the whitelist in the token * @param _member address to remove */ function removeFromWhitelist(address _member) public onlyInternal { token.removeFromWhiteList(_member); } /** * @dev Mints new token for an address * @param _member address to reward the minted tokens * @param _amount number of tokens to mint */ function mint(address _member, uint _amount) public onlyInternal { token.mint(_member, _amount); } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyInternal { token.lockForMemberVote(_of, _days); } /** * @dev Unlocks the unlockable tokens against CLA of a specified address * @param _of Address of user, claiming back unlockable tokens against CLA */ function unlock(address _of) public checkPause returns (uint256 unlockableTokens) { unlockableTokens = _tokensUnlockable(_of, CLA); if (unlockableTokens > 0) { locked[_of][CLA].claimed = true; emit Unlocked(_of, CLA, unlockableTokens); require(token.transfer(_of, unlockableTokens)); } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "MNCLT") { minCALockTime = val.mul(1 days); } else { revert("Invalid param code"); } } /** * @dev Gets the validity of locked tokens of a specified address * @param _of The address to query the validity * @param reason reason for which tokens were locked */ function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) { validity = locked[_of][reason].validity; } /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens) { for (uint256 i = 0; i < lockReason[_of].length; i++) { unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i])); } } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensLocked(_of, _reason); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensUnlockable(_of, _reason); } function totalSupply() public view returns (uint256) { return token.totalSupply(); } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount) { return _tokensLockedAtTime(_of, _reason, _time); } /** * @dev Returns the total amount of tokens held by an address: * transferable + locked + staked for pooled staking - pending burns. * Used by Claims and Governance in member voting to calculate the user's vote weight. * * @param _of The address to query the total balance of * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount) { amount = token.balanceOf(_of); for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLocked(_of, lockReason[_of][i])); } uint stakerReward = pooledStaking.stakerReward(_of); uint stakerDeposit = pooledStaking.stakerDeposit(_of); amount = amount.add(stakerDeposit).add(stakerReward); } /** * @dev Returns the total locked tokens at time * Returns the total amount of locked and staked tokens at a given time. Used by MemberRoles to check eligibility * for withdraw / switch membership. Includes tokens locked for Claim Assessment and staked for Risk Assessment. * Does not take into account pending burns. * * @param _of member whose locked tokens are to be calculate * @param _time timestamp when the tokens should be locked */ function totalLockedBalance(address _of, uint256 _time) public view returns (uint256 amount) { for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLockedAtTime(_of, lockReason[_of][i], _time)); } amount = amount.add(pooledStaking.stakerDeposit(_of)); } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _of address whose tokens are to be locked * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal { require(_tokensLocked(_of, _reason) == 0); require(_amount != 0); if (locked[_of][_reason].amount == 0) { lockReason[_of].push(_reason); } require(token.operatorTransfer(_of, _amount)); uint256 validUntil = now.add(_time); //solhint-disable-line locked[_of][_reason] = LockToken(_amount, validUntil, false); emit Locked(_of, _reason, _amount, validUntil); } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function _tokensLocked(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (!locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) internal view returns (uint256 amount) { if (locked[_of][_reason].validity > _time) { amount = locked[_of][_reason].amount; } } /** * @dev Extends lock for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function _extendLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); if (locked[_of][_reason].amount == 0) { _removeReason(_of, _reason); } token.burn(_amount); emit Burned(_of, _reason, _amount); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); if (locked[_of][_reason].amount == 0) { _removeReason(_of, _reason); } require(token.transfer(_of, _amount)); emit Unlocked(_of, _reason, _amount); } function _removeReason(address _of, bytes32 _reason) internal { uint len = lockReason[_of].length; for (uint i = 0; i < len; i++) { if (lockReason[_of][i] == _reason) { lockReason[_of][i] = lockReason[_of][len.sub(1)]; lockReason[_of].pop(); break; } } } } // File: nexusmutual-contracts/contracts/ClaimsData.sol /* Copyright (C) 2017 NexusMutual.io 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/ */ pragma solidity 0.5.7; contract ClaimsData is Iupgradable { using SafeMath for uint; struct Claim { uint coverId; uint dateUpd; } struct Vote { address voter; uint tokens; uint claimId; int8 verdict; bool rewardClaimed; } struct ClaimsPause { uint coverid; uint dateUpd; bool submit; } struct ClaimPauseVoting { uint claimid; uint pendingTime; bool voting; } struct RewardDistributed { uint lastCAvoteIndex; uint lastMVvoteIndex; } struct ClaimRewardDetails { uint percCA; uint percMV; uint tokenToBeDist; } struct ClaimTotalTokens { uint accept; uint deny; } struct ClaimRewardStatus { uint percCA; uint percMV; } ClaimRewardStatus[] internal rewardStatus; Claim[] internal allClaims; Vote[] internal allvotes; ClaimsPause[] internal claimPause; ClaimPauseVoting[] internal claimPauseVotingEP; mapping(address => RewardDistributed) internal voterVoteRewardReceived; mapping(uint => ClaimRewardDetails) internal claimRewardDetail; mapping(uint => ClaimTotalTokens) internal claimTokensCA; mapping(uint => ClaimTotalTokens) internal claimTokensMV; mapping(uint => int8) internal claimVote; mapping(uint => uint) internal claimsStatus; mapping(uint => uint) internal claimState12Count; mapping(uint => uint[]) internal claimVoteCA; mapping(uint => uint[]) internal claimVoteMember; mapping(address => uint[]) internal voteAddressCA; mapping(address => uint[]) internal voteAddressMember; mapping(address => uint[]) internal allClaimsByAddress; mapping(address => mapping(uint => uint)) internal userClaimVoteCA; mapping(address => mapping(uint => uint)) internal userClaimVoteMember; mapping(address => uint) public userClaimVotePausedOn; uint internal claimPauseLastsubmit; uint internal claimStartVotingFirstIndex; uint public pendingClaimStart; uint public claimDepositTime; uint public maxVotingTime; uint public minVotingTime; uint public payoutRetryTime; uint public claimRewardPerc; uint public minVoteThreshold; uint public maxVoteThreshold; uint public majorityConsensus; uint public pauseDaysCA; event ClaimRaise( uint indexed coverId, address indexed userAddress, uint claimId, uint dateSubmit ); event VoteCast( address indexed userAddress, uint indexed claimId, bytes4 indexed typeOf, uint tokens, uint submitDate, int8 verdict ); constructor() public { pendingClaimStart = 1; maxVotingTime = 48 * 1 hours; minVotingTime = 12 * 1 hours; payoutRetryTime = 24 * 1 hours; allvotes.push(Vote(address(0), 0, 0, 0, false)); allClaims.push(Claim(0, 0)); claimDepositTime = 7 days; claimRewardPerc = 20; minVoteThreshold = 5; maxVoteThreshold = 10; majorityConsensus = 70; pauseDaysCA = 3 days; _addRewardIncentive(); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function setpendingClaimStart(uint _start) external onlyInternal { require(pendingClaimStart <= _start); pendingClaimStart = _start; } /** * @dev Updates the max vote index for which claim assessor has received reward * @param _voter address of the voter. * @param caIndex last index till which reward was distributed for CA */ function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex; } /** * @dev Used to pause claim assessor activity for 3 days * @param user Member address whose claim voting ability needs to be paused */ function setUserClaimVotePausedOn(address user) external { require(ms.checkIsAuthToGoverned(msg.sender)); userClaimVotePausedOn[user] = now; } /** * @dev Updates the max vote index for which member has received reward * @param _voter address of the voter. * @param mvIndex last index till which reward was distributed for member */ function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex; } /** * @param claimid claim id. * @param percCA reward Percentage reward for claim assessor * @param percMV reward Percentage reward for members * @param tokens total tokens to be rewarded */ function setClaimRewardDetail( uint claimid, uint percCA, uint percMV, uint tokens ) external onlyInternal { claimRewardDetail[claimid].percCA = percCA; claimRewardDetail[claimid].percMV = percMV; claimRewardDetail[claimid].tokenToBeDist = tokens; } /** * @dev Sets the reward claim status against a vote id. * @param _voteid vote Id. * @param claimed true if reward for vote is claimed, else false. */ function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal { allvotes[_voteid].rewardClaimed = claimed; } /** * @dev Sets the final vote's result(either accepted or declined)of a claim. * @param _claimId Claim Id. * @param _verdict 1 if claim is accepted,-1 if declined. */ function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal { claimVote[_claimId] = _verdict; } /** * @dev Creates a new claim. */ function addClaim( uint _claimId, uint _coverId, address _from, uint _nowtime ) external onlyInternal { allClaims.push(Claim(_coverId, _nowtime)); allClaimsByAddress[_from].push(_claimId); } /** * @dev Add Vote's details of a given claim. */ function addVote( address _voter, uint _tokens, uint claimId, int8 _verdict ) external onlyInternal { allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false)); } /** * @dev Stores the id of the claim assessor vote given to a claim. * Maintains record of all votes given by all the CA to a claim. * @param _claimId Claim Id to which vote has given by the CA. * @param _voteid Vote Id. */ function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal { claimVoteCA[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Claim assessor's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the CA. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteCA( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteCA[_from][_claimId] = _voteid; voteAddressCA[_from].push(_voteid); } /** * @dev Stores the tokens locked by the Claim Assessors during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW if (_vote == -1) claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Stores the tokens locked by the Members during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW if (_vote == -1) claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Stores the id of the member vote given to a claim. * Maintains record of all votes given by all the Members to a claim. * @param _claimId Claim Id to which vote has been given by the Member. * @param _voteid Vote Id. */ function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal { claimVoteMember[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Member's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the Member. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteMember( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteMember[_from][_claimId] = _voteid; voteAddressMember[_from].push(_voteid); } /** * @dev Increases the count of failure until payout of a claim is successful. */ function updateState12Count(uint _claimId, uint _cnt) external onlyInternal { claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Sets status of a claim. * @param _claimId Claim Id. * @param _stat Status number. */ function setClaimStatus(uint _claimId, uint _stat) external onlyInternal { claimsStatus[_claimId] = _stat; } /** * @dev Sets the timestamp of a given claim at which the Claim's details has been updated. * @param _claimId Claim Id of claim which has been changed. * @param _dateUpd timestamp at which claim is updated. */ function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal { allClaims[_claimId].dateUpd = _dateUpd; } /** @dev Queues Claims during Emergency Pause. */ function setClaimAtEmergencyPause( uint _coverId, uint _dateUpd, bool _submit ) external onlyInternal { claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit)); } /** * @dev Set submission flag for Claims queued during emergency pause. * Set to true after EP is turned off and the claim is submitted . */ function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal { claimPause[_index].submit = _submit; } /** * @dev Sets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function setFirstClaimIndexToSubmitAfterEP( uint _firstClaimIndexToSubmit ) external onlyInternal { claimPauseLastsubmit = _firstClaimIndexToSubmit; } /** * @dev Sets the pending vote duration for a claim in case of emergency pause. */ function setPendingClaimDetails( uint _claimId, uint _pendingTime, bool _voting ) external onlyInternal { claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting)); } /** * @dev Sets voting flag true after claim is reopened for voting after emergency pause. */ function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal { claimPauseVotingEP[_claimId].voting = _vote; } /** * @dev Sets the index from which claim needs to be * reopened when emergency pause is swithched off. */ function setFirstClaimIndexToStartVotingAfterEP( uint _claimStartVotingFirstIndex ) external onlyInternal { claimStartVotingFirstIndex = _claimStartVotingFirstIndex; } /** * @dev Calls Vote Event. */ function callVoteEvent( address _userAddress, uint _claimId, bytes4 _typeOf, uint _tokens, uint _submitDate, int8 _verdict ) external onlyInternal { emit VoteCast( _userAddress, _claimId, _typeOf, _tokens, _submitDate, _verdict ); } /** * @dev Calls Claim Event. */ function callClaimEvent( uint _coverId, address _userAddress, uint _claimId, uint _datesubmit ) external onlyInternal { emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit); } /** * @dev Gets Uint Parameters by parameter code * @param code whose details we want * @return string value of the parameter * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "CAMAXVT") { val = maxVotingTime / (1 hours); } else if (code == "CAMINVT") { val = minVotingTime / (1 hours); } else if (code == "CAPRETRY") { val = payoutRetryTime / (1 hours); } else if (code == "CADEPT") { val = claimDepositTime / (1 days); } else if (code == "CAREWPER") { val = claimRewardPerc; } else if (code == "CAMINTH") { val = minVoteThreshold; } else if (code == "CAMAXTH") { val = maxVoteThreshold; } else if (code == "CACONPER") { val = majorityConsensus; } else if (code == "CAPAUSET") { val = pauseDaysCA / (1 days); } } /** * @dev Get claim queued during emergency pause by index. */ function getClaimOfEmergencyPauseByIndex( uint _index ) external view returns( uint coverId, uint dateUpd, bool submit ) { coverId = claimPause[_index].coverid; dateUpd = claimPause[_index].dateUpd; submit = claimPause[_index].submit; } /** * @dev Gets the Claim's details of given claimid. */ function getAllClaimsByIndex( uint _claimId ) external view returns( uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return( allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the vote id of a given claim of a given Claim Assessor. */ function getUserClaimVoteCA( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteCA[_add][_claimId]; } /** * @dev Gets the vote id of a given claim of a given member. */ function getUserClaimVoteMember( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteMember[_add][_claimId]; } /** * @dev Gets the count of all votes. */ function getAllVoteLength() external view returns(uint voteCount) { return allvotes.length.sub(1); //Start Index always from 1. } /** * @dev Gets the status number of a given claim. * @param _claimId Claim id. * @return statno Status Number. */ function getClaimStatusNumber(uint _claimId) external view returns(uint claimId, uint statno) { return (_claimId, claimsStatus[_claimId]); } /** * @dev Gets the reward percentage to be distributed for a given status id * @param statusNumber the number of type of status * @return percCA reward Percentage for claim assessor * @return percMV reward Percentage for members */ function getRewardStatus(uint statusNumber) external view returns(uint percCA, uint percMV) { return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV); } /** * @dev Gets the number of tries that have been made for a successful payout of a Claim. */ function getClaimState12Count(uint _claimId) external view returns(uint num) { num = claimState12Count[_claimId]; } /** * @dev Gets the last update date of a claim. */ function getClaimDateUpd(uint _claimId) external view returns(uint dateupd) { dateupd = allClaims[_claimId].dateUpd; } /** * @dev Gets all Claims created by a user till date. * @param _member user's address. * @return claimarr List of Claims id. */ function getAllClaimsByAddress(address _member) external view returns(uint[] memory claimarr) { return allClaimsByAddress[_member]; } /** * @dev Gets the number of tokens that has been locked * while giving vote to a claim by Claim Assessors. * @param _claimId Claim Id. * @return accept Total number of tokens when CA accepts the claim. * @return deny Total number of tokens when CA declines the claim. */ function getClaimsTokenCA( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensCA[_claimId].accept, claimTokensCA[_claimId].deny ); } /** * @dev Gets the number of tokens that have been * locked while assessing a claim as a member. * @param _claimId Claim Id. * @return accept Total number of tokens in acceptance of the claim. * @return deny Total number of tokens against the claim. */ function getClaimsTokenMV( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensMV[_claimId].accept, claimTokensMV[_claimId].deny ); } /** * @dev Gets the total number of votes cast as Claims assessor for/against a given claim */ function getCaClaimVotesToken(uint _claimId) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets the total number of tokens cast as a member for/against a given claim */ function getMemberClaimVotesToken( uint _claimId ) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @dev Provides information of a vote when given its vote id. * @param _voteid Vote Id. */ function getVoteDetails(uint _voteid) external view returns( uint tokens, uint claimId, int8 verdict, bool rewardClaimed ) { return ( allvotes[_voteid].tokens, allvotes[_voteid].claimId, allvotes[_voteid].verdict, allvotes[_voteid].rewardClaimed ); } /** * @dev Gets the voter's address of a given vote id. */ function getVoterVote(uint _voteid) external view returns(address voter) { return allvotes[_voteid].voter; } /** * @dev Provides information of a Claim when given its claim id. * @param _claimId Claim Id. */ function getClaim( uint _claimId ) external view returns( uint claimId, uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return ( _claimId, allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the total number of votes of a given claim. * @param _claimId Claim Id. * @param _ca if 1: votes given by Claim Assessors to a claim, * else returns the number of votes of given by Members to a claim. * @return len total number of votes for/against a given claim. */ function getClaimVoteLength( uint _claimId, uint8 _ca ) external view returns(uint claimId, uint len) { claimId = _claimId; if (_ca == 1) len = claimVoteCA[_claimId].length; else len = claimVoteMember[_claimId].length; } /** * @dev Gets the verdict of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return ver 1 if vote was given in favour,-1 if given in against. */ function getVoteVerdict( uint _claimId, uint _index, uint8 _ca ) external view returns(int8 ver) { if (_ca == 1) ver = allvotes[claimVoteCA[_claimId][_index]].verdict; else ver = allvotes[claimVoteMember[_claimId][_index]].verdict; } /** * @dev Gets the Number of tokens of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return tok Number of tokens. */ function getVoteToken( uint _claimId, uint _index, uint8 _ca ) external view returns(uint tok) { if (_ca == 1) tok = allvotes[claimVoteCA[_claimId][_index]].tokens; else tok = allvotes[claimVoteMember[_claimId][_index]].tokens; } /** * @dev Gets the Voter's address of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return voter Voter's address. */ function getVoteVoter( uint _claimId, uint _index, uint8 _ca ) external view returns(address voter) { if (_ca == 1) voter = allvotes[claimVoteCA[_claimId][_index]].voter; else voter = allvotes[claimVoteMember[_claimId][_index]].voter; } /** * @dev Gets total number of Claims created by a user till date. * @param _add User's address. */ function getUserClaimCount(address _add) external view returns(uint len) { len = allClaimsByAddress[_add].length; } /** * @dev Calculates number of Claims that are in pending state. */ function getClaimLength() external view returns(uint len) { len = allClaims.length.sub(pendingClaimStart); } /** * @dev Gets the Number of all the Claims created till date. */ function actualClaimLength() external view returns(uint len) { len = allClaims.length; } /** * @dev Gets details of a claim. * @param _index claim id = pending claim start + given index * @param _add User's address. * @return coverid cover against which claim has been submitted. * @return claimId Claim Id. * @return voteCA verdict of vote given as a Claim Assessor. * @return voteMV verdict of vote given as a Member. * @return statusnumber Status of claim. */ function getClaimFromNewStart( uint _index, address _add ) external view returns( uint coverid, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { uint i = pendingClaimStart.add(_index); coverid = allClaims[i].coverId; claimId = i; if (userClaimVoteCA[_add][i] > 0) voteCA = allvotes[userClaimVoteCA[_add][i]].verdict; else voteCA = 0; if (userClaimVoteMember[_add][i] > 0) voteMV = allvotes[userClaimVoteMember[_add][i]].verdict; else voteMV = 0; statusnumber = claimsStatus[i]; } /** * @dev Gets details of a claim of a user at a given index. */ function getUserClaimByIndex( uint _index, address _add ) external view returns( uint status, uint coverid, uint claimId ) { claimId = allClaimsByAddress[_add][_index]; status = claimsStatus[claimId]; coverid = allClaims[claimId].coverId; } /** * @dev Gets Id of all the votes given to a claim. * @param _claimId Claim Id. * @return ca id of all the votes given by Claim assessors to a claim. * @return mv id of all the votes given by members to a claim. */ function getAllVotesForClaim( uint _claimId ) external view returns( uint claimId, uint[] memory ca, uint[] memory mv ) { return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]); } /** * @dev Gets Number of tokens deposit in a vote using * Claim assessor's address and claim id. * @return tokens Number of deposited tokens. */ function getTokensClaim( address _of, uint _claimId ) external view returns( uint claimId, uint tokens ) { return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens); } /** * @param _voter address of the voter. * @return lastCAvoteIndex last index till which reward was distributed for CA * @return lastMVvoteIndex last index till which reward was distributed for member */ function getRewardDistributedIndex( address _voter ) external view returns( uint lastCAvoteIndex, uint lastMVvoteIndex ) { return ( voterVoteRewardReceived[_voter].lastCAvoteIndex, voterVoteRewardReceived[_voter].lastMVvoteIndex ); } /** * @param claimid claim id. * @return perc_CA reward Percentage for claim assessor * @return perc_MV reward Percentage for members * @return tokens total tokens to be rewarded */ function getClaimRewardDetail( uint claimid ) external view returns( uint percCA, uint percMV, uint tokens ) { return ( claimRewardDetail[claimid].percCA, claimRewardDetail[claimid].percMV, claimRewardDetail[claimid].tokenToBeDist ); } /** * @dev Gets cover id of a claim. */ function getClaimCoverId(uint _claimId) external view returns(uint claimId, uint coverid) { return (_claimId, allClaims[_claimId].coverId); } /** * @dev Gets total number of tokens staked during voting by Claim Assessors. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter). */ function getClaimVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets total number of tokens staked during voting by Members. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, * -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or * deny on the basis of verdict given as parameter). */ function getClaimMVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @param _voter address of voteid * @param index index to get voteid in CA */ function getVoteAddressCA(address _voter, uint index) external view returns(uint) { return voteAddressCA[_voter][index]; } /** * @param _voter address of voter * @param index index to get voteid in member vote */ function getVoteAddressMember(address _voter, uint index) external view returns(uint) { return voteAddressMember[_voter][index]; } /** * @param _voter address of voter */ function getVoteAddressCALength(address _voter) external view returns(uint) { return voteAddressCA[_voter].length; } /** * @param _voter address of voter */ function getVoteAddressMemberLength(address _voter) external view returns(uint) { return voteAddressMember[_voter].length; } /** * @dev Gets the Final result of voting of a claim. * @param _claimId Claim id. * @return verdict 1 if claim is accepted, -1 if declined. */ function getFinalVerdict(uint _claimId) external view returns(int8 verdict) { return claimVote[_claimId]; } /** * @dev Get number of Claims queued for submission during emergency pause. */ function getLengthOfClaimSubmittedAtEP() external view returns(uint len) { len = claimPause.length; } /** * @dev Gets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function getFirstClaimIndexToSubmitAfterEP() external view returns(uint indexToSubmit) { indexToSubmit = claimPauseLastsubmit; } /** * @dev Gets number of Claims to be reopened for voting post emergency pause period. */ function getLengthOfClaimVotingPause() external view returns(uint len) { len = claimPauseVotingEP.length; } /** * @dev Gets claim details to be reopened for voting after emergency pause. */ function getPendingClaimDetailsByIndex( uint _index ) external view returns( uint claimId, uint pendingTime, bool voting ) { claimId = claimPauseVotingEP[_index].claimid; pendingTime = claimPauseVotingEP[_index].pendingTime; voting = claimPauseVotingEP[_index].voting; } /** * @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off. */ function getFirstClaimIndexToStartVotingAfterEP() external view returns(uint firstindex) { firstindex = claimStartVotingFirstIndex; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "CAMAXVT") { _setMaxVotingTime(val * 1 hours); } else if (code == "CAMINVT") { _setMinVotingTime(val * 1 hours); } else if (code == "CAPRETRY") { _setPayoutRetryTime(val * 1 hours); } else if (code == "CADEPT") { _setClaimDepositTime(val * 1 days); } else if (code == "CAREWPER") { _setClaimRewardPerc(val); } else if (code == "CAMINTH") { _setMinVoteThreshold(val); } else if (code == "CAMAXTH") { _setMaxVoteThreshold(val); } else if (code == "CACONPER") { _setMajorityConsensus(val); } else if (code == "CAPAUSET") { _setPauseDaysCA(val * 1 days); } else { revert("Invalid param code"); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal {} /** * @dev Adds status under which a claim can lie. * @param percCA reward percentage for claim assessor * @param percMV reward percentage for members */ function _pushStatus(uint percCA, uint percMV) internal { rewardStatus.push(ClaimRewardStatus(percCA, percMV)); } /** * @dev adds reward incentive for all possible claim status for Claim assessors and members */ function _addRewardIncentive() internal { _pushStatus(0, 0); //0 Pending-Claim Assessor Vote _pushStatus(0, 0); //1 Pending-Claim Assessor Vote Denied, Pending Member Vote _pushStatus(0, 0); //2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote _pushStatus(0, 0); //3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote _pushStatus(0, 0); //4 Pending-CA Consensus not reached Accept, Pending Member Vote _pushStatus(0, 0); //5 Pending-CA Consensus not reached Deny, Pending Member Vote _pushStatus(100, 0); //6 Final-Claim Assessor Vote Denied _pushStatus(100, 0); //7 Final-Claim Assessor Vote Accepted _pushStatus(0, 100); //8 Final-Claim Assessor Vote Denied, MV Accepted _pushStatus(0, 100); //9 Final-Claim Assessor Vote Denied, MV Denied _pushStatus(0, 0); //10 Final-Claim Assessor Vote Accept, MV Nodecision _pushStatus(0, 0); //11 Final-Claim Assessor Vote Denied, MV Nodecision _pushStatus(0, 0); //12 Claim Accepted Payout Pending _pushStatus(0, 0); //13 Claim Accepted No Payout _pushStatus(0, 0); //14 Claim Accepted Payout Done } /** * @dev Sets Maximum time(in seconds) for which claim assessment voting is open */ function _setMaxVotingTime(uint _time) internal { maxVotingTime = _time; } /** * @dev Sets Minimum time(in seconds) for which claim assessment voting is open */ function _setMinVotingTime(uint _time) internal { minVotingTime = _time; } /** * @dev Sets Minimum vote threshold required */ function _setMinVoteThreshold(uint val) internal { minVoteThreshold = val; } /** * @dev Sets Maximum vote threshold required */ function _setMaxVoteThreshold(uint val) internal { maxVoteThreshold = val; } /** * @dev Sets the value considered as Majority Consenus in voting */ function _setMajorityConsensus(uint val) internal { majorityConsensus = val; } /** * @dev Sets the payout retry time */ function _setPayoutRetryTime(uint _time) internal { payoutRetryTime = _time; } /** * @dev Sets percentage of reward given for claim assessment */ function _setClaimRewardPerc(uint _val) internal { claimRewardPerc = _val; } /** * @dev Sets the time for which claim is deposited. */ function _setClaimDepositTime(uint _time) internal { claimDepositTime = _time; } /** * @dev Sets number of days claim assessment will be paused */ function _setPauseDaysCA(uint val) internal { pauseDaysCA = val; } } // File: nexusmutual-contracts/contracts/PoolData.sol /* Copyright (C) 2017 NexusMutual.io 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/ */ pragma solidity 0.5.7; contract DSValue { function peek() public view returns (bytes32, bool); function read() public view returns (bytes32); } contract PoolData is Iupgradable { using SafeMath for uint; struct ApiId { bytes4 typeOf; bytes4 currency; uint id; uint64 dateAdd; uint64 dateUpd; } struct CurrencyAssets { address currAddress; uint baseMin; uint varMin; } struct InvestmentAssets { address currAddress; bool status; uint64 minHoldingPercX100; uint64 maxHoldingPercX100; uint8 decimals; } struct IARankDetails { bytes4 maxIACurr; uint64 maxRate; bytes4 minIACurr; uint64 minRate; } struct McrData { uint mcrPercx100; uint mcrEther; uint vFull; //Pool funds uint64 date; } IARankDetails[] internal allIARankDetails; McrData[] public allMCRData; bytes4[] internal allInvestmentCurrencies; bytes4[] internal allCurrencies; bytes32[] public allAPIcall; mapping(bytes32 => ApiId) public allAPIid; mapping(uint64 => uint) internal datewiseId; mapping(bytes16 => uint) internal currencyLastIndex; mapping(bytes4 => CurrencyAssets) internal allCurrencyAssets; mapping(bytes4 => InvestmentAssets) internal allInvestmentAssets; mapping(bytes4 => uint) internal caAvgRate; mapping(bytes4 => uint) internal iaAvgRate; address public notariseMCR; address public daiFeedAddress; uint private constant DECIMAL1E18 = uint(10) ** 18; uint public uniswapDeadline; uint public liquidityTradeCallbackTime; uint public lastLiquidityTradeTrigger; uint64 internal lastDate; uint public variationPercX100; uint public iaRatesTime; uint public minCap; uint public mcrTime; uint public a; uint public shockParameter; uint public c; uint public mcrFailTime; uint public ethVolumeLimit; uint public capReached; uint public capacityLimit; constructor(address _notariseAdd, address _daiFeedAdd, address _daiAdd) public { notariseMCR = _notariseAdd; daiFeedAddress = _daiFeedAdd; c = 5800000; a = 1028; mcrTime = 24 hours; mcrFailTime = 6 hours; allMCRData.push(McrData(0, 0, 0, 0)); minCap = 12000 * DECIMAL1E18; shockParameter = 50; variationPercX100 = 100; //1% iaRatesTime = 24 hours; //24 hours in seconds uniswapDeadline = 20 minutes; liquidityTradeCallbackTime = 4 hours; ethVolumeLimit = 4; capacityLimit = 10; allCurrencies.push("ETH"); allCurrencyAssets["ETH"] = CurrencyAssets(address(0), 1000 * DECIMAL1E18, 0); allCurrencies.push("DAI"); allCurrencyAssets["DAI"] = CurrencyAssets(_daiAdd, 50000 * DECIMAL1E18, 0); allInvestmentCurrencies.push("ETH"); allInvestmentAssets["ETH"] = InvestmentAssets(address(0), true, 2500, 10000, 18); allInvestmentCurrencies.push("DAI"); allInvestmentAssets["DAI"] = InvestmentAssets(_daiAdd, true, 250, 1500, 18); } /** * @dev to set the maximum cap allowed * @param val is the new value */ function setCapReached(uint val) external onlyInternal { capReached = val; } /// @dev Updates the 3 day average rate of a IA currency. /// To be replaced by MakerDao's on chain rates /// @param curr IA Currency Name. /// @param rate Average exchange rate X 100 (of last 3 days). function updateIAAvgRate(bytes4 curr, uint rate) external onlyInternal { iaAvgRate[curr] = rate; } /// @dev Updates the 3 day average rate of a CA currency. /// To be replaced by MakerDao's on chain rates /// @param curr Currency Name. /// @param rate Average exchange rate X 100 (of last 3 days). function updateCAAvgRate(bytes4 curr, uint rate) external onlyInternal { caAvgRate[curr] = rate; } /// @dev Adds details of (Minimum Capital Requirement)MCR. /// @param mcrp Minimum Capital Requirement percentage (MCR% * 100 ,Ex:for 54.56% ,given 5456) /// @param vf Pool fund value in Ether used in the last full daily calculation from the Capital model. function pushMCRData(uint mcrp, uint mcre, uint vf, uint64 time) external onlyInternal { allMCRData.push(McrData(mcrp, mcre, vf, time)); } /** * @dev Updates the Timestamp at which result of oracalize call is received. */ function updateDateUpdOfAPI(bytes32 myid) external onlyInternal { allAPIid[myid].dateUpd = uint64(now); } /** * @dev Saves the details of the Oraclize API. * @param myid Id return by the oraclize query. * @param _typeof type of the query for which oraclize call is made. * @param id ID of the proposal,quote,cover etc. for which oraclize call is made */ function saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) external onlyInternal { allAPIid[myid] = ApiId(_typeof, "", id, uint64(now), uint64(now)); } /** * @dev Stores the id return by the oraclize query. * Maintains record of all the Ids return by oraclize query. * @param myid Id return by the oraclize query. */ function addInAllApiCall(bytes32 myid) external onlyInternal { allAPIcall.push(myid); } /** * @dev Saves investment asset rank details. * @param maxIACurr Maximum ranked investment asset currency. * @param maxRate Maximum ranked investment asset rate. * @param minIACurr Minimum ranked investment asset currency. * @param minRate Minimum ranked investment asset rate. * @param date in yyyymmdd. */ function saveIARankDetails( bytes4 maxIACurr, uint64 maxRate, bytes4 minIACurr, uint64 minRate, uint64 date ) external onlyInternal { allIARankDetails.push(IARankDetails(maxIACurr, maxRate, minIACurr, minRate)); datewiseId[date] = allIARankDetails.length.sub(1); } /** * @dev to get the time for the laste liquidity trade trigger */ function setLastLiquidityTradeTrigger() external onlyInternal { lastLiquidityTradeTrigger = now; } /** * @dev Updates Last Date. */ function updatelastDate(uint64 newDate) external onlyInternal { lastDate = newDate; } /** * @dev Adds currency asset currency. * @param curr currency of the asset * @param currAddress address of the currency * @param baseMin base minimum in 10^18. */ function addCurrencyAssetCurrency( bytes4 curr, address currAddress, uint baseMin ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencies.push(curr); allCurrencyAssets[curr] = CurrencyAssets(currAddress, baseMin, 0); } /** * @dev Adds investment asset. */ function addInvestmentAssetCurrency( bytes4 curr, address currAddress, bool status, uint64 minHoldingPercX100, uint64 maxHoldingPercX100, uint8 decimals ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentCurrencies.push(curr); allInvestmentAssets[curr] = InvestmentAssets(currAddress, status, minHoldingPercX100, maxHoldingPercX100, decimals); } /** * @dev Changes base minimum of a given currency asset. */ function changeCurrencyAssetBaseMin(bytes4 curr, uint baseMin) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencyAssets[curr].baseMin = baseMin; } /** * @dev changes variable minimum of a given currency asset. */ function changeCurrencyAssetVarMin(bytes4 curr, uint varMin) external onlyInternal { allCurrencyAssets[curr].varMin = varMin; } /** * @dev Changes the investment asset status. */ function changeInvestmentAssetStatus(bytes4 curr, bool status) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].status = status; } /** * @dev Changes the investment asset Holding percentage of a given currency. */ function changeInvestmentAssetHoldingPerc( bytes4 curr, uint64 minPercX100, uint64 maxPercX100 ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].minHoldingPercX100 = minPercX100; allInvestmentAssets[curr].maxHoldingPercX100 = maxPercX100; } /** * @dev Gets Currency asset token address. */ function changeCurrencyAssetAddress(bytes4 curr, address currAdd) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencyAssets[curr].currAddress = currAdd; } /** * @dev Changes Investment asset token address. */ function changeInvestmentAssetAddressAndDecimal( bytes4 curr, address currAdd, uint8 newDecimal ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].currAddress = currAdd; allInvestmentAssets[curr].decimals = newDecimal; } /// @dev Changes address allowed to post MCR. function changeNotariseAddress(address _add) external onlyInternal { notariseMCR = _add; } /// @dev updates daiFeedAddress address. /// @param _add address of DAI feed. function changeDAIfeedAddress(address _add) external onlyInternal { daiFeedAddress = _add; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "MCRTIM") { val = mcrTime / (1 hours); } else if (code == "MCRFTIM") { val = mcrFailTime / (1 hours); } else if (code == "MCRMIN") { val = minCap; } else if (code == "MCRSHOCK") { val = shockParameter; } else if (code == "MCRCAPL") { val = capacityLimit; } else if (code == "IMZ") { val = variationPercX100; } else if (code == "IMRATET") { val = iaRatesTime / (1 hours); } else if (code == "IMUNIDL") { val = uniswapDeadline / (1 minutes); } else if (code == "IMLIQT") { val = liquidityTradeCallbackTime / (1 hours); } else if (code == "IMETHVL") { val = ethVolumeLimit; } else if (code == "C") { val = c; } else if (code == "A") { val = a; } } /// @dev Checks whether a given address can notaise MCR data or not. /// @param _add Address. /// @return res Returns 0 if address is not authorized, else 1. function isnotarise(address _add) external view returns(bool res) { res = false; if (_add == notariseMCR) res = true; } /// @dev Gets the details of last added MCR. /// @return mcrPercx100 Total Minimum Capital Requirement percentage of that month of year(multiplied by 100). /// @return vFull Total Pool fund value in Ether used in the last full daily calculation. function getLastMCR() external view returns(uint mcrPercx100, uint mcrEtherx1E18, uint vFull, uint64 date) { uint index = allMCRData.length.sub(1); return ( allMCRData[index].mcrPercx100, allMCRData[index].mcrEther, allMCRData[index].vFull, allMCRData[index].date ); } /// @dev Gets last Minimum Capital Requirement percentage of Capital Model /// @return val MCR% value,multiplied by 100. function getLastMCRPerc() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].mcrPercx100; } /// @dev Gets last Ether price of Capital Model /// @return val ether value,multiplied by 100. function getLastMCREther() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].mcrEther; } /// @dev Gets Pool fund value in Ether used in the last full daily calculation from the Capital model. function getLastVfull() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].vFull; } /// @dev Gets last Minimum Capital Requirement in Ether. /// @return date of MCR. function getLastMCRDate() external view returns(uint64 date) { date = allMCRData[allMCRData.length.sub(1)].date; } /// @dev Gets details for token price calculation. function getTokenPriceDetails(bytes4 curr) external view returns(uint _a, uint _c, uint rate) { _a = a; _c = c; rate = _getAvgRate(curr, false); } /// @dev Gets the total number of times MCR calculation has been made. function getMCRDataLength() external view returns(uint len) { len = allMCRData.length; } /** * @dev Gets investment asset rank details by given date. */ function getIARankDetailsByDate( uint64 date ) external view returns( bytes4 maxIACurr, uint64 maxRate, bytes4 minIACurr, uint64 minRate ) { uint index = datewiseId[date]; return ( allIARankDetails[index].maxIACurr, allIARankDetails[index].maxRate, allIARankDetails[index].minIACurr, allIARankDetails[index].minRate ); } /** * @dev Gets Last Date. */ function getLastDate() external view returns(uint64 date) { return lastDate; } /** * @dev Gets investment currency for a given index. */ function getInvestmentCurrencyByIndex(uint index) external view returns(bytes4 currName) { return allInvestmentCurrencies[index]; } /** * @dev Gets count of investment currency. */ function getInvestmentCurrencyLen() external view returns(uint len) { return allInvestmentCurrencies.length; } /** * @dev Gets all the investment currencies. */ function getAllInvestmentCurrencies() external view returns(bytes4[] memory currencies) { return allInvestmentCurrencies; } /** * @dev Gets All currency for a given index. */ function getCurrenciesByIndex(uint index) external view returns(bytes4 currName) { return allCurrencies[index]; } /** * @dev Gets count of All currency. */ function getAllCurrenciesLen() external view returns(uint len) { return allCurrencies.length; } /** * @dev Gets all currencies */ function getAllCurrencies() external view returns(bytes4[] memory currencies) { return allCurrencies; } /** * @dev Gets currency asset details for a given currency. */ function getCurrencyAssetVarBase( bytes4 curr ) external view returns( bytes4 currency, uint baseMin, uint varMin ) { return ( curr, allCurrencyAssets[curr].baseMin, allCurrencyAssets[curr].varMin ); } /** * @dev Gets minimum variable value for currency asset. */ function getCurrencyAssetVarMin(bytes4 curr) external view returns(uint varMin) { return allCurrencyAssets[curr].varMin; } /** * @dev Gets base minimum of a given currency asset. */ function getCurrencyAssetBaseMin(bytes4 curr) external view returns(uint baseMin) { return allCurrencyAssets[curr].baseMin; } /** * @dev Gets investment asset maximum and minimum holding percentage of a given currency. */ function getInvestmentAssetHoldingPerc( bytes4 curr ) external view returns( uint64 minHoldingPercX100, uint64 maxHoldingPercX100 ) { return ( allInvestmentAssets[curr].minHoldingPercX100, allInvestmentAssets[curr].maxHoldingPercX100 ); } /** * @dev Gets investment asset decimals. */ function getInvestmentAssetDecimals(bytes4 curr) external view returns(uint8 decimal) { return allInvestmentAssets[curr].decimals; } /** * @dev Gets investment asset maximum holding percentage of a given currency. */ function getInvestmentAssetMaxHoldingPerc(bytes4 curr) external view returns(uint64 maxHoldingPercX100) { return allInvestmentAssets[curr].maxHoldingPercX100; } /** * @dev Gets investment asset minimum holding percentage of a given currency. */ function getInvestmentAssetMinHoldingPerc(bytes4 curr) external view returns(uint64 minHoldingPercX100) { return allInvestmentAssets[curr].minHoldingPercX100; } /** * @dev Gets investment asset details of a given currency */ function getInvestmentAssetDetails( bytes4 curr ) external view returns( bytes4 currency, address currAddress, bool status, uint64 minHoldingPerc, uint64 maxHoldingPerc, uint8 decimals ) { return ( curr, allInvestmentAssets[curr].currAddress, allInvestmentAssets[curr].status, allInvestmentAssets[curr].minHoldingPercX100, allInvestmentAssets[curr].maxHoldingPercX100, allInvestmentAssets[curr].decimals ); } /** * @dev Gets Currency asset token address. */ function getCurrencyAssetAddress(bytes4 curr) external view returns(address) { return allCurrencyAssets[curr].currAddress; } /** * @dev Gets investment asset token address. */ function getInvestmentAssetAddress(bytes4 curr) external view returns(address) { return allInvestmentAssets[curr].currAddress; } /** * @dev Gets investment asset active Status of a given currency. */ function getInvestmentAssetStatus(bytes4 curr) external view returns(bool status) { return allInvestmentAssets[curr].status; } /** * @dev Gets type of oraclize query for a given Oraclize Query ID. * @param myid Oraclize Query ID identifying the query for which the result is being received. * @return _typeof It could be of type "quote","quotation","cover","claim" etc. */ function getApiIdTypeOf(bytes32 myid) external view returns(bytes4) { return allAPIid[myid].typeOf; } /** * @dev Gets ID associated to oraclize query for a given Oraclize Query ID. * @param myid Oraclize Query ID identifying the query for which the result is being received. * @return id1 It could be the ID of "proposal","quotation","cover","claim" etc. */ function getIdOfApiId(bytes32 myid) external view returns(uint) { return allAPIid[myid].id; } /** * @dev Gets the Timestamp of a oracalize call. */ function getDateAddOfAPI(bytes32 myid) external view returns(uint64) { return allAPIid[myid].dateAdd; } /** * @dev Gets the Timestamp at which result of oracalize call is received. */ function getDateUpdOfAPI(bytes32 myid) external view returns(uint64) { return allAPIid[myid].dateUpd; } /** * @dev Gets currency by oracalize id. */ function getCurrOfApiId(bytes32 myid) external view returns(bytes4) { return allAPIid[myid].currency; } /** * @dev Gets ID return by the oraclize query of a given index. * @param index Index. * @return myid ID return by the oraclize query. */ function getApiCallIndex(uint index) external view returns(bytes32 myid) { myid = allAPIcall[index]; } /** * @dev Gets Length of API call. */ function getApilCallLength() external view returns(uint) { return allAPIcall.length; } /** * @dev Get Details of Oraclize API when given Oraclize Id. * @param myid ID return by the oraclize query. * @return _typeof ype of the query for which oraclize * call is made.("proposal","quote","quotation" etc.) */ function getApiCallDetails( bytes32 myid ) external view returns( bytes4 _typeof, bytes4 curr, uint id, uint64 dateAdd, uint64 dateUpd ) { return ( allAPIid[myid].typeOf, allAPIid[myid].currency, allAPIid[myid].id, allAPIid[myid].dateAdd, allAPIid[myid].dateUpd ); } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "MCRTIM") { _changeMCRTime(val * 1 hours); } else if (code == "MCRFTIM") { _changeMCRFailTime(val * 1 hours); } else if (code == "MCRMIN") { _changeMinCap(val); } else if (code == "MCRSHOCK") { _changeShockParameter(val); } else if (code == "MCRCAPL") { _changeCapacityLimit(val); } else if (code == "IMZ") { _changeVariationPercX100(val); } else if (code == "IMRATET") { _changeIARatesTime(val * 1 hours); } else if (code == "IMUNIDL") { _changeUniswapDeadlineTime(val * 1 minutes); } else if (code == "IMLIQT") { _changeliquidityTradeCallbackTime(val * 1 hours); } else if (code == "IMETHVL") { _setEthVolumeLimit(val); } else if (code == "C") { _changeC(val); } else if (code == "A") { _changeA(val); } else { revert("Invalid param code"); } } /** * @dev to get the average rate of currency rate * @param curr is the currency in concern * @return required rate */ function getCAAvgRate(bytes4 curr) public view returns(uint rate) { return _getAvgRate(curr, false); } /** * @dev to get the average rate of investment rate * @param curr is the investment in concern * @return required rate */ function getIAAvgRate(bytes4 curr) public view returns(uint rate) { return _getAvgRate(curr, true); } function changeDependentContractAddress() public onlyInternal {} /// @dev Gets the average rate of a CA currency. /// @param curr Currency Name. /// @return rate Average rate X 100(of last 3 days). function _getAvgRate(bytes4 curr, bool isIA) internal view returns(uint rate) { if (curr == "DAI") { DSValue ds = DSValue(daiFeedAddress); rate = uint(ds.read()).div(uint(10) ** 16); } else if (isIA) { rate = iaAvgRate[curr]; } else { rate = caAvgRate[curr]; } } /** * @dev to set the ethereum volume limit * @param val is the new limit value */ function _setEthVolumeLimit(uint val) internal { ethVolumeLimit = val; } /// @dev Sets minimum Cap. function _changeMinCap(uint newCap) internal { minCap = newCap; } /// @dev Sets Shock Parameter. function _changeShockParameter(uint newParam) internal { shockParameter = newParam; } /// @dev Changes time period for obtaining new MCR data from external oracle query. function _changeMCRTime(uint _time) internal { mcrTime = _time; } /// @dev Sets MCR Fail time. function _changeMCRFailTime(uint _time) internal { mcrFailTime = _time; } /** * @dev to change the uniswap deadline time * @param newDeadline is the value */ function _changeUniswapDeadlineTime(uint newDeadline) internal { uniswapDeadline = newDeadline; } /** * @dev to change the liquidity trade call back time * @param newTime is the new value to be set */ function _changeliquidityTradeCallbackTime(uint newTime) internal { liquidityTradeCallbackTime = newTime; } /** * @dev Changes time after which investment asset rates need to be fed. */ function _changeIARatesTime(uint _newTime) internal { iaRatesTime = _newTime; } /** * @dev Changes the variation range percentage. */ function _changeVariationPercX100(uint newPercX100) internal { variationPercX100 = newPercX100; } /// @dev Changes Growth Step function _changeC(uint newC) internal { c = newC; } /// @dev Changes scaling factor. function _changeA(uint val) internal { a = val; } /** * @dev to change the capacity limit * @param val is the new value */ function _changeCapacityLimit(uint val) internal { capacityLimit = val; } } // File: nexusmutual-contracts/contracts/QuotationData.sol /* Copyright (C) 2017 NexusMutual.io 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/ */ pragma solidity 0.5.7; contract QuotationData is Iupgradable { using SafeMath for uint; enum HCIDStatus { NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover } enum CoverStatus { Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested } struct Cover { address payable memberAddress; bytes4 currencyCode; uint sumAssured; uint16 coverPeriod; uint validUntil; address scAddress; uint premiumNXM; } struct HoldCover { uint holdCoverId; address payable userAddress; address scAddress; bytes4 coverCurr; uint[] coverDetails; uint16 coverPeriod; } address public authQuoteEngine; mapping(bytes4 => uint) internal currencyCSA; mapping(address => uint[]) internal userCover; mapping(address => uint[]) public userHoldedCover; mapping(address => bool) public refundEligible; mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd; mapping(uint => uint8) public coverStatus; mapping(uint => uint) public holdedCoverIDStatus; mapping(uint => bool) public timestampRepeated; Cover[] internal allCovers; HoldCover[] internal allCoverHolded; uint public stlp; uint public stl; uint public pm; uint public minDays; uint public tokensRetained; address public kycAuthAddress; event CoverDetailsEvent( uint indexed cid, address scAdd, uint sumAssured, uint expiry, uint premium, uint premiumNXM, bytes4 curr ); event CoverStatusEvent(uint indexed cid, uint8 statusNum); constructor(address _authQuoteAdd, address _kycAuthAdd) public { authQuoteEngine = _authQuoteAdd; kycAuthAddress = _kycAuthAdd; stlp = 90; stl = 100; pm = 30; minDays = 30; tokensRetained = 10; allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0)); uint[] memory arr = new uint[](1); allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0)); } /// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be added. function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be subtracted. function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount); } /// @dev Subtracts the amount from Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be subtracted. function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].sub(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev Adds the amount in Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be added. function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev sets bit for timestamp to avoid replay attacks. function setTimestampRepeated(uint _timestamp) external onlyInternal { timestampRepeated[_timestamp] = true; } /// @dev Creates a blank new cover. function addCover( uint16 _coverPeriod, uint _sumAssured, address payable _userAddress, bytes4 _currencyCode, address _scAddress, uint premium, uint premiumNXM ) external onlyInternal { uint expiryDate = now.add(uint(_coverPeriod).mul(1 days)); allCovers.push(Cover(_userAddress, _currencyCode, _sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM)); uint cid = allCovers.length.sub(1); userCover[_userAddress].push(cid); emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode); } /// @dev create holded cover which will process after verdict of KYC. function addHoldCover( address payable from, address scAddress, bytes4 coverCurr, uint[] calldata coverDetails, uint16 coverPeriod ) external onlyInternal { uint holdedCoverLen = allCoverHolded.length; holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending); allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress, coverCurr, coverDetails, coverPeriod)); userHoldedCover[from].push(allCoverHolded.length.sub(1)); } ///@dev sets refund eligible bit. ///@param _add user address. ///@param status indicates if user have pending kyc. function setRefundEligible(address _add, bool status) external onlyInternal { refundEligible[_add] = status; } /// @dev to set current status of particular holded coverID (1 for not completed KYC, /// 2 for KYC passed, 3 for failed KYC or full refunded, /// 4 for KYC completed but cover not processed) function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal { holdedCoverIDStatus[holdedCoverID] = status; } /** * @dev to set address of kyc authentication * @param _add is the new address */ function setKycAuthAddress(address _add) external onlyInternal { kycAuthAddress = _add; } /// @dev Changes authorised address for generating quote off chain. function changeAuthQuoteEngine(address _add) external onlyInternal { authQuoteEngine = _add; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "STLP") { val = stlp; } else if (code == "STL") { val = stl; } else if (code == "PM") { val = pm; } else if (code == "QUOMIND") { val = minDays; } else if (code == "QUOTOK") { val = tokensRetained; } } /// @dev Gets Product details. /// @return _minDays minimum cover period. /// @return _PM Profit margin. /// @return _STL short term Load. /// @return _STLP short term load period. function getProductDetails() external view returns ( uint _minDays, uint _pm, uint _stl, uint _stlp ) { _minDays = minDays; _pm = pm; _stl = stl; _stlp = stlp; } /// @dev Gets total number covers created till date. function getCoverLength() external view returns(uint len) { return (allCovers.length); } /// @dev Gets Authorised Engine address. function getAuthQuoteEngine() external view returns(address _add) { _add = authQuoteEngine; } /// @dev Gets the Total Sum Assured amount of a given currency. function getTotalSumAssured(bytes4 _curr) external view returns(uint amount) { amount = currencyCSA[_curr]; } /// @dev Gets all the Cover ids generated by a given address. /// @param _add User's address. /// @return allCover array of covers. function getAllCoversOfUser(address _add) external view returns(uint[] memory allCover) { return (userCover[_add]); } /// @dev Gets total number of covers generated by a given address function getUserCoverLength(address _add) external view returns(uint len) { len = userCover[_add].length; } /// @dev Gets the status of a given cover. function getCoverStatusNo(uint _cid) external view returns(uint8) { return coverStatus[_cid]; } /// @dev Gets the Cover Period (in days) of a given cover. function getCoverPeriod(uint _cid) external view returns(uint32 cp) { cp = allCovers[_cid].coverPeriod; } /// @dev Gets the Sum Assured Amount of a given cover. function getCoverSumAssured(uint _cid) external view returns(uint sa) { sa = allCovers[_cid].sumAssured; } /// @dev Gets the Currency Name in which a given cover is assured. function getCurrencyOfCover(uint _cid) external view returns(bytes4 curr) { curr = allCovers[_cid].currencyCode; } /// @dev Gets the validity date (timestamp) of a given cover. function getValidityOfCover(uint _cid) external view returns(uint date) { date = allCovers[_cid].validUntil; } /// @dev Gets Smart contract address of cover. function getscAddressOfCover(uint _cid) external view returns(uint, address) { return (_cid, allCovers[_cid].scAddress); } /// @dev Gets the owner address of a given cover. function getCoverMemberAddress(uint _cid) external view returns(address payable _add) { _add = allCovers[_cid].memberAddress; } /// @dev Gets the premium amount of a given cover in NXM. function getCoverPremiumNXM(uint _cid) external view returns(uint _premiumNXM) { _premiumNXM = allCovers[_cid].premiumNXM; } /// @dev Provides the details of a cover Id /// @param _cid cover Id /// @return memberAddress cover user address. /// @return scAddress smart contract Address /// @return currencyCode currency of cover /// @return sumAssured sum assured of cover /// @return premiumNXM premium in NXM function getCoverDetailsByCoverID1( uint _cid ) external view returns ( uint cid, address _memberAddress, address _scAddress, bytes4 _currencyCode, uint _sumAssured, uint premiumNXM ) { return ( _cid, allCovers[_cid].memberAddress, allCovers[_cid].scAddress, allCovers[_cid].currencyCode, allCovers[_cid].sumAssured, allCovers[_cid].premiumNXM ); } /// @dev Provides details of a cover Id /// @param _cid cover Id /// @return status status of cover. /// @return sumAssured Sum assurance of cover. /// @return coverPeriod Cover Period of cover (in days). /// @return validUntil is validity of cover. function getCoverDetailsByCoverID2( uint _cid ) external view returns ( uint cid, uint8 status, uint sumAssured, uint16 coverPeriod, uint validUntil ) { return ( _cid, coverStatus[_cid], allCovers[_cid].sumAssured, allCovers[_cid].coverPeriod, allCovers[_cid].validUntil ); } /// @dev Provides details of a holded cover Id /// @param _hcid holded cover Id /// @return scAddress SmartCover address of cover. /// @return coverCurr currency of cover. /// @return coverPeriod Cover Period of cover (in days). function getHoldedCoverDetailsByID1( uint _hcid ) external view returns ( uint hcid, address scAddress, bytes4 coverCurr, uint16 coverPeriod ) { return ( _hcid, allCoverHolded[_hcid].scAddress, allCoverHolded[_hcid].coverCurr, allCoverHolded[_hcid].coverPeriod ); } /// @dev Gets total number holded covers created till date. function getUserHoldedCoverLength(address _add) external view returns (uint) { return userHoldedCover[_add].length; } /// @dev Gets holded cover index by index of user holded covers. function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) { return userHoldedCover[_add][index]; } /// @dev Provides the details of a holded cover Id /// @param _hcid holded cover Id /// @return memberAddress holded cover user address. /// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute. function getHoldedCoverDetailsByID2( uint _hcid ) external view returns ( uint hcid, address payable memberAddress, uint[] memory coverDetails ) { return ( _hcid, allCoverHolded[_hcid].userAddress, allCoverHolded[_hcid].coverDetails ); } /// @dev Gets the Total Sum Assured amount of a given currency and smart contract address. function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns(uint amount) { amount = currencyCSAOfSCAdd[_add][_curr]; } //solhint-disable-next-line function changeDependentContractAddress() public {} /// @dev Changes the status of a given cover. /// @param _cid cover Id. /// @param _stat New status. function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal { coverStatus[_cid] = _stat; emit CoverStatusEvent(_cid, _stat); } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "STLP") { _changeSTLP(val); } else if (code == "STL") { _changeSTL(val); } else if (code == "PM") { _changePM(val); } else if (code == "QUOMIND") { _changeMinDays(val); } else if (code == "QUOTOK") { _setTokensRetained(val); } else { revert("Invalid param code"); } } /// @dev Changes the existing Profit Margin value function _changePM(uint _pm) internal { pm = _pm; } /// @dev Changes the existing Short Term Load Period (STLP) value. function _changeSTLP(uint _stlp) internal { stlp = _stlp; } /// @dev Changes the existing Short Term Load (STL) value. function _changeSTL(uint _stl) internal { stl = _stl; } /// @dev Changes the existing Minimum cover period (in days) function _changeMinDays(uint _days) internal { minDays = _days; } /** * @dev to set the the amount of tokens retained * @param val is the amount retained */ function _setTokensRetained(uint val) internal { tokensRetained = val; } } // File: nexusmutual-contracts/contracts/TokenData.sol /* Copyright (C) 2017 NexusMutual.io 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/ */ pragma solidity 0.5.7; contract TokenData is Iupgradable { using SafeMath for uint; address payable public walletAddress; uint public lockTokenTimeAfterCoverExp; uint public bookTime; uint public lockCADays; uint public lockMVDays; uint public scValidDays; uint public joiningFee; uint public stakerCommissionPer; uint public stakerMaxCommissionPer; uint public tokenExponent; uint public priceStep; struct StakeCommission { uint commissionEarned; uint commissionRedeemed; } struct Stake { address stakedContractAddress; uint stakedContractIndex; uint dateAdd; uint stakeAmount; uint unlockedAmount; uint burnedAmount; uint unLockableBeforeLastBurn; } struct Staker { address stakerAddress; uint stakerIndex; } struct CoverNote { uint amount; bool isDeposited; } /** * @dev mapping of uw address to array of sc address to fetch * all staked contract address of underwriter, pushing * data into this array of Stake returns stakerIndex */ mapping(address => Stake[]) public stakerStakedContracts; /** * @dev mapping of sc address to array of UW address to fetch * all underwritters of the staked smart contract * pushing data into this mapped array returns scIndex */ mapping(address => Staker[]) public stakedContractStakers; /** * @dev mapping of staked contract Address to the array of StakeCommission * here index of this array is stakedContractIndex */ mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission; mapping(address => uint) public lastCompletedStakeCommission; /** * @dev mapping of the staked contract address to the current * staker index who will receive commission. */ mapping(address => uint) public stakedContractCurrentCommissionIndex; /** * @dev mapping of the staked contract address to the * current staker index to burn token from. */ mapping(address => uint) public stakedContractCurrentBurnIndex; /** * @dev mapping to return true if Cover Note deposited against coverId */ mapping(uint => CoverNote) public depositedCN; mapping(address => uint) internal isBookedTokens; event Commission( address indexed stakedContractAddress, address indexed stakerAddress, uint indexed scIndex, uint commissionAmount ); constructor(address payable _walletAdd) public { walletAddress = _walletAdd; bookTime = 12 hours; joiningFee = 2000000000000000; // 0.002 Ether lockTokenTimeAfterCoverExp = 35 days; scValidDays = 250; lockCADays = 7 days; lockMVDays = 2 days; stakerCommissionPer = 20; stakerMaxCommissionPer = 50; tokenExponent = 4; priceStep = 1000; } /** * @dev Change the wallet address which receive Joining Fee */ function changeWalletAddress(address payable _address) external onlyInternal { walletAddress = _address; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "TOKEXP") { val = tokenExponent; } else if (code == "TOKSTEP") { val = priceStep; } else if (code == "RALOCKT") { val = scValidDays; } else if (code == "RACOMM") { val = stakerCommissionPer; } else if (code == "RAMAXC") { val = stakerMaxCommissionPer; } else if (code == "CABOOKT") { val = bookTime / (1 hours); } else if (code == "CALOCKT") { val = lockCADays / (1 days); } else if (code == "MVLOCKT") { val = lockMVDays / (1 days); } else if (code == "QUOLOCKT") { val = lockTokenTimeAfterCoverExp / (1 days); } else if (code == "JOINFEE") { val = joiningFee; } } /** * @dev Just for interface */ function changeDependentContractAddress() public { //solhint-disable-line } /** * @dev to get the contract staked by a staker * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return the address of staked contract */ function getStakerStakedContractByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (address stakedContractAddress) { stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; } /** * @dev to get the staker's staked burned * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount burned */ function getStakerStakedBurnedByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint burnedAmount) { burnedAmount = stakerStakedContracts[ _stakerAddress][_stakerIndex].burnedAmount; } /** * @dev to get the staker's staked unlockable before the last burn * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return unlockable staked tokens */ function getStakerStakedUnlockableBeforeLastBurnByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint unlockable) { unlockable = stakerStakedContracts[ _stakerAddress][_stakerIndex].unLockableBeforeLastBurn; } /** * @dev to get the staker's staked contract index * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return is the index of the smart contract address */ function getStakerStakedContractIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint scIndex) { scIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; } /** * @dev to get the staker index of the staked contract * @param _stakedContractAddress is the address of the staked contract * @param _stakedContractIndex is the index of staked contract * @return is the index of the staker */ function getStakedContractStakerIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint sIndex) { sIndex = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerIndex; } /** * @dev to get the staker's initial staked amount on the contract * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return staked amount */ function getStakerInitialStakedAmountOnContract( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakeAmount; } /** * @dev to get the staker's staked contract length * @param _stakerAddress is the address of the staker * @return length of staked contract */ function getStakerStakedContractLength( address _stakerAddress ) public view returns (uint length) { length = stakerStakedContracts[_stakerAddress].length; } /** * @dev to get the staker's unlocked tokens which were staked * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount */ function getStakerUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].unlockedAmount; } /** * @dev pushes the unlocked staked tokens by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev pushes the Burned tokens for a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be burned. */ function pushBurnedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev pushes the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function pushUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev sets the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function setUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = _amount; } /** * @dev pushes the earned commission earned by a staker. * @param _stakerAddress address of staker. * @param _stakedContractAddress address of smart contract. * @param _stakedContractIndex index of the staker to distribute commission. * @param _commissionAmount amount to be given as commission. */ function pushEarnedStakeCommissions( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _commissionAmount ) public onlyInternal { stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex]. commissionEarned = stakedContractStakeCommission[_stakedContractAddress][ _stakedContractIndex].commissionEarned.add(_commissionAmount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Commission( _stakerAddress, _stakedContractAddress, _stakedContractIndex, _commissionAmount ); } /** * @dev pushes the redeemed commission redeemed by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushRedeemedStakeCommissions( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { uint stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; address stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; stakedContractStakeCommission[stakedContractAddress][stakedContractIndex]. commissionRedeemed = stakedContractStakeCommission[ stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Gets stake commission given to an underwriter * for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets stake commission redeemed by an underwriter * for particular staked contract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. * @return commissionEarned total amount given to staker. */ function getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalEarnedStakeCommission( address _stakerAddress ) public view returns (uint totalCommissionEarned) { totalCommissionEarned = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionEarned = totalCommissionEarned. add(_getStakerEarnedStakeCommission(_stakerAddress, i)); } } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalReedmedStakeCommission( address _stakerAddress ) public view returns(uint totalCommissionRedeemed) { totalCommissionRedeemed = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionRedeemed = totalCommissionRedeemed.add( _getStakerRedeemedStakeCommission(_stakerAddress, i)); } } /** * @dev set flag to deposit/ undeposit cover note * against a cover Id * @param coverId coverId of Cover * @param flag true/false for deposit/undeposit */ function setDepositCN(uint coverId, bool flag) public onlyInternal { if (flag == true) { require(!depositedCN[coverId].isDeposited, "Cover note already deposited"); } depositedCN[coverId].isDeposited = flag; } /** * @dev set locked cover note amount * against a cover Id * @param coverId coverId of Cover * @param amount amount of nxm to be locked */ function setDepositCNAmount(uint coverId, uint amount) public onlyInternal { depositedCN[coverId].amount = amount; } /** * @dev to get the staker address on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @param _stakedContractIndex is the index of staked contract's index * @return address of staker */ function getStakedContractStakerByIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (address stakerAddress) { stakerAddress = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerAddress; } /** * @dev to get the length of stakers on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @return length in concern */ function getStakedContractStakersLength( address _stakedContractAddress ) public view returns (uint length) { length = stakedContractStakers[_stakedContractAddress].length; } /** * @dev Adds a new stake record. * @param _stakerAddress staker address. * @param _stakedContractAddress smart contract address. * @param _amount amountof NXM to be staked. */ function addStake( address _stakerAddress, address _stakedContractAddress, uint _amount ) public onlyInternal returns(uint scIndex) { scIndex = (stakedContractStakers[_stakedContractAddress].push( Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1); stakerStakedContracts[_stakerAddress].push( Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0)); } /** * @dev books the user's tokens for maintaining Assessor Velocity, * i.e. once a token is used to cast a vote as a Claims assessor, * @param _of user's address. */ function bookCATokens(address _of) public onlyInternal { require(!isCATokensBooked(_of), "Tokens already booked"); isBookedTokens[_of] = now.add(bookTime); } /** * @dev to know if claim assessor's tokens are booked or not * @param _of is the claim assessor's address in concern * @return boolean representing the status of tokens booked */ function isCATokensBooked(address _of) public view returns(bool res) { if (now < isBookedTokens[_of]) res = true; } /** * @dev Sets the index which will receive commission. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentCommissionIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index; } /** * @dev Sets the last complete commission index * @param _stakerAddress smart contract address. * @param _index current index. */ function setLastCompletedStakeCommissionIndex( address _stakerAddress, uint _index ) public onlyInternal { lastCompletedStakeCommission[_stakerAddress] = _index; } /** * @dev Sets the index till which commission is distrubuted. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentBurnIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentBurnIndex[_stakedContractAddress] = _index; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "TOKEXP") { _setTokenExponent(val); } else if (code == "TOKSTEP") { _setPriceStep(val); } else if (code == "RALOCKT") { _changeSCValidDays(val); } else if (code == "RACOMM") { _setStakerCommissionPer(val); } else if (code == "RAMAXC") { _setStakerMaxCommissionPer(val); } else if (code == "CABOOKT") { _changeBookTime(val * 1 hours); } else if (code == "CALOCKT") { _changelockCADays(val * 1 days); } else if (code == "MVLOCKT") { _changelockMVDays(val * 1 days); } else if (code == "QUOLOCKT") { _setLockTokenTimeAfterCoverExp(val * 1 days); } else if (code == "JOINFEE") { _setJoiningFee(val); } else { revert("Invalid param code"); } } /** * @dev Internal function to get stake commission given to an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionEarned; } /** * @dev Internal function to get stake commission redeemed by an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionRedeemed; } /** * @dev to set the percentage of staker commission * @param _val is new percentage value */ function _setStakerCommissionPer(uint _val) internal { stakerCommissionPer = _val; } /** * @dev to set the max percentage of staker commission * @param _val is new percentage value */ function _setStakerMaxCommissionPer(uint _val) internal { stakerMaxCommissionPer = _val; } /** * @dev to set the token exponent value * @param _val is new value */ function _setTokenExponent(uint _val) internal { tokenExponent = _val; } /** * @dev to set the price step * @param _val is new value */ function _setPriceStep(uint _val) internal { priceStep = _val; } /** * @dev Changes number of days for which NXM needs to staked in case of underwriting */ function _changeSCValidDays(uint _days) internal { scValidDays = _days; } /** * @dev Changes the time period up to which tokens will be locked. * Used to generate the validity period of tokens booked by * a user for participating in claim's assessment/claim's voting. */ function _changeBookTime(uint _time) internal { bookTime = _time; } /** * @dev Changes lock CA days - number of days for which tokens * are locked while submitting a vote. */ function _changelockCADays(uint _val) internal { lockCADays = _val; } /** * @dev Changes lock MV days - number of days for which tokens are locked * while submitting a vote. */ function _changelockMVDays(uint _val) internal { lockMVDays = _val; } /** * @dev Changes extra lock period for a cover, post its expiry. */ function _setLockTokenTimeAfterCoverExp(uint time) internal { lockTokenTimeAfterCoverExp = time; } /** * @dev Set the joining fee for membership */ function _setJoiningFee(uint _amount) internal { joiningFee = _amount; } } // File: nexusmutual-contracts/contracts/external/oraclize/ethereum-api/usingOraclize.sol /* ORACLIZE_API Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity >= 0.5.0 < 0.6.0; // Incompatible compiler version - please select a compiler within the stated pragma range, or use a different version of the oraclizeAPI! // Dummy contract only used to emit to end-user they are using wrong solc contract solcChecker { /* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) external; } contract OraclizeI { address public cbAddress; function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function getPrice(string memory _datasource) public returns (uint _dsprice); function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash); function getPrice(string memory _datasource, uint _gasLimit) public returns (uint _dsprice); function queryN(uint _timestamp, string memory _datasource, bytes memory _argN) public payable returns (bytes32 _id); function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id); function query2(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) public payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id); } contract OraclizeAddrResolverI { function getAddress() public returns (address _address); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. 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. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory _buf, uint _capacity) internal pure { uint capacity = _capacity; if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } _buf.capacity = capacity; // Allocate space for the buffer data assembly { let ptr := mload(0x40) mstore(_buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory _buf, uint _capacity) private pure { bytes memory oldbuf = _buf.buf; init(_buf, _capacity); append(_buf, oldbuf); } function max(uint _a, uint _b) private pure returns (uint _max) { if (_a > _b) { return _a; } return _b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) { if (_data.length + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _data.length) * 2); } uint dest; uint src; uint len = _data.length; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length) mstore(bufptr, add(buflen, mload(_data))) // Update buffer length src := add(_data, 32) } for(; len >= 32; len -= 32) { // Copy word-length chunks while possible assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return _buf; } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, uint8 _data) internal pure { if (_buf.buf.length + 1 > _buf.capacity) { resize(_buf, _buf.capacity * 2); } assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length) mstore8(dest, _data) mstore(bufptr, add(buflen, 1)) // Update buffer length } } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) { if (_len + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _len) * 2); } uint mask = 256 ** _len - 1; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len mstore(dest, or(and(mload(dest), not(mask)), _data)) mstore(bufptr, add(buflen, _len)) // Update buffer length } return _buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure { if (_value <= 23) { _buf.append(uint8((_major << 5) | _value)); } else if (_value <= 0xFF) { _buf.append(uint8((_major << 5) | 24)); _buf.appendInt(_value, 1); } else if (_value <= 0xFFFF) { _buf.append(uint8((_major << 5) | 25)); _buf.appendInt(_value, 2); } else if (_value <= 0xFFFFFFFF) { _buf.append(uint8((_major << 5) | 26)); _buf.appendInt(_value, 4); } else if (_value <= 0xFFFFFFFFFFFFFFFF) { _buf.append(uint8((_major << 5) | 27)); _buf.appendInt(_value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure { _buf.append(uint8((_major << 5) | 31)); } function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure { encodeType(_buf, MAJOR_TYPE_INT, _value); } function encodeInt(Buffer.buffer memory _buf, int _value) internal pure { if (_value >= 0) { encodeType(_buf, MAJOR_TYPE_INT, uint(_value)); } else { encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value)); } } function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_BYTES, _value.length); _buf.append(_value); } function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length); _buf.append(bytes(_value)); } function startArray(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { using CBOR for Buffer.buffer; OraclizeI oraclize; OraclizeAddrResolverI OAR; uint constant day = 60 * 60 * 24; uint constant week = 60 * 60 * 24 * 7; uint constant month = 60 * 60 * 24 * 30; byte constant proofType_NONE = 0x00; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; byte constant proofType_Android = 0x40; byte constant proofType_TLSNotary = 0x10; string oraclize_network_name; uint8 constant networkID_auto = 0; uint8 constant networkID_morden = 2; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_consensys = 161; mapping(bytes32 => bytes32) oraclize_randomDS_args; mapping(bytes32 => bool) oraclize_randomDS_sessionKeysHashVerified; modifier oraclizeAPI { if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) { oraclize_setNetwork(networkID_auto); } if (address(oraclize) != OAR.getAddress()) { oraclize = OraclizeI(OAR.getAddress()); } _; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) { // RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1))); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_setNetwork(uint8 _networkID) internal returns (bool _networkSet) { return oraclize_setNetwork(); _networkID; // silence the warning and remain backwards compatible } function oraclize_setNetworkName(string memory _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string memory _networkName) { return oraclize_network_name; } function oraclize_setNetwork() internal returns (bool _networkSet) { if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) { //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) { //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) { //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) { //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { //goerli testnet OAR = OraclizeAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41); oraclize_setNetworkName("eth_goerli"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) { //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) { //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) { //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 _myid, string memory _result) public { __callback(_myid, _result, new bytes(0)); } function __callback(bytes32 _myid, string memory _result, bytes memory _proof) public { return; _myid; _result; _proof; // Silence compiler warnings } function oraclize_getPrice(string memory _datasource) oraclizeAPI internal returns (uint _queryPrice) { return oraclize.getPrice(_datasource); } function oraclize_getPrice(string memory _datasource, uint _gasLimit) oraclizeAPI internal returns (uint _queryPrice) { return oraclize.getPrice(_datasource, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query.value(price)(0, _datasource, _arg); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query.value(price)(_timestamp, _datasource, _arg); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource,_gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query_withGasLimit.value(price)(_timestamp, _datasource, _arg, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query_withGasLimit.value(price)(0, _datasource, _arg, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query2.value(price)(0, _datasource, _arg1, _arg2); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query2.value(price)(_timestamp, _datasource, _arg1, _arg2); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query2_withGasLimit.value(price)(_timestamp, _datasource, _arg1, _arg2, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query2_withGasLimit.value(price)(0, _datasource, _arg1, _arg2, _gasLimit); } function oraclize_query(string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN.value(price)(0, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN.value(price)(_timestamp, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN.value(price)(0, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN.value(price)(_timestamp, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_setProof(byte _proofP) oraclizeAPI internal { return oraclize.setProofType(_proofP); } function oraclize_cbAddress() oraclizeAPI internal returns (address _callbackAddress) { return oraclize.cbAddress(); } function getCodeSize(address _addr) view internal returns (uint _size) { assembly { _size := extcodesize(_addr) } } function oraclize_setCustomGasPrice(uint _gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(_gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32 _sessionKeyHash) { return oraclize.randomDS_getSessionPubKeyHash(); } function parseAddr(string memory _a) internal pure returns (address _parsedAddress) { bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i = 2; i < 2 + 2 * 20; i += 2) { iaddr *= 256; b1 = uint160(uint8(tmp[i])); b2 = uint160(uint8(tmp[i + 1])); if ((b1 >= 97) && (b1 <= 102)) { b1 -= 87; } else if ((b1 >= 65) && (b1 <= 70)) { b1 -= 55; } else if ((b1 >= 48) && (b1 <= 57)) { b1 -= 48; } if ((b2 >= 97) && (b2 <= 102)) { b2 -= 87; } else if ((b2 >= 65) && (b2 <= 70)) { b2 -= 55; } else if ((b2 >= 48) && (b2 <= 57)) { b2 -= 48; } iaddr += (b1 * 16 + b2); } return address(iaddr); } function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) { minLength = b.length; } for (uint i = 0; i < minLength; i ++) { if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } } if (a.length < b.length) { return -1; } else if (a.length > b.length) { return 1; } else { return 0; } } function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if (h.length < 1 || n.length < 1 || (n.length > h.length)) { return -1; } else if (h.length > (2 ** 128 - 1)) { return -1; } else { uint subindex = 0; for (uint i = 0; i < h.length; i++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if (subindex == n.length) { return int(i); } } } return -1; } } function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, "", "", ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { babcde[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { babcde[k++] = _bb[i]; } for (i = 0; i < _bc.length; i++) { babcde[k++] = _bc[i]; } for (i = 0; i < _bd.length; i++) { babcde[k++] = _bd[i]; } for (i = 0; i < _be.length; i++) { babcde[k++] = _be[i]; } return string(babcde); } function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) { return safeParseInt(_a, 0); } function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) break; else _b--; } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { require(!decimals, 'More than one decimal encountered in string!'); decimals = true; } else { revert("Non-numeral character encountered in string!"); } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function parseInt(string memory _a) internal pure returns (uint _parsedInt) { return parseInt(_a, 0); } function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { decimals = true; } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeString(_arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeBytes(_arr[i]); } buf.endSequence(); return buf.buf; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) { require((_nbytes > 0) && (_nbytes <= 32)); _delay *= 10; // Convert from seconds to ledger timer ticks bytes memory nbytes = new bytes(1); nbytes[0] = byte(uint8(_nbytes)); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) /* The following variables can be relaxed. Check the relaxed random contract at https://github.com/oraclize/ethereum-examples for an idea on how to override and replace commit hash variables. */ mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2]))); return queryId; } function oraclize_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal { oraclize_randomDS_args[_queryId] = _commitment; } function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) { bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20); sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(_dersig, offset + (uint(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs); if (address(uint160(uint256(keccak256(_pubkey)))) == signer) { return true; } else { (sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs); return (address(uint160(uint256(keccak256(_pubkey)))) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) { bool sigok; // Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(uint8(_proof[_sig2offset + 1])) + 2); copyBytes(_proof, _sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1 + 65 + 32); tosign2[0] = byte(uint8(1)); //role copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (!sigok) { return false; } // Random DS Proof Step 7: Verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1 + 65); tosign3[0] = 0xFE; copyBytes(_proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(uint8(_proof[3 + 65 + 1])) + 2); copyBytes(_proof, 3 + 65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) { // Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) { return 1; } bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (!proofVerified) { return 2; } return 0; } function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) { bool match_ = true; require(_prefix.length == _nRandomBytes); for (uint256 i = 0; i< _nRandomBytes; i++) { if (_content[i] != _prefix[i]) { match_ = false; } } return match_; } function oraclize_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) { // Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId) uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32; bytes memory keyhash = new bytes(32); copyBytes(_proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) { return false; } bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2); copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0); // Random DS Proof Step 3: We assume sig1 is valid (it will be verified during step 5) and we verify if '_result' is the _prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), _result, uint(uint8(_proof[ledgerProofLength + 32 + 8])))) { return false; } // Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8 + 1 + 32); copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65; copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[_queryId]; } else return false; // Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32 + 8 + 1 + 32); copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) { return false; } // Verify if sessionPubkeyHash was verified already, if not.. let's do it! if (!oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) { oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function copyBytes(bytes memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) { uint minLength = _length + _toOffset; require(_to.length >= minLength); // Buffer too small. Should be a better way? uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint j = 32 + _toOffset; while (i < (32 + _fromOffset + _length)) { assembly { let tmp := mload(add(_from, i)) mstore(add(_to, j), tmp) } i += 32; j += 32; } return _to; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license Duplicate Solidity's ecrecover, but catching the CALL return value */ function safer_ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal returns (bool _success, address _recoveredAddress) { /* We do our own memory management here. Solidity uses memory offset 0x40 to store the current end of memory. We write past it (as writes are memory extensions), but don't update the offset so Solidity will reuse it. The memory used here is only needed for this context. FIXME: inline assembly can't access return values */ bool ret; address addr; assembly { let size := mload(0x40) mstore(size, _hash) mstore(add(size, 32), _v) mstore(add(size, 64), _r) mstore(add(size, 96), _s) ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code. addr := mload(size) } return (ret, addr); } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function ecrecovery(bytes32 _hash, bytes memory _sig) internal returns (bool _success, address _recoveredAddress) { bytes32 r; bytes32 s; uint8 v; if (_sig.length != 65) { return (false, address(0)); } /* The signature format is a compact form of: {bytes32 r}{bytes32 s}{uint8 v} Compact means, uint8 is not padded to 32 bytes. */ assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) /* Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread. There is no 'mload8' to do this, but that would be nicer. */ v := byte(0, mload(add(_sig, 96))) /* Alternative solution: 'byte' is not working due to the Solidity parser, so lets use the second best option, 'and' v := and(mload(add(_sig, 65)), 255) */ } /* albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28] geth uses [0, 1] and some clients have followed. This might change, see: https://github.com/ethereum/go-ethereum/issues/2053 */ if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (false, address(0)); } return safer_ecrecover(_hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } /* END ORACLIZE_API */ // File: nexusmutual-contracts/contracts/Quotation.sol /* Copyright (C) 2017 NexusMutual.io 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/ */ pragma solidity 0.5.7; contract Quotation is Iupgradable { using SafeMath for uint; TokenFunctions internal tf; TokenController internal tc; TokenData internal td; Pool1 internal p1; PoolData internal pd; QuotationData internal qd; MCR internal m1; MemberRoles internal mr; bool internal locked; event RefundEvent(address indexed user, bool indexed status, uint holdedCoverID, bytes32 reason); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { m1 = MCR(ms.getLatestAddress("MC")); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); td = TokenData(ms.getLatestAddress("TD")); qd = QuotationData(ms.getLatestAddress("QD")); p1 = Pool1(ms.getLatestAddress("P1")); pd = PoolData(ms.getLatestAddress("PD")); mr = MemberRoles(ms.getLatestAddress("MR")); } function sendEther() public payable { } /** * @dev Expires a cover after a set period of time. * Changes the status of the Cover and reduces the current * sum assured of all areas in which the quotation lies * Unlocks the CN tokens of the cover. Updates the Total Sum Assured value. * @param _cid Cover Id. */ function expireCover(uint _cid) public { require(checkCoverExpired(_cid) && qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.CoverExpired)); tf.unlockCN(_cid); bytes4 curr; address scAddress; uint sumAssured; (, , scAddress, curr, sumAssured, ) = qd.getCoverDetailsByCoverID1(_cid); if (qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.ClaimAccepted)) _removeSAFromCSA(_cid, sumAssured); qd.changeCoverStatusNo(_cid, uint8(QuotationData.CoverStatus.CoverExpired)); } /** * @dev Checks if a cover should get expired/closed or not. * @param _cid Cover Index. * @return expire true if the Cover's time has expired, false otherwise. */ function checkCoverExpired(uint _cid) public view returns(bool expire) { expire = qd.getValidityOfCover(_cid) < uint64(now); } /** * @dev Updates the Sum Assured Amount of all the quotation. * @param _cid Cover id * @param _amount that will get subtracted Current Sum Assured * amount that comes under a quotation. */ function removeSAFromCSA(uint _cid, uint _amount) public onlyInternal { _removeSAFromCSA(_cid, _amount); } /** * @dev Makes Cover funded via NXM tokens. * @param smartCAdd Smart Contract Address */ function makeCoverUsingNXMTokens( uint[] memory coverDetails, uint16 coverPeriod, bytes4 coverCurr, address smartCAdd, uint8 _v, bytes32 _r, bytes32 _s ) public isMemberAndcheckPause { tc.burnFrom(msg.sender, coverDetails[2]); //need burn allowance _verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Verifies cover details signed off chain. * @param from address of funder. * @param scAddress Smart Contract Address */ function verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public onlyInternal { _verifyCoverDetails( from, scAddress, coverCurr, coverDetails, coverPeriod, _v, _r, _s ); } /** * @dev Verifies signature. * @param coverDetails details related to cover. * @param coverPeriod validity of cover. * @param smaratCA smarat contract address. * @param _v argument from vrs hash. * @param _r argument from vrs hash. * @param _s argument from vrs hash. */ function verifySign( uint[] memory coverDetails, uint16 coverPeriod, bytes4 curr, address smaratCA, uint8 _v, bytes32 _r, bytes32 _s ) public view returns(bool) { require(smaratCA != address(0)); require(pd.capReached() == 1, "Can not buy cover until cap reached for 1st time"); bytes32 hash = getOrderHash(coverDetails, coverPeriod, curr, smaratCA); return isValidSignature(hash, _v, _r, _s); } /** * @dev Gets order hash for given cover details. * @param coverDetails details realted to cover. * @param coverPeriod validity of cover. * @param smaratCA smarat contract address. */ function getOrderHash( uint[] memory coverDetails, uint16 coverPeriod, bytes4 curr, address smaratCA ) public view returns(bytes32) { return keccak256( abi.encodePacked( coverDetails[0], curr, coverPeriod, smaratCA, coverDetails[1], coverDetails[2], coverDetails[3], coverDetails[4], address(this) ) ); } /** * @dev Verifies signature. * @param hash order hash * @param v argument from vrs hash. * @param r argument from vrs hash. * @param s argument from vrs hash. */ function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns(bool) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); address a = ecrecover(prefixedHash, v, r, s); return (a == qd.getAuthQuoteEngine()); } /** * @dev to get the status of recently holded coverID * @param userAdd is the user address in concern * @return the status of the concerned coverId */ function getRecentHoldedCoverIdStatus(address userAdd) public view returns(int) { uint holdedCoverLen = qd.getUserHoldedCoverLength(userAdd); if (holdedCoverLen == 0) { return -1; } else { uint holdedCoverID = qd.getUserHoldedCoverByIndex(userAdd, holdedCoverLen.sub(1)); return int(qd.holdedCoverIDStatus(holdedCoverID)); } } /** * @dev to initiate the membership and the cover * @param smartCAdd is the smart contract address to make cover on * @param coverCurr is the currency used to make cover * @param coverDetails list of details related to cover like cover amount, expire time, coverCurrPrice and priceNXM * @param coverPeriod is cover period for which cover is being bought * @param _v argument from vrs hash * @param _r argument from vrs hash * @param _s argument from vrs hash */ function initiateMembershipAndCover( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public payable checkPause { require(coverDetails[3] > now); require(!qd.timestampRepeated(coverDetails[4])); qd.setTimestampRepeated(coverDetails[4]); require(!ms.isMember(msg.sender)); require(qd.refundEligible(msg.sender) == false); uint joinFee = td.joiningFee(); uint totalFee = joinFee; if (coverCurr == "ETH") { totalFee = joinFee.add(coverDetails[1]); } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); require(erc20.transferFrom(msg.sender, address(this), coverDetails[1])); } require(msg.value == totalFee); require(verifySign(coverDetails, coverPeriod, coverCurr, smartCAdd, _v, _r, _s)); qd.addHoldCover(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod); qd.setRefundEligible(msg.sender, true); } /** * @dev to get the verdict of kyc process * @param status is the kyc status * @param _add is the address of member */ function kycVerdict(address _add, bool status) public checkPause noReentrancy { require(msg.sender == qd.kycAuthAddress()); _kycTrigger(status, _add); } /** * @dev transfering Ethers to newly created quotation contract. */ function transferAssetsToNewContract(address newAdd) public onlyInternal noReentrancy { uint amount = address(this).balance; IERC20 erc20; if (amount > 0) { // newAdd.transfer(amount); Quotation newQT = Quotation(newAdd); newQT.sendEther.value(amount)(); } uint currAssetLen = pd.getAllCurrenciesLen(); for (uint64 i = 1; i < currAssetLen; i++) { bytes4 currName = pd.getCurrenciesByIndex(i); address currAddr = pd.getCurrencyAssetAddress(currName); erc20 = IERC20(currAddr); //solhint-disable-line if (erc20.balanceOf(address(this)) > 0) { require(erc20.transfer(newAdd, erc20.balanceOf(address(this)))); } } } /** * @dev Creates cover of the quotation, changes the status of the quotation , * updates the total sum assured and locks the tokens of the cover against a quote. * @param from Quote member Ethereum address. */ function _makeCover ( //solhint-disable-line address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod ) internal { uint cid = qd.getCoverLength(); qd.addCover(coverPeriod, coverDetails[0], from, coverCurr, scAddress, coverDetails[1], coverDetails[2]); // if cover period of quote is less than 60 days. if (coverPeriod <= 60) { p1.closeCoverOraclise(cid, uint64(uint(coverPeriod).mul(1 days))); } uint coverNoteAmount = (coverDetails[2].mul(qd.tokensRetained())).div(100); tc.mint(from, coverNoteAmount); tf.lockCN(coverNoteAmount, coverPeriod, cid, from); qd.addInTotalSumAssured(coverCurr, coverDetails[0]); qd.addInTotalSumAssuredSC(scAddress, coverCurr, coverDetails[0]); tf.pushStakerRewards(scAddress, coverDetails[2]); } /** * @dev Makes a vover. * @param from address of funder. * @param scAddress Smart Contract Address */ function _verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) internal { require(coverDetails[3] > now); require(!qd.timestampRepeated(coverDetails[4])); qd.setTimestampRepeated(coverDetails[4]); require(verifySign(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s)); _makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod); } /** * @dev Updates the Sum Assured Amount of all the quotation. * @param _cid Cover id * @param _amount that will get subtracted Current Sum Assured * amount that comes under a quotation. */ function _removeSAFromCSA(uint _cid, uint _amount) internal checkPause { address _add; bytes4 coverCurr; (, , _add, coverCurr, , ) = qd.getCoverDetailsByCoverID1(_cid); qd.subFromTotalSumAssured(coverCurr, _amount); qd.subFromTotalSumAssuredSC(_add, coverCurr, _amount); } /** * @dev to trigger the kyc process * @param status is the kyc status * @param _add is the address of member */ function _kycTrigger(bool status, address _add) internal { uint holdedCoverLen = qd.getUserHoldedCoverLength(_add).sub(1); uint holdedCoverID = qd.getUserHoldedCoverByIndex(_add, holdedCoverLen); address payable userAdd; address scAddress; bytes4 coverCurr; uint16 coverPeriod; uint[] memory coverDetails = new uint[](4); IERC20 erc20; (, userAdd, coverDetails) = qd.getHoldedCoverDetailsByID2(holdedCoverID); (, scAddress, coverCurr, coverPeriod) = qd.getHoldedCoverDetailsByID1(holdedCoverID); require(qd.refundEligible(userAdd)); qd.setRefundEligible(userAdd, false); require(qd.holdedCoverIDStatus(holdedCoverID) == uint(QuotationData.HCIDStatus.kycPending)); uint joinFee = td.joiningFee(); if (status) { mr.payJoiningFee.value(joinFee)(userAdd); if (coverDetails[3] > now) { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPass)); address poolAdd = ms.getLatestAddress("P1"); if (coverCurr == "ETH") { p1.sendEther.value(coverDetails[1])(); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(poolAdd, coverDetails[1])); } emit RefundEvent(userAdd, status, holdedCoverID, "KYC Passed"); _makeCover(userAdd, scAddress, coverCurr, coverDetails, coverPeriod); } else { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPassNoCover)); if (coverCurr == "ETH") { userAdd.transfer(coverDetails[1]); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(userAdd, coverDetails[1])); } emit RefundEvent(userAdd, status, holdedCoverID, "Cover Failed"); } } else { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycFailedOrRefunded)); uint totalRefund = joinFee; if (coverCurr == "ETH") { totalRefund = coverDetails[1].add(joinFee); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(userAdd, coverDetails[1])); } userAdd.transfer(totalRefund); emit RefundEvent(userAdd, status, holdedCoverID, "KYC Failed"); } } } // File: nexusmutual-contracts/contracts/external/uniswap/solidity-interface.sol pragma solidity 0.5.7; contract Factory { function getExchange(address token) public view returns (address); function getToken(address exchange) public view returns (address); } contract Exchange { function getEthToTokenInputPrice(uint256 ethSold) public view returns(uint256); function getTokenToEthInputPrice(uint256 tokensSold) public view returns(uint256); function ethToTokenSwapInput(uint256 minTokens, uint256 deadline) public payable returns (uint256); function ethToTokenTransferInput(uint256 minTokens, uint256 deadline, address recipient) public payable returns (uint256); function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline) public payable returns (uint256); function tokenToEthTransferInput(uint256 tokensSold, uint256 minEth, uint256 deadline, address recipient) public payable returns (uint256); function tokenToTokenSwapInput( uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address tokenAddress ) public returns (uint256); function tokenToTokenTransferInput( uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address recipient, address tokenAddress ) public returns (uint256); } // File: nexusmutual-contracts/contracts/Pool2.sol /* Copyright (C) 2017 NexusMutual.io 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/ */ pragma solidity 0.5.7; contract Pool2 is Iupgradable { using SafeMath for uint; MCR internal m1; Pool1 internal p1; PoolData internal pd; Factory internal factory; address public uniswapFactoryAddress; uint internal constant DECIMAL1E18 = uint(10) ** 18; bool internal locked; constructor(address _uniswapFactoryAdd) public { uniswapFactoryAddress = _uniswapFactoryAdd; factory = Factory(_uniswapFactoryAdd); } function() external payable {} event Liquidity(bytes16 typeOf, bytes16 functionName); event Rebalancing(bytes4 iaCurr, uint tokenAmount); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } /** * @dev to change the uniswap factory address * @param newFactoryAddress is the new factory address in concern * @return the status of the concerned coverId */ function changeUniswapFactoryAddress(address newFactoryAddress) external onlyInternal { // require(ms.isOwner(msg.sender) || ms.checkIsAuthToGoverned(msg.sender)); uniswapFactoryAddress = newFactoryAddress; factory = Factory(uniswapFactoryAddress); } /** * @dev On upgrade transfer all investment assets and ether to new Investment Pool * @param newPoolAddress New Investment Assest Pool address */ function upgradeInvestmentPool(address payable newPoolAddress) external onlyInternal noReentrancy { uint len = pd.getInvestmentCurrencyLen(); for (uint64 i = 1; i < len; i++) { bytes4 iaName = pd.getInvestmentCurrencyByIndex(i); _upgradeInvestmentPool(iaName, newPoolAddress); } if (address(this).balance > 0) { Pool2 newP2 = Pool2(newPoolAddress); newP2.sendEther.value(address(this).balance)(); } } /** * @dev Internal Swap of assets between Capital * and Investment Sub pool for excess or insufficient * liquidity conditions of a given currency. */ function internalLiquiditySwap(bytes4 curr) external onlyInternal noReentrancy { uint caBalance; uint baseMin; uint varMin; (, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr); caBalance = _getCurrencyAssetsBalance(curr); if (caBalance > uint(baseMin).add(varMin).mul(2)) { _internalExcessLiquiditySwap(curr, baseMin, varMin, caBalance); } else if (caBalance < uint(baseMin).add(varMin)) { _internalInsufficientLiquiditySwap(curr, baseMin, varMin, caBalance); } } /** * @dev Saves a given investment asset details. To be called daily. * @param curr array of Investment asset name. * @param rate array of investment asset exchange rate. * @param date current date in yyyymmdd. */ function saveIADetails(bytes4[] calldata curr, uint64[] calldata rate, uint64 date, bool bit) external checkPause noReentrancy { bytes4 maxCurr; bytes4 minCurr; uint64 maxRate; uint64 minRate; //ONLY NOTARZIE ADDRESS CAN POST require(pd.isnotarise(msg.sender)); (maxCurr, maxRate, minCurr, minRate) = _calculateIARank(curr, rate); pd.saveIARankDetails(maxCurr, maxRate, minCurr, minRate, date); pd.updatelastDate(date); uint len = curr.length; for (uint i = 0; i < len; i++) { pd.updateIAAvgRate(curr[i], rate[i]); } if (bit) //for testing purpose _rebalancingLiquidityTrading(maxCurr, maxRate); p1.saveIADetailsOracalise(pd.iaRatesTime()); } /** * @dev External Trade for excess or insufficient * liquidity conditions of a given currency. */ function externalLiquidityTrade() external onlyInternal { bool triggerTrade; bytes4 curr; bytes4 minIACurr; bytes4 maxIACurr; uint amount; uint minIARate; uint maxIARate; uint baseMin; uint varMin; uint caBalance; (maxIACurr, maxIARate, minIACurr, minIARate) = pd.getIARankDetailsByDate(pd.getLastDate()); uint len = pd.getAllCurrenciesLen(); for (uint64 i = 0; i < len; i++) { curr = pd.getCurrenciesByIndex(i); (, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr); caBalance = _getCurrencyAssetsBalance(curr); if (caBalance > uint(baseMin).add(varMin).mul(2)) { //excess amount = caBalance.sub(((uint(baseMin).add(varMin)).mul(3)).div(2)); //*10**18; triggerTrade = _externalExcessLiquiditySwap(curr, minIACurr, amount); } else if (caBalance < uint(baseMin).add(varMin)) { // insufficient amount = (((uint(baseMin).add(varMin)).mul(3)).div(2)).sub(caBalance); triggerTrade = _externalInsufficientLiquiditySwap(curr, maxIACurr, amount); } if (triggerTrade) { p1.triggerExternalLiquidityTrade(); } } } /** * Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { m1 = MCR(ms.getLatestAddress("MC")); pd = PoolData(ms.getLatestAddress("PD")); p1 = Pool1(ms.getLatestAddress("P1")); } function sendEther() public payable { } /** * @dev Gets currency asset balance for a given currency name. */ function _getCurrencyAssetsBalance(bytes4 _curr) public view returns(uint caBalance) { if (_curr == "ETH") { caBalance = address(p1).balance; } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); caBalance = erc20.balanceOf(address(p1)); } } /** * @dev Transfers ERC20 investment asset from this Pool to another Pool. */ function _transferInvestmentAsset( bytes4 _curr, address _transferTo, uint _amount ) internal { if (_curr == "ETH") { if (_amount > address(this).balance) _amount = address(this).balance; p1.sendEther.value(_amount)(); } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); if (_amount > erc20.balanceOf(address(this))) _amount = erc20.balanceOf(address(this)); require(erc20.transfer(_transferTo, _amount)); } } /** * @dev to perform rebalancing * @param iaCurr is the investment asset currency * @param iaRate is the investment asset rate */ function _rebalancingLiquidityTrading( bytes4 iaCurr, uint64 iaRate ) internal checkPause { uint amountToSell; uint totalRiskBal = pd.getLastVfull(); uint intermediaryEth; uint ethVol = pd.ethVolumeLimit(); totalRiskBal = (totalRiskBal.mul(100000)).div(DECIMAL1E18); Exchange exchange; if (totalRiskBal > 0) { amountToSell = ((totalRiskBal.mul(2).mul( iaRate)).mul(pd.variationPercX100())).div(100 * 100 * 100000); amountToSell = (amountToSell.mul( 10**uint(pd.getInvestmentAssetDecimals(iaCurr)))).div(100); // amount of asset to sell if (iaCurr != "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(iaCurr))); intermediaryEth = exchange.getTokenToEthInputPrice(amountToSell); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amountToSell = (exchange.getEthToTokenInputPrice(intermediaryEth).mul(995)).div(1000); } IERC20 erc20; erc20 = IERC20(pd.getCurrencyAssetAddress(iaCurr)); erc20.approve(address(exchange), amountToSell); exchange.tokenToEthSwapInput(amountToSell, (exchange.getTokenToEthInputPrice( amountToSell).mul(995)).div(1000), pd.uniswapDeadline().add(now)); } else if (iaCurr == "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) { _transferInvestmentAsset(iaCurr, ms.getLatestAddress("P1"), amountToSell); } emit Rebalancing(iaCurr, amountToSell); } } /** * @dev Checks whether trading is required for a * given investment asset at a given exchange rate. */ function _checkTradeConditions( bytes4 curr, uint64 iaRate, uint totalRiskBal ) internal view returns(bool check) { if (iaRate > 0) { uint iaBalance = _getInvestmentAssetBalance(curr).div(DECIMAL1E18); if (iaBalance > 0 && totalRiskBal > 0) { uint iaMax; uint iaMin; uint checkNumber; uint z; (iaMin, iaMax) = pd.getInvestmentAssetHoldingPerc(curr); z = pd.variationPercX100(); checkNumber = (iaBalance.mul(100 * 100000)).div(totalRiskBal.mul(iaRate)); if ((checkNumber > ((totalRiskBal.mul(iaMax.add(z))).mul(100000)).div(100)) || (checkNumber < ((totalRiskBal.mul(iaMin.sub(z))).mul(100000)).div(100))) check = true; //eligibleIA } } } /** * @dev Gets the investment asset rank. */ function _getIARank( bytes4 curr, uint64 rateX100, uint totalRiskPoolBalance ) internal view returns (int rhsh, int rhsl) //internal function { uint currentIAmaxHolding; uint currentIAminHolding; uint iaBalance = _getInvestmentAssetBalance(curr); (currentIAminHolding, currentIAmaxHolding) = pd.getInvestmentAssetHoldingPerc(curr); if (rateX100 > 0) { uint rhsf; rhsf = (iaBalance.mul(1000000)).div(totalRiskPoolBalance.mul(rateX100)); rhsh = int(rhsf - currentIAmaxHolding); rhsl = int(rhsf - currentIAminHolding); } } /** * @dev Calculates the investment asset rank. */ function _calculateIARank( bytes4[] memory curr, uint64[] memory rate ) internal view returns( bytes4 maxCurr, uint64 maxRate, bytes4 minCurr, uint64 minRate ) { int max = 0; int min = -1; int rhsh; int rhsl; uint totalRiskPoolBalance; (totalRiskPoolBalance, ) = m1.calVtpAndMCRtp(); uint len = curr.length; for (uint i = 0; i < len; i++) { rhsl = 0; rhsh = 0; if (pd.getInvestmentAssetStatus(curr[i])) { (rhsh, rhsl) = _getIARank(curr[i], rate[i], totalRiskPoolBalance); if (rhsh > max || i == 0) { max = rhsh; maxCurr = curr[i]; maxRate = rate[i]; } if (rhsl < min || rhsl == 0 || i == 0) { min = rhsl; minCurr = curr[i]; minRate = rate[i]; } } } } /** * @dev to get balance of an investment asset * @param _curr is the investment asset in concern * @return the balance */ function _getInvestmentAssetBalance(bytes4 _curr) internal view returns (uint balance) { if (_curr == "ETH") { balance = address(this).balance; } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); balance = erc20.balanceOf(address(this)); } } /** * @dev Creates Excess liquidity trading order for a given currency and a given balance. */ function _internalExcessLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal { // require(ms.isInternal(msg.sender) || md.isnotarise(msg.sender)); bytes4 minIACurr; // uint amount; (, , minIACurr, ) = pd.getIARankDetailsByDate(pd.getLastDate()); if (_curr == minIACurr) { // amount = _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2)); //*10**18; p1.transferCurrencyAsset(_curr, _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2))); } else { p1.triggerExternalLiquidityTrade(); } } /** * @dev insufficient liquidity swap * for a given currency and a given balance. */ function _internalInsufficientLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal { bytes4 maxIACurr; uint amount; (maxIACurr, , , ) = pd.getIARankDetailsByDate(pd.getLastDate()); if (_curr == maxIACurr) { amount = (((_baseMin.add(_varMin)).mul(3)).div(2)).sub(_caBalance); _transferInvestmentAsset(_curr, ms.getLatestAddress("P1"), amount); } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr)); if ((maxIACurr == "ETH" && address(this).balance > 0) || (maxIACurr != "ETH" && erc20.balanceOf(address(this)) > 0)) p1.triggerExternalLiquidityTrade(); } } /** * @dev Creates External excess liquidity trading * order for a given currency and a given balance. * @param curr Currency Asset to Sell * @param minIACurr Investment Asset to Buy * @param amount Amount of Currency Asset to Sell */ function _externalExcessLiquiditySwap( bytes4 curr, bytes4 minIACurr, uint256 amount ) internal returns (bool trigger) { uint intermediaryEth; Exchange exchange; IERC20 erc20; uint ethVol = pd.ethVolumeLimit(); if (curr == minIACurr) { p1.transferCurrencyAsset(curr, amount); } else if (curr == "ETH" && minIACurr != "ETH") { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(minIACurr))); if (amount > (address(exchange).balance.mul(ethVol)).div(100)) { // 4% ETH volume limit amount = (address(exchange).balance.mul(ethVol)).div(100); trigger = true; } p1.transferCurrencyAsset(curr, amount); exchange.ethToTokenSwapInput.value(amount) (exchange.getEthToTokenInputPrice(amount).mul(995).div(1000), pd.uniswapDeadline().add(now)); } else if (curr != "ETH" && minIACurr == "ETH") { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); erc20 = IERC20(pd.getCurrencyAssetAddress(curr)); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); intermediaryEth = exchange.getTokenToEthInputPrice(amount); trigger = true; } p1.transferCurrencyAsset(curr, amount); // erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange))); erc20.approve(address(exchange), amount); exchange.tokenToEthSwapInput(amount, ( intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now)); } else { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } Exchange tmp = Exchange(factory.getExchange( pd.getInvestmentAssetAddress(minIACurr))); // minIACurr exchange if (intermediaryEth > address(tmp).balance.mul(ethVol).div(100)) { intermediaryEth = address(tmp).balance.mul(ethVol).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } p1.transferCurrencyAsset(curr, amount); erc20 = IERC20(pd.getCurrencyAssetAddress(curr)); erc20.approve(address(exchange), amount); exchange.tokenToTokenSwapInput(amount, (tmp.getEthToTokenInputPrice( intermediaryEth).mul(995)).div(1000), (intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now), pd.getInvestmentAssetAddress(minIACurr)); } } /** * @dev insufficient liquidity swap * for a given currency and a given balance. * @param curr Currency Asset to buy * @param maxIACurr Investment Asset to sell * @param amount Amount of Investment Asset to sell */ function _externalInsufficientLiquiditySwap( bytes4 curr, bytes4 maxIACurr, uint256 amount ) internal returns (bool trigger) { Exchange exchange; IERC20 erc20; uint intermediaryEth; // uint ethVol = pd.ethVolumeLimit(); if (curr == maxIACurr) { _transferInvestmentAsset(curr, ms.getLatestAddress("P1"), amount); } else if (curr == "ETH" && maxIACurr != "ETH") { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr))); intermediaryEth = exchange.getEthToTokenInputPrice(amount); if (amount > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) { amount = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); intermediaryEth = exchange.getEthToTokenInputPrice(amount); trigger = true; } erc20 = IERC20(pd.getCurrencyAssetAddress(maxIACurr)); if (intermediaryEth > erc20.balanceOf(address(this))) { intermediaryEth = erc20.balanceOf(address(this)); } // erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange))); erc20.approve(address(exchange), intermediaryEth); exchange.tokenToEthTransferInput(intermediaryEth, ( exchange.getTokenToEthInputPrice(intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1)); } else if (curr != "ETH" && maxIACurr == "ETH") { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > address(this).balance) intermediaryEth = address(this).balance; if (intermediaryEth > (address(exchange).balance.mul (pd.ethVolumeLimit())).div(100)) { // 4% ETH volume limit intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); trigger = true; } exchange.ethToTokenTransferInput.value(intermediaryEth)((exchange.getEthToTokenInputPrice( intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1)); } else { address currAdd = pd.getCurrencyAssetAddress(curr); exchange = Exchange(factory.getExchange(currAdd)); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) { intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); trigger = true; } Exchange tmp = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr))); if (intermediaryEth > address(tmp).balance.mul(pd.ethVolumeLimit()).div(100)) { intermediaryEth = address(tmp).balance.mul(pd.ethVolumeLimit()).div(100); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } uint maxIAToSell = tmp.getEthToTokenInputPrice(intermediaryEth); erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr)); uint maxIABal = erc20.balanceOf(address(this)); if (maxIAToSell > maxIABal) { maxIAToSell = maxIABal; intermediaryEth = tmp.getTokenToEthInputPrice(maxIAToSell); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); } amount = exchange.getEthToTokenInputPrice(intermediaryEth); erc20.approve(address(tmp), maxIAToSell); tmp.tokenToTokenTransferInput(maxIAToSell, ( amount.mul(995)).div(1000), ( intermediaryEth), pd.uniswapDeadline().add(now), address(p1), currAdd); } } /** * @dev Transfers ERC20 investment asset from this Pool to another Pool. */ function _upgradeInvestmentPool( bytes4 _curr, address _newPoolAddress ) internal { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); if (erc20.balanceOf(address(this)) > 0) require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this)))); } } // File: nexusmutual-contracts/contracts/Pool1.sol /* Copyright (C) 2017 NexusMutual.io 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/ */ pragma solidity 0.5.7; contract Pool1 is usingOraclize, Iupgradable { using SafeMath for uint; Quotation internal q2; NXMToken internal tk; TokenController internal tc; TokenFunctions internal tf; Pool2 internal p2; PoolData internal pd; MCR internal m1; Claims public c1; TokenData internal td; bool internal locked; uint internal constant DECIMAL1E18 = uint(10) ** 18; // uint internal constant PRICE_STEP = uint(1000) * DECIMAL1E18; event Apiresult(address indexed sender, string msg, bytes32 myid); event Payout(address indexed to, uint coverId, uint tokens); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } function () external payable {} //solhint-disable-line /** * @dev Pays out the sum assured in case a claim is accepted * @param coverid Cover Id. * @param claimid Claim Id. * @return succ true if payout is successful, false otherwise. */ function sendClaimPayout( uint coverid, uint claimid, uint sumAssured, address payable coverHolder, bytes4 coverCurr ) external onlyInternal noReentrancy returns(bool succ) { uint sa = sumAssured.div(DECIMAL1E18); bool check; IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //Payout if (coverCurr == "ETH" && address(this).balance >= sumAssured) { // check = _transferCurrencyAsset(coverCurr, coverHolder, sumAssured); coverHolder.transfer(sumAssured); check = true; } else if (coverCurr == "DAI" && erc20.balanceOf(address(this)) >= sumAssured) { erc20.transfer(coverHolder, sumAssured); check = true; } if (check == true) { q2.removeSAFromCSA(coverid, sa); pd.changeCurrencyAssetVarMin(coverCurr, pd.getCurrencyAssetVarMin(coverCurr).sub(sumAssured)); emit Payout(coverHolder, coverid, sumAssured); succ = true; } else { c1.setClaimStatus(claimid, 12); } _triggerExternalLiquidityTrade(); // p2.internalLiquiditySwap(coverCurr); tf.burnStakerLockedToken(coverid, coverCurr, sumAssured); } /** * @dev to trigger external liquidity trade */ function triggerExternalLiquidityTrade() external onlyInternal { _triggerExternalLiquidityTrade(); } ///@dev Oraclize call to close emergency pause. function closeEmergencyPause(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 300000); _saveApiDetails(myid, "EP", 0); } /// @dev Calls the Oraclize Query to close a given Claim after a given period of time. /// @param id Claim Id to be closed /// @param time Time (in seconds) after which Claims assessment voting needs to be closed function closeClaimsOraclise(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 3000000); _saveApiDetails(myid, "CLA", id); } /// @dev Calls Oraclize Query to expire a given Cover after a given period of time. /// @param id Quote Id to be expired /// @param time Time (in seconds) after which the cover should be expired function closeCoverOraclise(uint id, uint64 time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", strConcat( "http://a1.nexusmutual.io/api/Claims/closeClaim_hash/", uint2str(id)), 1000000); _saveApiDetails(myid, "COV", id); } /// @dev Calls the Oraclize Query to initiate MCR calculation. /// @param time Time (in milliseconds) after which the next MCR calculation should be initiated function mcrOraclise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/postMCR/M1", 0); _saveApiDetails(myid, "MCR", 0); } /// @dev Calls the Oraclize Query in case MCR calculation fails. /// @param time Time (in seconds) after which the next MCR calculation should be initiated function mcrOracliseFail(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 1000000); _saveApiDetails(myid, "MCRF", id); } /// @dev Oraclize call to update investment asset rates. function saveIADetailsOracalise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/saveIADetails/M1", 0); _saveApiDetails(myid, "IARB", 0); } /** * @dev Transfers all assest (i.e ETH balance, Currency Assest) from old Pool to new Pool * @param newPoolAddress Address of the new Pool */ function upgradeCapitalPool(address payable newPoolAddress) external noReentrancy onlyInternal { for (uint64 i = 1; i < pd.getAllCurrenciesLen(); i++) { bytes4 caName = pd.getCurrenciesByIndex(i); _upgradeCapitalPool(caName, newPoolAddress); } if (address(this).balance > 0) { Pool1 newP1 = Pool1(newPoolAddress); newP1.sendEther.value(address(this).balance)(); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { m1 = MCR(ms.getLatestAddress("MC")); tk = NXMToken(ms.tokenAddress()); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); pd = PoolData(ms.getLatestAddress("PD")); q2 = Quotation(ms.getLatestAddress("QT")); p2 = Pool2(ms.getLatestAddress("P2")); c1 = Claims(ms.getLatestAddress("CL")); td = TokenData(ms.getLatestAddress("TD")); } function sendEther() public payable { } /** * @dev transfers currency asset to an address * @param curr is the currency of currency asset to transfer * @param amount is amount of currency asset to transfer * @return boolean to represent success or failure */ function transferCurrencyAsset( bytes4 curr, uint amount ) public onlyInternal noReentrancy returns(bool) { return _transferCurrencyAsset(curr, amount); } /// @dev Handles callback of external oracle query. function __callback(bytes32 myid, string memory result) public { result; //silence compiler warning // owner will be removed from production build ms.delegateCallBack(myid); } /// @dev Enables user to purchase cover with funding in ETH. /// @param smartCAdd Smart Contract Address function makeCoverBegin( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public isMember checkPause payable { require(msg.value == coverDetails[1]); q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Enables user to purchase cover via currency asset eg DAI */ function makeCoverUsingCA( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public isMember checkPause { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); require(erc20.transferFrom(msg.sender, address(this), coverDetails[1]), "Transfer failed"); q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /// @dev Enables user to purchase NXM at the current token price. function buyToken() public payable isMember checkPause returns(bool success) { require(msg.value > 0); uint tokenPurchased = _getToken(address(this).balance, msg.value); tc.mint(msg.sender, tokenPurchased); success = true; } /// @dev Sends a given amount of Ether to a given address. /// @param amount amount (in wei) to send. /// @param _add Receiver's address. /// @return succ True if transfer is a success, otherwise False. function transferEther(uint amount, address payable _add) public noReentrancy checkPause returns(bool succ) { require(ms.checkIsAuthToGoverned(msg.sender), "Not authorized to Govern"); succ = _add.send(amount); } /** * @dev Allows selling of NXM for ether. * Seller first needs to give this contract allowance to * transfer/burn tokens in the NXMToken contract * @param _amount Amount of NXM to sell * @return success returns true on successfull sale */ function sellNXMTokens(uint _amount) public isMember noReentrancy checkPause returns(bool success) { require(tk.balanceOf(msg.sender) >= _amount, "Not enough balance"); require(!tf.isLockedForMemberVote(msg.sender), "Member voted"); require(_amount <= m1.getMaxSellTokens(), "exceeds maximum token sell limit"); uint sellingPrice = _getWei(_amount); tc.burnFrom(msg.sender, _amount); msg.sender.transfer(sellingPrice); success = true; } /** * @dev gives the investment asset balance * @return investment asset balance */ function getInvestmentAssetBalance() public view returns (uint balance) { IERC20 erc20; uint currTokens; for (uint i = 1; i < pd.getInvestmentCurrencyLen(); i++) { bytes4 currency = pd.getInvestmentCurrencyByIndex(i); erc20 = IERC20(pd.getInvestmentAssetAddress(currency)); currTokens = erc20.balanceOf(address(p2)); if (pd.getIAAvgRate(currency) > 0) balance = balance.add((currTokens.mul(100)).div(pd.getIAAvgRate(currency))); } balance = balance.add(address(p2).balance); } /** * @dev Returns the amount of wei a seller will get for selling NXM * @param amount Amount of NXM to sell * @return weiToPay Amount of wei the seller will get */ function getWei(uint amount) public view returns(uint weiToPay) { return _getWei(amount); } /** * @dev Returns the amount of token a buyer will get for corresponding wei * @param weiPaid Amount of wei * @return tokenToGet Amount of tokens the buyer will get */ function getToken(uint weiPaid) public view returns(uint tokenToGet) { return _getToken((address(this).balance).add(weiPaid), weiPaid); } /** * @dev to trigger external liquidity trade */ function _triggerExternalLiquidityTrade() internal { if (now > pd.lastLiquidityTradeTrigger().add(pd.liquidityTradeCallbackTime())) { pd.setLastLiquidityTradeTrigger(); bytes32 myid = _oraclizeQuery(4, pd.liquidityTradeCallbackTime(), "URL", "", 300000); _saveApiDetails(myid, "ULT", 0); } } /** * @dev Returns the amount of wei a seller will get for selling NXM * @param _amount Amount of NXM to sell * @return weiToPay Amount of wei the seller will get */ function _getWei(uint _amount) internal view returns(uint weiToPay) { uint tokenPrice; uint weiPaid; uint tokenSupply = tk.totalSupply(); uint vtp; uint mcrFullperc; uint vFull; uint mcrtp; (mcrFullperc, , vFull, ) = pd.getLastMCR(); (vtp, ) = m1.calVtpAndMCRtp(); while (_amount > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp); tokenPrice = (tokenPrice.mul(975)).div(1000); //97.5% if (_amount <= td.priceStep().mul(DECIMAL1E18)) { weiToPay = weiToPay.add((tokenPrice.mul(_amount)).div(DECIMAL1E18)); break; } else { _amount = _amount.sub(td.priceStep().mul(DECIMAL1E18)); tokenSupply = tokenSupply.sub(td.priceStep().mul(DECIMAL1E18)); weiPaid = (tokenPrice.mul(td.priceStep().mul(DECIMAL1E18))).div(DECIMAL1E18); vtp = vtp.sub(weiPaid); weiToPay = weiToPay.add(weiPaid); } } } /** * @dev gives the token * @param _poolBalance is the pool balance * @param _weiPaid is the amount paid in wei * @return the token to get */ function _getToken(uint _poolBalance, uint _weiPaid) internal view returns(uint tokenToGet) { uint tokenPrice; uint superWeiLeft = (_weiPaid).mul(DECIMAL1E18); uint tempTokens; uint superWeiSpent; uint tokenSupply = tk.totalSupply(); uint vtp; uint mcrFullperc; uint vFull; uint mcrtp; (mcrFullperc, , vFull, ) = pd.getLastMCR(); (vtp, ) = m1.calculateVtpAndMCRtp((_poolBalance).sub(_weiPaid)); require(m1.calculateTokenPrice("ETH") > 0, "Token price can not be zero"); while (superWeiLeft > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp); tempTokens = superWeiLeft.div(tokenPrice); if (tempTokens <= td.priceStep().mul(DECIMAL1E18)) { tokenToGet = tokenToGet.add(tempTokens); break; } else { tokenToGet = tokenToGet.add(td.priceStep().mul(DECIMAL1E18)); tokenSupply = tokenSupply.add(td.priceStep().mul(DECIMAL1E18)); superWeiSpent = td.priceStep().mul(DECIMAL1E18).mul(tokenPrice); superWeiLeft = superWeiLeft.sub(superWeiSpent); vtp = vtp.add((td.priceStep().mul(DECIMAL1E18).mul(tokenPrice)).div(DECIMAL1E18)); } } } /** * @dev Save the details of the Oraclize API. * @param myid Id return by the oraclize query. * @param _typeof type of the query for which oraclize call is made. * @param id ID of the proposal, quote, cover etc. for which oraclize call is made. */ function _saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) internal { pd.saveApiDetails(myid, _typeof, id); pd.addInAllApiCall(myid); } /** * @dev transfers currency asset * @param _curr is currency of asset to transfer * @param _amount is the amount to be transferred * @return boolean representing the success of transfer */ function _transferCurrencyAsset(bytes4 _curr, uint _amount) internal returns(bool succ) { if (_curr == "ETH") { if (address(this).balance < _amount) _amount = address(this).balance; p2.sendEther.value(_amount)(); succ = true; } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); //solhint-disable-line if (erc20.balanceOf(address(this)) < _amount) _amount = erc20.balanceOf(address(this)); require(erc20.transfer(address(p2), _amount)); succ = true; } } /** * @dev Transfers ERC20 Currency asset from this Pool to another Pool on upgrade. */ function _upgradeCapitalPool( bytes4 _curr, address _newPoolAddress ) internal { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); if (erc20.balanceOf(address(this)) > 0) require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this)))); } /** * @dev oraclize query * @param paramCount is number of paramters passed * @param timestamp is the current timestamp * @param datasource in concern * @param arg in concern * @param gasLimit required for query * @return id of oraclize query */ function _oraclizeQuery( uint paramCount, uint timestamp, string memory datasource, string memory arg, uint gasLimit ) internal returns (bytes32 id) { if (paramCount == 4) { id = oraclize_query(timestamp, datasource, arg, gasLimit); } else if (paramCount == 3) { id = oraclize_query(timestamp, datasource, arg); } else { id = oraclize_query(datasource, arg); } } } // File: nexusmutual-contracts/contracts/MCR.sol /* Copyright (C) 2017 NexusMutual.io 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/ */ pragma solidity 0.5.7; contract MCR is Iupgradable { using SafeMath for uint; Pool1 internal p1; PoolData internal pd; NXMToken internal tk; QuotationData internal qd; MemberRoles internal mr; TokenData internal td; ProposalCategory internal proposalCategory; uint private constant DECIMAL1E18 = uint(10) ** 18; uint private constant DECIMAL1E05 = uint(10) ** 5; uint private constant DECIMAL1E19 = uint(10) ** 19; uint private constant minCapFactor = uint(10) ** 21; uint public variableMincap; uint public dynamicMincapThresholdx100 = 13000; uint public dynamicMincapIncrementx100 = 100; event MCREvent( uint indexed date, uint blockNumber, bytes4[] allCurr, uint[] allCurrRates, uint mcrEtherx100, uint mcrPercx100, uint vFull ); /** * @dev Adds new MCR data. * @param mcrP Minimum Capital Requirement in percentage. * @param vF Pool1 fund value in Ether used in the last full daily calculation of the Capital model. * @param onlyDate Date(yyyymmdd) at which MCR details are getting added. */ function addMCRData( uint mcrP, uint mcrE, uint vF, bytes4[] calldata curr, uint[] calldata _threeDayAvg, uint64 onlyDate ) external checkPause { require(proposalCategory.constructorCheck()); require(pd.isnotarise(msg.sender)); if (mr.launched() && pd.capReached() != 1) { if (mcrP >= 10000) pd.setCapReached(1); } uint len = pd.getMCRDataLength(); _addMCRData(len, onlyDate, curr, mcrE, mcrP, vF, _threeDayAvg); } /** * @dev Adds MCR Data for last failed attempt. */ function addLastMCRData(uint64 date) external checkPause onlyInternal { uint64 lastdate = uint64(pd.getLastMCRDate()); uint64 failedDate = uint64(date); if (failedDate >= lastdate) { uint mcrP; uint mcrE; uint vF; (mcrP, mcrE, vF, ) = pd.getLastMCR(); uint len = pd.getAllCurrenciesLen(); pd.pushMCRData(mcrP, mcrE, vF, date); for (uint j = 0; j < len; j++) { bytes4 currName = pd.getCurrenciesByIndex(j); pd.updateCAAvgRate(currName, pd.getCAAvgRate(currName)); } emit MCREvent(date, block.number, new bytes4[](0), new uint[](0), mcrE, mcrP, vF); // Oraclize call for next MCR calculation _callOracliseForMCR(); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { qd = QuotationData(ms.getLatestAddress("QD")); p1 = Pool1(ms.getLatestAddress("P1")); pd = PoolData(ms.getLatestAddress("PD")); tk = NXMToken(ms.tokenAddress()); mr = MemberRoles(ms.getLatestAddress("MR")); td = TokenData(ms.getLatestAddress("TD")); proposalCategory = ProposalCategory(ms.getLatestAddress("PC")); } /** * @dev Gets total sum assured(in ETH). * @return amount of sum assured */ function getAllSumAssurance() public view returns(uint amount) { uint len = pd.getAllCurrenciesLen(); for (uint i = 0; i < len; i++) { bytes4 currName = pd.getCurrenciesByIndex(i); if (currName == "ETH") { amount = amount.add(qd.getTotalSumAssured(currName)); } else { if (pd.getCAAvgRate(currName) > 0) amount = amount.add((qd.getTotalSumAssured(currName).mul(100)).div(pd.getCAAvgRate(currName))); } } } /** * @dev Calculates V(Tp) and MCR%(Tp), i.e, Pool Fund Value in Ether * and MCR% used in the Token Price Calculation. * @return vtp Pool Fund Value in Ether used for the Token Price Model * @return mcrtp MCR% used in the Token Price Model. */ function _calVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) { vtp = 0; IERC20 erc20; uint currTokens = 0; uint i; for (i = 1; i < pd.getAllCurrenciesLen(); i++) { bytes4 currency = pd.getCurrenciesByIndex(i); erc20 = IERC20(pd.getCurrencyAssetAddress(currency)); currTokens = erc20.balanceOf(address(p1)); if (pd.getCAAvgRate(currency) > 0) vtp = vtp.add((currTokens.mul(100)).div(pd.getCAAvgRate(currency))); } vtp = vtp.add(poolBalance).add(p1.getInvestmentAssetBalance()); uint mcrFullperc; uint vFull; (mcrFullperc, , vFull, ) = pd.getLastMCR(); if (vFull > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); } } /** * @dev Calculates the Token Price of NXM in a given currency. * @param curr Currency name. */ function calculateStepTokenPrice( bytes4 curr, uint mcrtp ) public view onlyInternal returns(uint tokenPrice) { return _calculateTokenPrice(curr, mcrtp); } /** * @dev Calculates the Token Price of NXM in a given currency * with provided token supply for dynamic token price calculation * @param curr Currency name. */ function calculateTokenPrice (bytes4 curr) public view returns(uint tokenPrice) { uint mcrtp; (, mcrtp) = _calVtpAndMCRtp(address(p1).balance); return _calculateTokenPrice(curr, mcrtp); } function calVtpAndMCRtp() public view returns(uint vtp, uint mcrtp) { return _calVtpAndMCRtp(address(p1).balance); } function calculateVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) { return _calVtpAndMCRtp(poolBalance); } function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) public view returns(uint lowerThreshold, uint upperThreshold) { minCap = (minCap.mul(minCapFactor)).add(variableMincap); uint lower = 0; if (vtp >= vF) { upperThreshold = vtp.mul(120).mul(100).div((minCap)); //Max Threshold = [MAX(Vtp, Vfull) x 120] / mcrMinCap } else { upperThreshold = vF.mul(120).mul(100).div((minCap)); } if (vtp > 0) { lower = totalSA.mul(DECIMAL1E18).mul(pd.shockParameter()).div(100); if(lower < minCap.mul(11).div(10)) lower = minCap.mul(11).div(10); } if (lower > 0) { //Min Threshold = [Vtp / MAX(TotalActiveSA x ShockParameter, mcrMinCap x 1.1)] x 100 lowerThreshold = vtp.mul(100).mul(100).div(lower); } } /** * @dev Gets max numbers of tokens that can be sold at the moment. */ function getMaxSellTokens() public view returns(uint maxTokens) { uint baseMin = pd.getCurrencyAssetBaseMin("ETH"); uint maxTokensAccPoolBal; if (address(p1).balance > baseMin.mul(50).div(100)) { maxTokensAccPoolBal = address(p1).balance.sub( (baseMin.mul(50)).div(100)); } maxTokensAccPoolBal = (maxTokensAccPoolBal.mul(DECIMAL1E18)).div( (calculateTokenPrice("ETH").mul(975)).div(1000)); uint lastMCRPerc = pd.getLastMCRPerc(); if (lastMCRPerc > 10000) maxTokens = (((uint(lastMCRPerc).sub(10000)).mul(2000)).mul(DECIMAL1E18)).div(10000); if (maxTokens > maxTokensAccPoolBal) maxTokens = maxTokensAccPoolBal; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "DMCT") { val = dynamicMincapThresholdx100; } else if (code == "DMCI") { val = dynamicMincapIncrementx100; } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "DMCT") { dynamicMincapThresholdx100 = val; } else if (code == "DMCI") { dynamicMincapIncrementx100 = val; } else { revert("Invalid param code"); } } /** * @dev Calls oraclize query to calculate MCR details after 24 hours. */ function _callOracliseForMCR() internal { p1.mcrOraclise(pd.mcrTime()); } /** * @dev Calculates the Token Price of NXM in a given currency * with provided token supply for dynamic token price calculation * @param _curr Currency name. * @return tokenPrice Token price. */ function _calculateTokenPrice( bytes4 _curr, uint mcrtp ) internal view returns(uint tokenPrice) { uint getA; uint getC; uint getCAAvgRate; uint tokenExponentValue = td.tokenExponent(); // uint max = (mcrtp.mul(mcrtp).mul(mcrtp).mul(mcrtp)); uint max = mcrtp ** tokenExponentValue; uint dividingFactor = tokenExponentValue.mul(4); (getA, getC, getCAAvgRate) = pd.getTokenPriceDetails(_curr); uint mcrEth = pd.getLastMCREther(); getC = getC.mul(DECIMAL1E18); tokenPrice = (mcrEth.mul(DECIMAL1E18).mul(max).div(getC)).div(10 ** dividingFactor); tokenPrice = tokenPrice.add(getA.mul(DECIMAL1E18).div(DECIMAL1E05)); tokenPrice = tokenPrice.mul(getCAAvgRate * 10); tokenPrice = (tokenPrice).div(10**3); } /** * @dev Adds MCR Data. Checks if MCR is within valid * thresholds in order to rule out any incorrect calculations */ function _addMCRData( uint len, uint64 newMCRDate, bytes4[] memory curr, uint mcrE, uint mcrP, uint vF, uint[] memory _threeDayAvg ) internal { uint vtp = 0; uint lowerThreshold = 0; uint upperThreshold = 0; if (len > 1) { (vtp, ) = _calVtpAndMCRtp(address(p1).balance); (lowerThreshold, upperThreshold) = getThresholdValues(vtp, vF, getAllSumAssurance(), pd.minCap()); } if(mcrP > dynamicMincapThresholdx100) variableMincap = (variableMincap.mul(dynamicMincapIncrementx100.add(10000)).add(minCapFactor.mul(pd.minCap().mul(dynamicMincapIncrementx100)))).div(10000); // Explanation for above formula :- // actual formula -> variableMinCap = variableMinCap + (variableMinCap+minCap)*dynamicMincapIncrement/100 // Implemented formula is simplified form of actual formula. // Let consider above formula as b = b + (a+b)*c/100 // here, dynamicMincapIncrement is in x100 format. // so b+(a+b)*cx100/10000 can be written as => (10000.b + b.cx100 + a.cx100)/10000. // It can further simplify to (b.(10000+cx100) + a.cx100)/10000. if (len == 1 || (mcrP) >= lowerThreshold && (mcrP) <= upperThreshold) { vtp = pd.getLastMCRDate(); // due to stack to deep error,we are reusing already declared variable pd.pushMCRData(mcrP, mcrE, vF, newMCRDate); for (uint i = 0; i < curr.length; i++) { pd.updateCAAvgRate(curr[i], _threeDayAvg[i]); } emit MCREvent(newMCRDate, block.number, curr, _threeDayAvg, mcrE, mcrP, vF); // Oraclize call for next MCR calculation if (vtp < newMCRDate) { _callOracliseForMCR(); } } else { p1.mcrOracliseFail(newMCRDate, pd.mcrFailTime()); } } } // File: nexusmutual-contracts/contracts/Claims.sol /* Copyright (C) 2017 NexusMutual.io 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/ */ pragma solidity 0.5.7; contract Claims is Iupgradable { using SafeMath for uint; TokenFunctions internal tf; NXMToken internal tk; TokenController internal tc; ClaimsReward internal cr; Pool1 internal p1; ClaimsData internal cd; TokenData internal td; PoolData internal pd; Pool2 internal p2; QuotationData internal qd; MCR internal m1; uint private constant DECIMAL1E18 = uint(10) ** 18; /** * @dev Sets the status of claim using claim id. * @param claimId claim id. * @param stat status to be set. */ function setClaimStatus(uint claimId, uint stat) external onlyInternal { _setClaimStatus(claimId, stat); } /** * @dev Gets claim details of claim id = pending claim start + given index */ function getClaimFromNewStart( uint index ) external view returns ( uint coverId, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { (coverId, claimId, voteCA, voteMV, statusnumber) = cd.getClaimFromNewStart(index, msg.sender); // status = rewardStatus[statusnumber].claimStatusDesc; } /** * @dev Gets details of a claim submitted by the calling user, at a given index */ function getUserClaimByIndex( uint index ) external view returns( uint status, uint coverId, uint claimId ) { uint statusno; (statusno, coverId, claimId) = cd.getUserClaimByIndex(index, msg.sender); status = statusno; } /** * @dev Gets details of a given claim id. * @param _claimId Claim Id. * @return status Current status of claim id * @return finalVerdict Decision made on the claim, 1 -> acceptance, -1 -> denial * @return claimOwner Address through which claim is submitted * @return coverId Coverid associated with the claim id */ function getClaimbyIndex(uint _claimId) external view returns ( uint claimId, uint status, int8 finalVerdict, address claimOwner, uint coverId ) { uint stat; claimId = _claimId; (, coverId, finalVerdict, stat, , ) = cd.getClaim(_claimId); claimOwner = qd.getCoverMemberAddress(coverId); status = stat; } /** * @dev Calculates total amount that has been used to assess a claim. * Computaion:Adds acceptCA(tokens used for voting in favor of a claim) * denyCA(tokens used for voting against a claim) * current token price. * @param claimId Claim Id. * @param member Member type 0 -> Claim Assessors, else members. * @return tokens Total Amount used in Claims assessment. */ function getCATokens(uint claimId, uint member) external view returns(uint tokens) { uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 curr = qd.getCurrencyOfCover(coverId); uint tokenx1e18 = m1.calculateTokenPrice(curr); uint accept; uint deny; if (member == 0) { (, accept, deny) = cd.getClaimsTokenCA(claimId); } else { (, accept, deny) = cd.getClaimsTokenMV(claimId); } tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens) } /** * Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { tk = NXMToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); p1 = Pool1(ms.getLatestAddress("P1")); p2 = Pool2(ms.getLatestAddress("P2")); pd = PoolData(ms.getLatestAddress("PD")); cr = ClaimsReward(ms.getLatestAddress("CR")); cd = ClaimsData(ms.getLatestAddress("CD")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function changePendingClaimStart() public onlyInternal { uint origstat; uint state12Count; uint pendingClaimStart = cd.pendingClaimStart(); uint actualClaimLength = cd.actualClaimLength(); for (uint i = pendingClaimStart; i < actualClaimLength; i++) { (, , , origstat, , state12Count) = cd.getClaim(i); if (origstat > 5 && ((origstat != 12) || (origstat == 12 && state12Count >= 60))) cd.setpendingClaimStart(i); else break; } } /** * @dev Submits a claim for a given cover note. * Adds claim to queue incase of emergency pause else directly submits the claim. * @param coverId Cover Id. */ function submitClaim(uint coverId) public { address qadd = qd.getCoverMemberAddress(coverId); require(qadd == msg.sender); uint8 cStatus; (, cStatus, , , ) = qd.getCoverDetailsByCoverID2(coverId); require(cStatus != uint8(QuotationData.CoverStatus.ClaimSubmitted), "Claim already submitted"); require(cStatus != uint8(QuotationData.CoverStatus.CoverExpired), "Cover already expired"); if (ms.isPause() == false) { _addClaim(coverId, now, qadd); } else { cd.setClaimAtEmergencyPause(coverId, now, false); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.Requested)); } } /** * @dev Submits the Claims queued once the emergency pause is switched off. */ function submitClaimAfterEPOff() public onlyInternal { uint lengthOfClaimSubmittedAtEP = cd.getLengthOfClaimSubmittedAtEP(); uint firstClaimIndexToSubmitAfterEP = cd.getFirstClaimIndexToSubmitAfterEP(); uint coverId; uint dateUpd; bool submit; address qadd; for (uint i = firstClaimIndexToSubmitAfterEP; i < lengthOfClaimSubmittedAtEP; i++) { (coverId, dateUpd, submit) = cd.getClaimOfEmergencyPauseByIndex(i); require(submit == false); qadd = qd.getCoverMemberAddress(coverId); _addClaim(coverId, dateUpd, qadd); cd.setClaimSubmittedAtEPTrue(i, true); } cd.setFirstClaimIndexToSubmitAfterEP(lengthOfClaimSubmittedAtEP); } /** * @dev Castes vote for members who have tokens locked under Claims Assessment * @param claimId claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now); uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime())); require(tokens > 0); uint stat; (, stat) = cd.getClaimStatusNumber(claimId); require(stat == 0); require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0); td.bookCATokens(msg.sender); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict); uint voteLength = cd.getAllVoteLength(); cd.addClaimVoteCA(claimId, voteLength); cd.setUserClaimVoteCA(msg.sender, claimId, voteLength); cd.setClaimTokensCA(claimId, verdict, tokens); tc.extendLockOf(msg.sender, "CLA", td.lockCADays()); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } /** * @dev Submits a member vote for assessing a claim. * Tokens other than those locked under Claims * Assessment can be used to cast a vote for a given claim id. * @param claimId Selected claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); uint stat; uint tokens = tc.totalBalanceOf(msg.sender); (, stat) = cd.getClaimStatusNumber(claimId); require(stat >= 1 && stat <= 5); require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict); tc.lockForMemberVote(msg.sender, td.lockMVDays()); uint voteLength = cd.getAllVoteLength(); cd.addClaimVotemember(claimId, voteLength); cd.setUserClaimVoteMember(msg.sender, claimId, voteLength); cd.setClaimTokensMV(claimId, verdict, tokens); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } /** * @dev Pause Voting of All Pending Claims when Emergency Pause Start. */ function pauseAllPendingClaimsVoting() public onlyInternal { uint firstIndex = cd.pendingClaimStart(); uint actualClaimLength = cd.actualClaimLength(); for (uint i = firstIndex; i < actualClaimLength; i++) { if (checkVoteClosing(i) == 0) { uint dateUpd = cd.getClaimDateUpd(i); cd.setPendingClaimDetails(i, (dateUpd.add(cd.maxVotingTime())).sub(now), false); } } } /** * @dev Resume the voting phase of all Claims paused due to an emergency pause. */ function startAllPendingClaimsVoting() public onlyInternal { uint firstIndx = cd.getFirstClaimIndexToStartVotingAfterEP(); uint i; uint lengthOfClaimVotingPause = cd.getLengthOfClaimVotingPause(); for (i = firstIndx; i < lengthOfClaimVotingPause; i++) { uint pendingTime; uint claimID; (claimID, pendingTime, ) = cd.getPendingClaimDetailsByIndex(i); uint pTime = (now.sub(cd.maxVotingTime())).add(pendingTime); cd.setClaimdateUpd(claimID, pTime); cd.setPendingClaimVoteStatus(i, true); uint coverid; (, coverid) = cd.getClaimCoverId(claimID); address qadd = qd.getCoverMemberAddress(coverid); tf.extendCNEPOff(qadd, coverid, pendingTime.add(cd.claimDepositTime())); p1.closeClaimsOraclise(claimID, uint64(pTime)); } cd.setFirstClaimIndexToStartVotingAfterEP(i); } /** * @dev Checks if voting of a claim should be closed or not. * @param claimId Claim Id. * @return close 1 -> voting should be closed, 0 -> if voting should not be closed, * -1 -> voting has already been closed. */ function checkVoteClosing(uint claimId) public view returns(int8 close) { close = 0; uint status; (, status) = cd.getClaimStatusNumber(claimId); uint dateUpd = cd.getClaimDateUpd(claimId); if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) { if (cd.getClaimState12Count(claimId) < 60) close = 1; } if (status > 5 && status != 12) { close = -1; } else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) { close = 1; } else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) { close = 0; } else if (status == 0 || (status >= 1 && status <= 5)) { close = _checkVoteClosingFinal(claimId, status); } } /** * @dev Checks if voting of a claim should be closed or not. * Internally called by checkVoteClosing method * for Claims whose status number is 0 or status number lie between 2 and 6. * @param claimId Claim Id. * @param status Current status of claim. * @return close 1 if voting should be closed,0 in case voting should not be closed, * -1 if voting has already been closed. */ function _checkVoteClosingFinal(uint claimId, uint status) internal view returns(int8 close) { close = 0; uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 curr = qd.getCurrencyOfCover(coverId); uint tokenx1e18 = m1.calculateTokenPrice(curr); uint accept; uint deny; (, accept, deny) = cd.getClaimsTokenCA(claimId); uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); (, accept, deny) = cd.getClaimsTokenMV(claimId); uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18); if (status == 0 && caTokens >= sumassured.mul(10)) { close = 1; } else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) { close = 1; } } /** * @dev Changes the status of an existing claim id, based on current * status and current conditions of the system * @param claimId Claim Id. * @param stat status number. */ function _setClaimStatus(uint claimId, uint stat) internal { uint origstat; uint state12Count; uint dateUpd; uint coverId; (, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId); (, origstat) = cd.getClaimStatusNumber(claimId); if (stat == 12 && origstat == 12) { cd.updateState12Count(claimId, 1); } cd.setClaimStatus(claimId, stat); if (state12Count >= 60 && stat == 12) { cd.setClaimStatus(claimId, 13); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied)); } uint time = now; cd.setClaimdateUpd(claimId, time); if (stat >= 2 && stat <= 5) { p1.closeClaimsOraclise(claimId, cd.maxVotingTime()); } if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) <= now) && (state12Count < 60)) { p1.closeClaimsOraclise(claimId, cd.payoutRetryTime()); } else if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) > now) && (state12Count < 60)) { uint64 timeLeft = uint64((dateUpd.add(cd.payoutRetryTime())).sub(now)); p1.closeClaimsOraclise(claimId, timeLeft); } } /** * @dev Submits a claim for a given cover note. * Set deposits flag against cover. */ function _addClaim(uint coverId, uint time, address add) internal { tf.depositCN(coverId); uint len = cd.actualClaimLength(); cd.addClaim(len, coverId, add, now); cd.callClaimEvent(coverId, add, len, time); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted)); bytes4 curr = qd.getCurrencyOfCover(coverId); uint sumAssured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18); pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).add(sumAssured)); p2.internalLiquiditySwap(curr); p1.closeClaimsOraclise(len, cd.maxVotingTime()); } } // File: nexusmutual-contracts/contracts/ClaimsReward.sol /* Copyright (C) 2020 NexusMutual.io 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/ */ //Claims Reward Contract contains the functions for calculating number of tokens // that will get rewarded, unlocked or burned depending upon the status of claim. pragma solidity 0.5.7; contract ClaimsReward is Iupgradable { using SafeMath for uint; NXMToken internal tk; TokenController internal tc; TokenFunctions internal tf; TokenData internal td; QuotationData internal qd; Claims internal c1; ClaimsData internal cd; Pool1 internal p1; Pool2 internal p2; PoolData internal pd; Governance internal gv; IPooledStaking internal pooledStaking; uint private constant DECIMAL1E18 = uint(10) ** 18; function changeDependentContractAddress() public onlyInternal { c1 = Claims(ms.getLatestAddress("CL")); cd = ClaimsData(ms.getLatestAddress("CD")); tk = NXMToken(ms.tokenAddress()); tc = TokenController(ms.getLatestAddress("TC")); td = TokenData(ms.getLatestAddress("TD")); tf = TokenFunctions(ms.getLatestAddress("TF")); p1 = Pool1(ms.getLatestAddress("P1")); p2 = Pool2(ms.getLatestAddress("P2")); pd = PoolData(ms.getLatestAddress("PD")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); } /// @dev Decides the next course of action for a given claim. function changeClaimStatus(uint claimid) public checkPause onlyInternal { uint coverid; (, coverid) = cd.getClaimCoverId(claimid); uint status; (, status) = cd.getClaimStatusNumber(claimid); // when current status is "Pending-Claim Assessor Vote" if (status == 0) { _changeClaimStatusCA(claimid, coverid, status); } else if (status >= 1 && status <= 5) { _changeClaimStatusMV(claimid, coverid, status); } else if (status == 12) { // when current status is "Claim Accepted Payout Pending" uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); address payable coverHolder = qd.getCoverMemberAddress(coverid); bytes4 coverCurrency = qd.getCurrencyOfCover(coverid); bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, coverHolder, coverCurrency); if (success) { tf.burnStakedTokens(coverid, coverCurrency, sumAssured); c1.setClaimStatus(claimid, 14); } } c1.changePendingClaimStart(); } /// @dev Amount of tokens to be rewarded to a user for a particular vote id. /// @param check 1 -> CA vote, else member vote /// @param voteid vote id for which reward has to be Calculated /// @param flag if 1 calculate even if claimed,else don't calculate if already claimed /// @return tokenCalculated reward to be given for vote id /// @return lastClaimedCheck true if final verdict is still pending for that voteid /// @return tokens number of tokens locked under that voteid /// @return perc percentage of reward to be given. function getRewardToBeGiven( uint check, uint voteid, uint flag ) public view returns ( uint tokenCalculated, bool lastClaimedCheck, uint tokens, uint perc ) { uint claimId; int8 verdict; bool claimed; uint tokensToBeDist; uint totalTokens; (tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid); lastClaimedCheck = false; int8 claimVerdict = cd.getFinalVerdict(claimId); if (claimVerdict == 0) { lastClaimedCheck = true; } if (claimVerdict == verdict && (claimed == false || flag == 1)) { if (check == 1) { (perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId); } else { (, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId); } if (perc > 0) { if (check == 1) { if (verdict == 1) { (, totalTokens, ) = cd.getClaimsTokenCA(claimId); } else { (, , totalTokens) = cd.getClaimsTokenCA(claimId); } } else { if (verdict == 1) { (, totalTokens, ) = cd.getClaimsTokenMV(claimId); }else { (, , totalTokens) = cd.getClaimsTokenMV(claimId); } } tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100)); } } } /// @dev Transfers all tokens held by contract to a new contract in case of upgrade. function upgrade(address _newAdd) public onlyInternal { uint amount = tk.balanceOf(address(this)); if (amount > 0) { require(tk.transfer(_newAdd, amount)); } } /// @dev Total reward in token due for claim by a user. /// @return total total number of tokens function getRewardToBeDistributedByUser(address _add) public view returns(uint total) { uint lengthVote = cd.getVoteAddressCALength(_add); uint lastIndexCA; uint lastIndexMV; uint tokenForVoteId; uint voteId; (lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add); for (uint i = lastIndexCA; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(_add, i); (tokenForVoteId, , , ) = getRewardToBeGiven(1, voteId, 0); total = total.add(tokenForVoteId); } lengthVote = cd.getVoteAddressMemberLength(_add); for (uint j = lastIndexMV; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(_add, j); (tokenForVoteId, , , ) = getRewardToBeGiven(0, voteId, 0); total = total.add(tokenForVoteId); } return (total); } /// @dev Gets reward amount and claiming status for a given claim id. /// @return reward amount of tokens to user. /// @return claimed true if already claimed false if yet to be claimed. function getRewardAndClaimedStatus(uint check, uint claimId) public view returns(uint reward, bool claimed) { uint voteId; uint claimid; uint lengthVote; if (check == 1) { lengthVote = cd.getVoteAddressCALength(msg.sender); for (uint i = 0; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(msg.sender, i); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) { break; } } } else { lengthVote = cd.getVoteAddressMemberLength(msg.sender); for (uint j = 0; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(msg.sender, j); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) { break; } } } (reward, , , ) = getRewardToBeGiven(check, voteId, 1); } /** * @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance * Claim assesment, Risk assesment, Governance rewards */ function claimAllPendingReward(uint records) public isMemberAndcheckPause { _claimRewardToBeDistributed(records); pooledStaking.withdrawReward(msg.sender); uint governanceRewards = gv.claimReward(msg.sender, records); if (governanceRewards > 0) { require(tk.transfer(msg.sender, governanceRewards)); } } /** * @dev Function used to get pending rewards of a particular user address. * @param _add user address. * @return total reward amount of the user */ function getAllPendingRewardOfUser(address _add) public view returns(uint) { uint caReward = getRewardToBeDistributedByUser(_add); uint pooledStakingReward = pooledStaking.stakerReward(_add); uint governanceReward = gv.getPendingReward(_add); return caReward.add(pooledStakingReward).add(governanceReward); } /// @dev Rewards/Punishes users who participated in Claims assessment. // Unlocking and burning of the tokens will also depend upon the status of claim. /// @param claimid Claim Id. function _rewardAgainstClaim(uint claimid, uint coverid, uint sumAssured, uint status) internal { uint premiumNXM = qd.getCoverPremiumNXM(coverid); bytes4 curr = qd.getCurrencyOfCover(coverid); uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100);// 20% of premium uint percCA; uint percMV; (percCA, percMV) = cd.getRewardStatus(status); cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens); if (percCA > 0 || percMV > 0) { tc.mint(address(this), distributableTokens); } if (status == 6 || status == 9 || status == 11) { cd.changeFinalVerdict(claimid, -1); td.setDepositCN(coverid, false); // Unset flag tf.burnDepositCN(coverid); // burn Deposited CN pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).sub(sumAssured)); p2.internalLiquiditySwap(curr); } else if (status == 7 || status == 8 || status == 10) { cd.changeFinalVerdict(claimid, 1); td.setDepositCN(coverid, false); // Unset flag tf.unlockCN(coverid); bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, qd.getCoverMemberAddress(coverid), curr); if (success) { tf.burnStakedTokens(coverid, curr, sumAssured); } } } /// @dev Computes the result of Claim Assessors Voting for a given claim id. function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency. uint accept; uint deny; uint acceptAndDeny; bool rewardOrPunish; uint sumAssured; (, accept) = cd.getClaimVote(claimid, 1); (, deny) = cd.getClaimVote(claimid, -1); acceptAndDeny = accept.add(deny); accept = accept.mul(100); deny = deny.mul(100); if (caTokens == 0) { status = 3; } else { sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); // Min threshold reached tokens used for voting > 5* sum assured if (caTokens > sumAssured.mul(5)) { if (accept.div(acceptAndDeny) > 70) { status = 7; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted)); rewardOrPunish = true; } else if (deny.div(acceptAndDeny) > 70) { status = 6; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied)); rewardOrPunish = true; } else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 4; } else { status = 5; } } else { if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 2; } else { status = 3; } } } c1.setClaimStatus(claimid, status); if (rewardOrPunish) { _rewardAgainstClaim(claimid, coverid, sumAssured, status); } } } /// @dev Computes the result of Member Voting for a given claim id. function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint8 coverStatus; uint statusOrig = status; uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency. // If tokens used for acceptance >50%, claim is accepted uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); uint thresholdUnreached = 0; // Minimum threshold for member voting is reached only when // value of tokens used for voting > 5* sum assured of claim id if (mvTokens < sumAssured.mul(5)) { thresholdUnreached = 1; } uint accept; (, accept) = cd.getClaimMVote(claimid, 1); uint deny; (, deny) = cd.getClaimMVote(claimid, -1); if (accept.add(deny) > 0) { if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 8; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 9; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } } if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) { status = 10; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) { status = 11; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } c1.setClaimStatus(claimid, status); qd.changeCoverStatusNo(coverid, uint8(coverStatus)); // Reward/Punish Claim Assessors and Members who participated in Claims assessment _rewardAgainstClaim(claimid, coverid, sumAssured, status); } } /// @dev Allows a user to claim all pending Claims assessment rewards. function _claimRewardToBeDistributed(uint _records) internal { uint lengthVote = cd.getVoteAddressCALength(msg.sender); uint voteid; uint lastIndex; (lastIndex, ) = cd.getRewardDistributedIndex(msg.sender); uint total = 0; uint tokenForVoteId = 0; bool lastClaimedCheck; uint _days = td.lockCADays(); bool claimed; uint counter = 0; uint claimId; uint perc; uint i; uint lastClaimed = lengthVote; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressCA(msg.sender, i); (tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (perc > 0 && !claimed) { counter++; cd.setRewardClaimed(voteid, true); } else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) { (perc, , ) = cd.getClaimRewardDetail(claimId); if (perc == 0) { counter++; } cd.setRewardClaimed(voteid, true); } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexCA(msg.sender, i); } else { cd.setRewardDistributedIndexCA(msg.sender, lastClaimed); } lengthVote = cd.getVoteAddressMemberLength(msg.sender); lastClaimed = lengthVote; _days = _days.mul(counter); if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) { tc.reduceLock(msg.sender, "CLA", _days); } (, lastIndex) = cd.getRewardDistributedIndex(msg.sender); lastClaimed = lengthVote; counter = 0; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressMember(msg.sender, i); (tokenForVoteId, lastClaimedCheck, , ) = getRewardToBeGiven(0, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (claimed == false && cd.getFinalVerdict(claimId) != 0) { cd.setRewardClaimed(voteid, true); counter++; } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (total > 0) { require(tk.transfer(msg.sender, total)); } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexMV(msg.sender, i); } else { cd.setRewardDistributedIndexMV(msg.sender, lastClaimed); } } /** * @dev Function used to claim the commission earned by the staker. */ function _claimStakeCommission(uint _records, address _user) external onlyInternal { uint total=0; uint len = td.getStakerStakedContractLength(_user); uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user); uint commissionEarned; uint commissionRedeemed; uint maxCommission; uint lastCommisionRedeemed = len; uint counter; uint i; for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) { commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i); commissionEarned = td.getStakerEarnedStakeCommission(_user, i); maxCommission = td.getStakerInitialStakedAmountOnContract( _user, i).mul(td.stakerMaxCommissionPer()).div(100); if (lastCommisionRedeemed == len && maxCommission != commissionEarned) lastCommisionRedeemed = i; td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed)); total = total.add(commissionEarned.sub(commissionRedeemed)); counter++; } if (lastCommisionRedeemed == len) { td.setLastCompletedStakeCommissionIndex(_user, i); } else { td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed); } if (total > 0) require(tk.transfer(_user, total)); //solhint-disable-line } } // File: nexusmutual-contracts/contracts/MemberRoles.sol /* Copyright (C) 2017 GovBlocks.io 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/ */ pragma solidity 0.5.7; contract MemberRoles is IMemberRoles, Governed, Iupgradable { TokenController public dAppToken; TokenData internal td; QuotationData internal qd; ClaimsReward internal cr; Governance internal gv; TokenFunctions internal tf; NXMToken public tk; struct MemberRoleDetails { uint memberCounter; mapping(address => bool) memberActive; address[] memberAddress; address authorized; } enum Role {UnAssigned, AdvisoryBoard, Member, Owner} event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp); MemberRoleDetails[] internal memberRoleData; bool internal constructorCheck; uint public maxABCount; bool public launched; uint public launchedOn; modifier checkRoleAuthority(uint _memberRoleId) { if (memberRoleData[_memberRoleId].authorized != address(0)) require(msg.sender == memberRoleData[_memberRoleId].authorized); else require(isAuthorizedToGovern(msg.sender), "Not Authorized"); _; } /** * @dev to swap advisory board member * @param _newABAddress is address of new AB member * @param _removeAB is advisory board member to be removed */ function swapABMember ( address _newABAddress, address _removeAB ) external checkRoleAuthority(uint(Role.AdvisoryBoard)) { _updateRole(_newABAddress, uint(Role.AdvisoryBoard), true); _updateRole(_removeAB, uint(Role.AdvisoryBoard), false); } /** * @dev to swap the owner address * @param _newOwnerAddress is the new owner address */ function swapOwner ( address _newOwnerAddress ) external { require(msg.sender == address(ms)); _updateRole(ms.owner(), uint(Role.Owner), false); _updateRole(_newOwnerAddress, uint(Role.Owner), true); } /** * @dev is used to add initital advisory board members * @param abArray is the list of initial advisory board members */ function addInitialABMembers(address[] calldata abArray) external onlyOwner { //Ensure that NXMaster has initialized. require(ms.masterInitialized()); require(maxABCount >= SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length) ); //AB count can't exceed maxABCount for (uint i = 0; i < abArray.length; i++) { require(checkRole(abArray[i], uint(MemberRoles.Role.Member))); _updateRole(abArray[i], uint(Role.AdvisoryBoard), true); } } /** * @dev to change max number of AB members allowed * @param _val is the new value to be set */ function changeMaxABCount(uint _val) external onlyInternal { maxABCount = _val; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { td = TokenData(ms.getLatestAddress("TD")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); tf = TokenFunctions(ms.getLatestAddress("TF")); tk = NXMToken(ms.tokenAddress()); dAppToken = TokenController(ms.getLatestAddress("TC")); } /** * @dev to change the master address * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) require(masterAddress == msg.sender); masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev to initiate the member roles * @param _firstAB is the address of the first AB member * @param memberAuthority is the authority (role) of the member */ function memberRolesInitiate (address _firstAB, address memberAuthority) public { require(!constructorCheck); _addInitialMemberRoles(_firstAB, memberAuthority); constructorCheck = true; } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function addRole( //solhint-disable-line bytes32 _roleName, string memory _roleDescription, address _authorized ) public onlyAuthorizedToGovern { _addRole(_roleName, _roleDescription, _authorized); } /// @dev Assign or Delete a member from specific role. /// @param _memberAddress Address of Member /// @param _roleId RoleId to update /// @param _active active is set to be True if we want to assign this role to member, False otherwise! function updateRole( //solhint-disable-line address _memberAddress, uint _roleId, bool _active ) public checkRoleAuthority(_roleId) { _updateRole(_memberAddress, _roleId, _active); } /** * @dev to add members before launch * @param userArray is list of addresses of members * @param tokens is list of tokens minted for each array element */ function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner { require(!launched); for (uint i=0; i < userArray.length; i++) { require(!ms.isMember(userArray[i])); dAppToken.addToWhitelist(userArray[i]); _updateRole(userArray[i], uint(Role.Member), true); dAppToken.mint(userArray[i], tokens[i]); } launched = true; launchedOn = now; } /** * @dev Called by user to pay joining membership fee */ function payJoiningFee(address _userAddress) public payable { require(_userAddress != address(0)); require(!ms.isPause(), "Emergency Pause Applied"); if (msg.sender == address(ms.getLatestAddress("QT"))) { require(td.walletAddress() != address(0), "No walletAddress present"); dAppToken.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(msg.value); } else { require(!qd.refundEligible(_userAddress)); require(!ms.isMember(_userAddress)); require(msg.value == td.joiningFee()); qd.setRefundEligible(_userAddress, true); } } /** * @dev to perform kyc verdict * @param _userAddress whose kyc is being performed * @param verdict of kyc process */ function kycVerdict(address payable _userAddress, bool verdict) public { require(msg.sender == qd.kycAuthAddress()); require(!ms.isPause()); require(_userAddress != address(0)); require(!ms.isMember(_userAddress)); require(qd.refundEligible(_userAddress)); if (verdict) { qd.setRefundEligible(_userAddress, false); uint fee = td.joiningFee(); dAppToken.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(fee); //solhint-disable-line } else { qd.setRefundEligible(_userAddress, false); _userAddress.transfer(td.joiningFee()); //solhint-disable-line } } /** * @dev Called by existed member if wish to Withdraw membership. */ function withdrawMembership() public { require(!ms.isPause() && ms.isMember(msg.sender)); require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment). require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens"); gv.removeDelegation(msg.sender); dAppToken.burnFrom(msg.sender, tk.balanceOf(msg.sender)); _updateRole(msg.sender, uint(Role.Member), false); dAppToken.removeFromWhitelist(msg.sender); // need clarification on whitelist } /** * @dev Called by existed member if wish to switch membership to other address. * @param _add address of user to forward membership. */ function switchMembership(address _add) external { require(!ms.isPause() && ms.isMember(msg.sender) && !ms.isMember(_add)); require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment). require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens"); gv.removeDelegation(msg.sender); dAppToken.addToWhitelist(_add); _updateRole(_add, uint(Role.Member), true); tk.transferFrom(msg.sender, _add, tk.balanceOf(msg.sender)); _updateRole(msg.sender, uint(Role.Member), false); dAppToken.removeFromWhitelist(msg.sender); emit switchedMembership(msg.sender, _add, now); } /// @dev Return number of member roles function totalRoles() public view returns(uint256) { //solhint-disable-line return memberRoleData.length; } /// @dev Change Member Address who holds the authority to Add/Delete any member from specific role. /// @param _roleId roleId to update its Authorized Address /// @param _newAuthorized New authorized address against role id function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) { //solhint-disable-line memberRoleData[_roleId].authorized = _newAuthorized; } /// @dev Gets the member addresses assigned by a specific role /// @param _memberRoleId Member role id /// @return roleId Role id /// @return allMemberAddress Member addresses of specified role id function members(uint _memberRoleId) public view returns(uint, address[] memory memberArray) { //solhint-disable-line uint length = memberRoleData[_memberRoleId].memberAddress.length; uint i; uint j = 0; memberArray = new address[](memberRoleData[_memberRoleId].memberCounter); for (i = 0; i < length; i++) { address member = memberRoleData[_memberRoleId].memberAddress[i]; if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) { //solhint-disable-line memberArray[j] = member; j++; } } return (_memberRoleId, memberArray); } /// @dev Gets all members' length /// @param _memberRoleId Member role id /// @return memberRoleData[_memberRoleId].memberCounter Member length function numberOfMembers(uint _memberRoleId) public view returns(uint) { //solhint-disable-line return memberRoleData[_memberRoleId].memberCounter; } /// @dev Return member address who holds the right to add/remove any member from specific role. function authorized(uint _memberRoleId) public view returns(address) { //solhint-disable-line return memberRoleData[_memberRoleId].authorized; } /// @dev Get All role ids array that has been assigned to a member so far. function roles(address _memberAddress) public view returns(uint[] memory) { //solhint-disable-line uint length = memberRoleData.length; uint[] memory assignedRoles = new uint[](length); uint counter = 0; for (uint i = 1; i < length; i++) { if (memberRoleData[i].memberActive[_memberAddress]) { assignedRoles[counter] = i; counter++; } } return assignedRoles; } /// @dev Returns true if the given role id is assigned to a member. /// @param _memberAddress Address of member /// @param _roleId Checks member's authenticity with the roleId. /// i.e. Returns true if this roleId is assigned to member function checkRole(address _memberAddress, uint _roleId) public view returns(bool) { //solhint-disable-line if (_roleId == uint(Role.UnAssigned)) return true; else if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line return true; else return false; } /// @dev Return total number of members assigned against each role id. /// @return totalMembers Total members in particular role id function getMemberLengthForAllRoles() public view returns(uint[] memory totalMembers) { //solhint-disable-line totalMembers = new uint[](memberRoleData.length); for (uint i = 0; i < memberRoleData.length; i++) { totalMembers[i] = numberOfMembers(i); } } /** * @dev to update the member roles * @param _memberAddress in concern * @param _roleId the id of role * @param _active if active is true, add the member, else remove it */ function _updateRole(address _memberAddress, uint _roleId, bool _active) internal { // require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically"); if (_active) { require(!memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1); memberRoleData[_roleId].memberActive[_memberAddress] = true; memberRoleData[_roleId].memberAddress.push(_memberAddress); } else { require(memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1); delete memberRoleData[_roleId].memberActive[_memberAddress]; } } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function _addRole( bytes32 _roleName, string memory _roleDescription, address _authorized ) internal { emit MemberRole(memberRoleData.length, _roleName, _roleDescription); memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized)); } /** * @dev to check if member is in the given member array * @param _memberAddress in concern * @param memberArray in concern * @return boolean to represent the presence */ function _checkMemberInArray( address _memberAddress, address[] memory memberArray ) internal pure returns(bool memberExists) { uint i; for (i = 0; i < memberArray.length; i++) { if (memberArray[i] == _memberAddress) { memberExists = true; break; } } } /** * @dev to add initial member roles * @param _firstAB is the member address to be added * @param memberAuthority is the member authority(role) to be added for */ function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal { maxABCount = 5; _addRole("Unassigned", "Unassigned", address(0)); _addRole( "Advisory Board", "Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line address(0) ); _addRole( "Member", "Represents all users of Mutual.", //solhint-disable-line memberAuthority ); _addRole( "Owner", "Represents Owner of Mutual.", //solhint-disable-line address(0) ); // _updateRole(_firstAB, uint(Role.AdvisoryBoard), true); _updateRole(_firstAB, uint(Role.Owner), true); // _updateRole(_firstAB, uint(Role.Member), true); launchedOn = 0; } function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) { address memberAddress = memberRoleData[_memberRoleId].memberAddress[index]; return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]); } function membersLength(uint _memberRoleId) external view returns (uint) { return memberRoleData[_memberRoleId].memberAddress.length; } } // File: nexusmutual-contracts/contracts/ProposalCategory.sol /* Copyright (C) 2017 GovBlocks.io 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/ */ pragma solidity 0.5.7; contract ProposalCategory is Governed, IProposalCategory, Iupgradable { bool public constructorCheck; MemberRoles internal mr; struct CategoryStruct { uint memberRoleToVote; uint majorityVotePerc; uint quorumPerc; uint[] allowedToCreateProposal; uint closingTime; uint minStake; } struct CategoryAction { uint defaultIncentive; address contractAddress; bytes2 contractName; } CategoryStruct[] internal allCategory; mapping (uint => CategoryAction) internal categoryActionData; mapping (uint => uint) public categoryABReq; mapping (uint => uint) public isSpecialResolution; mapping (uint => bytes) public categoryActionHashes; bool public categoryActionHashUpdated; /** * @dev Restricts calls to deprecated functions */ modifier deprecated() { revert("Function deprecated"); _; } /** * @dev Adds new category (Discontinued, moved functionality to newCategory) * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external deprecated { } /** * @dev Initiates Default settings for Proposal Category contract (Adding default categories) */ function proposalCategoryInitiate() external deprecated { //solhint-disable-line } /** * @dev Initiates Default action function hashes for existing categories * To be called after the contract has been upgraded by governance */ function updateCategoryActionHashes() external onlyOwner { require(!categoryActionHashUpdated, "Category action hashes already updated"); categoryActionHashUpdated = true; categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)"); categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)"); categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)"); categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()"); categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)"); categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)"); categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)"); categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)"); categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)");//solhint-disable-line categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)"); categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)"); categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)"); categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)"); categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)"); categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)"); categoryActionHashes[29] = abi.encodeWithSignature("upgradeContract(bytes2,address)"); categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)"); categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)"); categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)");//solhint-disable-line categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()"); } /** * @dev Gets Total number of categories added till now */ function totalCategories() external view returns(uint) { return allCategory.length; } /** * @dev Gets category details */ function category(uint _categoryId) external view returns(uint, uint, uint, uint, uint[] memory, uint, uint) { return( _categoryId, allCategory[_categoryId].memberRoleToVote, allCategory[_categoryId].majorityVotePerc, allCategory[_categoryId].quorumPerc, allCategory[_categoryId].allowedToCreateProposal, allCategory[_categoryId].closingTime, allCategory[_categoryId].minStake ); } /** * @dev Gets category ab required and isSpecialResolution * @return the category id * @return if AB voting is required * @return is category a special resolution */ function categoryExtendedData(uint _categoryId) external view returns(uint, uint, uint) { return( _categoryId, categoryABReq[_categoryId], isSpecialResolution[_categoryId] ); } /** * @dev Gets the category acion details * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive */ function categoryAction(uint _categoryId) external view returns(uint, address, bytes2, uint) { return( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive ); } /** * @dev Gets the category acion details of a category id * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive * @return action function hash */ function categoryActionDetails(uint _categoryId) external view returns(uint, address, bytes2, uint, bytes memory) { return( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive, categoryActionHashes[_categoryId] ); } /** * @dev Updates dependant contract addresses */ function changeDependentContractAddress() public { mr = MemberRoles(ms.getLatestAddress("MR")); } /** * @dev Adds new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function newCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } _addCategory( _name, _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _actionHash, _contractAddress, _contractName, _incentives ); if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash); } } /** * @dev Changes the master address and update it's instance * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) require(masterAddress == msg.sender); masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev Updates category details (Discontinued, moved functionality to editCategory) * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public deprecated { } /** * @dev Updates category details * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function editCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } delete categoryActionHashes[_categoryId]; if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash); } allCategory[_categoryId].memberRoleToVote = _memberRoleToVote; allCategory[_categoryId].majorityVotePerc = _majorityVotePerc; allCategory[_categoryId].closingTime = _closingTime; allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal; allCategory[_categoryId].minStake = _incentives[0]; allCategory[_categoryId].quorumPerc = _quorumPerc; categoryActionData[_categoryId].defaultIncentive = _incentives[1]; categoryActionData[_categoryId].contractName = _contractName; categoryActionData[_categoryId].contractAddress = _contractAddress; categoryABReq[_categoryId] = _incentives[2]; isSpecialResolution[_categoryId] = _incentives[3]; emit Category(_categoryId, _name, _actionHash); } /** * @dev Internal call to add new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function _addCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) internal { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); allCategory.push( CategoryStruct( _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _incentives[0] ) ); uint categoryId = allCategory.length - 1; categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName); categoryABReq[categoryId] = _incentives[2]; isSpecialResolution[categoryId] = _incentives[3]; emit Category(categoryId, _name, _actionHash); } /** * @dev Internal call to check if given roles are valid or not */ function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal) internal view returns(uint) { uint totalRoles = mr.totalRoles(); if (_memberRoleToVote >= totalRoles) { return 0; } for (uint i = 0; i < _allowedToCreateProposal.length; i++) { if (_allowedToCreateProposal[i] >= totalRoles) { return 0; } } return 1; } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IGovernance.sol /* Copyright (C) 2017 GovBlocks.io 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/ */ pragma solidity 0.5.7; contract IGovernance { event Proposal( address indexed proposalOwner, uint256 indexed proposalId, uint256 dateAdd, string proposalTitle, string proposalSD, string proposalDescHash ); event Solution( uint256 indexed proposalId, address indexed solutionOwner, uint256 indexed solutionId, string solutionDescHash, uint256 dateAdd ); event Vote( address indexed from, uint256 indexed proposalId, uint256 indexed voteId, uint256 dateAdd, uint256 solutionChosen ); event RewardClaimed( address indexed member, uint gbtReward ); /// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal. event VoteCast (uint256 proposalId); /// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can /// call any offchain actions event ProposalAccepted (uint256 proposalId); /// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time. event CloseProposalOnTime ( uint256 indexed proposalId, uint256 time ); /// @dev ActionSuccess event is called whenever an onchain action is executed. event ActionSuccess ( uint256 proposalId ); /// @dev Creates a new proposal /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external; /// @dev Edits the details of an existing proposal and creates new version /// @param _proposalId Proposal id that details needs to be updated /// @param _proposalDescHash Proposal description hash having long and short description of proposal. function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external; /// @dev Categorizes proposal to proceed further. Categories shows the proposal objective. function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentives ) external; /// @dev Initiates add solution /// @param _solutionHash Solution hash having required data against adding solution function addSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Opens proposal for voting function openProposalForVoting(uint _proposalId) external; /// @dev Submit proposal with solution /// @param _proposalId Proposal id /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Creates a new proposal with solution and votes for the solution /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Casts vote /// @param _proposalId Proposal id /// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution function submitVote(uint _proposalId, uint _solutionChosen) external; function closeProposal(uint _proposalId) external; function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward); function proposal(uint _proposalId) external view returns( uint proposalId, uint category, uint status, uint finalVerdict, uint totalReward ); function canCloseProposal(uint _proposalId) public view returns(uint closeValue); function pauseProposal(uint _proposalId) public; function resumeProposal(uint _proposalId) public; function allowedToCatgorize() public view returns(uint roleId); } // File: nexusmutual-contracts/contracts/Governance.sol // /* Copyright (C) 2017 GovBlocks.io // 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/ */ pragma solidity 0.5.7; contract Governance is IGovernance, Iupgradable { using SafeMath for uint; enum ProposalStatus { Draft, AwaitingSolution, VotingStarted, Accepted, Rejected, Majority_Not_Reached_But_Accepted, Denied } struct ProposalData { uint propStatus; uint finalVerdict; uint category; uint commonIncentive; uint dateUpd; address owner; } struct ProposalVote { address voter; uint proposalId; uint dateAdd; } struct VoteTally { mapping(uint=>uint) memberVoteValue; mapping(uint=>uint) abVoteValue; uint voters; } struct DelegateVote { address follower; address leader; uint lastUpd; } ProposalVote[] internal allVotes; DelegateVote[] public allDelegation; mapping(uint => ProposalData) internal allProposalData; mapping(uint => bytes[]) internal allProposalSolutions; mapping(address => uint[]) internal allVotesByMember; mapping(uint => mapping(address => bool)) public rewardClaimed; mapping (address => mapping(uint => uint)) public memberProposalVote; mapping (address => uint) public followerDelegation; mapping (address => uint) internal followerCount; mapping (address => uint[]) internal leaderDelegation; mapping (uint => VoteTally) public proposalVoteTally; mapping (address => bool) public isOpenForDelegation; mapping (address => uint) public lastRewardClaimed; bool internal constructorCheck; uint public tokenHoldingTime; uint internal roleIdAllowedToCatgorize; uint internal maxVoteWeigthPer; uint internal specialResolutionMajPerc; uint internal maxFollowers; uint internal totalProposals; uint internal maxDraftTime; MemberRoles internal memberRole; ProposalCategory internal proposalCategory; TokenController internal tokenInstance; mapping(uint => uint) public proposalActionStatus; mapping(uint => uint) internal proposalExecutionTime; mapping(uint => mapping(address => bool)) public proposalRejectedByAB; mapping(uint => uint) internal actionRejectedCount; bool internal actionParamsInitialised; uint internal actionWaitingTime; uint constant internal AB_MAJ_TO_REJECT_ACTION = 3; enum ActionStatus { Pending, Accepted, Rejected, Executed, NoAction } /** * @dev Called whenever an action execution is failed. */ event ActionFailed ( uint256 proposalId ); /** * @dev Called whenever an AB member rejects the action execution. */ event ActionRejected ( uint256 indexed proposalId, address rejectedBy ); /** * @dev Checks if msg.sender is proposal owner */ modifier onlyProposalOwner(uint _proposalId) { require(msg.sender == allProposalData[_proposalId].owner, "Not allowed"); _; } /** * @dev Checks if proposal is opened for voting */ modifier voteNotStarted(uint _proposalId) { require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)); _; } /** * @dev Checks if msg.sender is allowed to create proposal under given category */ modifier isAllowed(uint _categoryId) { require(allowedToCreateProposal(_categoryId), "Not allowed"); _; } /** * @dev Checks if msg.sender is allowed categorize proposal under given category */ modifier isAllowedToCategorize() { require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed"); _; } /** * @dev Checks if msg.sender had any pending rewards to be claimed */ modifier checkPendingRewards { require(getPendingReward(msg.sender) == 0, "Claim reward"); _; } /** * @dev Event emitted whenever a proposal is categorized */ event ProposalCategorized( uint indexed proposalId, address indexed categorizedBy, uint categoryId ); /** * @dev Removes delegation of an address. * @param _add address to undelegate. */ function removeDelegation(address _add) external onlyInternal { _unDelegate(_add); } /** * @dev Creates a new proposal * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective */ function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external isAllowed(_categoryId) { require(ms.isMember(msg.sender), "Not Member"); _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); } /** * @dev Edits the details of an existing proposal * @param _proposalId Proposal id that details needs to be updated * @param _proposalDescHash Proposal description hash having long and short description of proposal. */ function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external onlyProposalOwner(_proposalId) { require( allProposalSolutions[_proposalId].length < 2, "Not allowed" ); allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft); allProposalData[_proposalId].category = 0; allProposalData[_proposalId].commonIncentive = 0; emit Proposal( allProposalData[_proposalId].owner, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); } /** * @dev Categorizes proposal to proceed further. Categories shows the proposal objective. */ function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) external voteNotStarted(_proposalId) isAllowedToCategorize { _categorizeProposal(_proposalId, _categoryId, _incentive); } /** * @dev Initiates add solution * To implement the governance interface */ function addSolution(uint, string calldata, bytes calldata) external { } /** * @dev Opens proposal for voting * To implement the governance interface */ function openProposalForVoting(uint) external { } /** * @dev Submit proposal with solution * @param _proposalId Proposal id * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external onlyProposalOwner(_proposalId) { require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution)); _proposalSubmission(_proposalId, _solutionHash, _action); } /** * @dev Creates a new proposal with solution * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external isAllowed(_categoryId) { uint proposalId = totalProposals; _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); require(_categoryId > 0); _proposalSubmission( proposalId, _solutionHash, _action ); } /** * @dev Submit a vote on the proposal. * @param _proposalId to vote upon. * @param _solutionChosen is the chosen vote. */ function submitVote(uint _proposalId, uint _solutionChosen) external { require(allProposalData[_proposalId].propStatus == uint(Governance.ProposalStatus.VotingStarted), "Not allowed"); require(_solutionChosen < allProposalSolutions[_proposalId].length); _submitVote(_proposalId, _solutionChosen); } /** * @dev Closes the proposal. * @param _proposalId of proposal to be closed. */ function closeProposal(uint _proposalId) external { uint category = allProposalData[_proposalId].category; uint _memberRole; if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now && allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } else { require(canCloseProposal(_proposalId) == 1); (, _memberRole, , , , , ) = proposalCategory.category(allProposalData[_proposalId].category); if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) { _closeAdvisoryBoardVote(_proposalId, category); } else { _closeMemberVote(_proposalId, category); } } } /** * @dev Claims reward for member. * @param _memberAddress to claim reward of. * @param _maxRecords maximum number of records to claim reward for. _proposals list of proposals of which reward will be claimed. * @return amount of pending reward. */ function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward) { uint voteId; address leader; uint lastUpd; require(msg.sender == ms.getLatestAddress("CR")); uint delegationId = followerDelegation[_memberAddress]; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; uint totalVotes = allVotesByMember[leader].length; uint lastClaimed = totalVotes; uint j; uint i; for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) { voteId = allVotesByMember[leader][i]; proposalId = allVotes[voteId].proposalId; if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) { if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { if (!rewardClaimed[voteId][_memberAddress]) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); rewardClaimed[voteId][_memberAddress] = true; j++; } } else { if (lastClaimed == totalVotes) { lastClaimed = i; } } } } if (lastClaimed == totalVotes) { lastRewardClaimed[_memberAddress] = i; } else { lastRewardClaimed[_memberAddress] = lastClaimed; } if (j > 0) { emit RewardClaimed( _memberAddress, pendingDAppReward ); } } /** * @dev Sets delegation acceptance status of individual user * @param _status delegation acceptance status */ function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards { isOpenForDelegation[msg.sender] = _status; } /** * @dev Delegates vote to an address. * @param _add is the address to delegate vote to. */ function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards { require(ms.masterInitialized()); require(allDelegation[followerDelegation[_add]].leader == address(0)); if (followerDelegation[msg.sender] > 0) { require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now); } require(!alreadyDelegated(msg.sender)); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner))); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard))); require(followerCount[_add] < maxFollowers); if (allVotesByMember[msg.sender].length > 0) { require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime) < now); } require(ms.isMember(_add)); require(isOpenForDelegation[_add]); allDelegation.push(DelegateVote(msg.sender, _add, now)); followerDelegation[msg.sender] = allDelegation.length - 1; leaderDelegation[_add].push(allDelegation.length - 1); followerCount[_add]++; lastRewardClaimed[msg.sender] = allVotesByMember[_add].length; } /** * @dev Undelegates the sender */ function unDelegate() external isMemberAndcheckPause checkPendingRewards { _unDelegate(msg.sender); } /** * @dev Triggers action of accepted proposal after waiting time is finished */ function triggerAction(uint _proposalId) external { require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger"); _triggerAction(_proposalId, allProposalData[_proposalId].category); } /** * @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious */ function rejectAction(uint _proposalId) external { require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now); require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted)); require(!proposalRejectedByAB[_proposalId][msg.sender]); require( keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category)) != keccak256(abi.encodeWithSignature("swapABMember(address,address)")) ); proposalRejectedByAB[_proposalId][msg.sender] = true; actionRejectedCount[_proposalId]++; emit ActionRejected(_proposalId, msg.sender); if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) { proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected); } } /** * @dev Sets intial actionWaitingTime value * To be called after governance implementation has been updated */ function setInitialActionParameters() external onlyOwner { require(!actionParamsInitialised); actionParamsInitialised = true; actionWaitingTime = 24 * 1 hours; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "GOVHOLD") { val = tokenHoldingTime / (1 days); } else if (code == "MAXFOL") { val = maxFollowers; } else if (code == "MAXDRFT") { val = maxDraftTime / (1 days); } else if (code == "EPTIME") { val = ms.pauseTime() / (1 days); } else if (code == "ACWT") { val = actionWaitingTime / (1 hours); } } /** * @dev Gets all details of a propsal * @param _proposalId whose details we want * @return proposalId * @return category * @return status * @return finalVerdict * @return totalReward */ function proposal(uint _proposalId) external view returns( uint proposalId, uint category, uint status, uint finalVerdict, uint totalRewar ) { return( _proposalId, allProposalData[_proposalId].category, allProposalData[_proposalId].propStatus, allProposalData[_proposalId].finalVerdict, allProposalData[_proposalId].commonIncentive ); } /** * @dev Gets some details of a propsal * @param _proposalId whose details we want * @return proposalId * @return number of all proposal solutions * @return amount of votes */ function proposalDetails(uint _proposalId) external view returns(uint, uint, uint) { return( _proposalId, allProposalSolutions[_proposalId].length, proposalVoteTally[_proposalId].voters ); } /** * @dev Gets solution action on a proposal * @param _proposalId whose details we want * @param _solution whose details we want * @return action of a solution on a proposal */ function getSolutionAction(uint _proposalId, uint _solution) external view returns(uint, bytes memory) { return ( _solution, allProposalSolutions[_proposalId][_solution] ); } /** * @dev Gets length of propsal * @return length of propsal */ function getProposalLength() external view returns(uint) { return totalProposals; } /** * @dev Get followers of an address * @return get followers of an address */ function getFollowers(address _add) external view returns(uint[] memory) { return leaderDelegation[_add]; } /** * @dev Gets pending rewards of a member * @param _memberAddress in concern * @return amount of pending reward */ function getPendingReward(address _memberAddress) public view returns(uint pendingDAppReward) { uint delegationId = followerDelegation[_memberAddress]; address leader; uint lastUpd; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) { if (allVotes[allVotesByMember[leader][i]].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) { if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) { proposalId = allVotes[allVotesByMember[leader][i]].proposalId; if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); } } } } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "GOVHOLD") { tokenHoldingTime = val * 1 days; } else if (code == "MAXFOL") { maxFollowers = val; } else if (code == "MAXDRFT") { maxDraftTime = val * 1 days; } else if (code == "EPTIME") { ms.updatePauseTime(val * 1 days); } else if (code == "ACWT") { actionWaitingTime = val * 1 hours; } else { revert("Invalid code"); } } /** * @dev Updates all dependency addresses to latest ones from Master */ function changeDependentContractAddress() public { tokenInstance = TokenController(ms.dAppLocker()); memberRole = MemberRoles(ms.getLatestAddress("MR")); proposalCategory = ProposalCategory(ms.getLatestAddress("PC")); } /** * @dev Checks if msg.sender is allowed to create a proposal under given category */ function allowedToCreateProposal(uint category) public view returns(bool check) { if (category == 0) return true; uint[] memory mrAllowed; (, , , , mrAllowed, , ) = proposalCategory.category(category); for (uint i = 0; i < mrAllowed.length; i++) { if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i])) return true; } } /** * @dev Checks if an address is already delegated * @param _add in concern * @return bool value if the address is delegated or not */ function alreadyDelegated(address _add) public view returns(bool delegated) { for (uint i=0; i < leaderDelegation[_add].length; i++) { if (allDelegation[leaderDelegation[_add][i]].leader == _add) { return true; } } } /** * @dev Pauses a proposal * To implement govblocks interface */ function pauseProposal(uint) public { } /** * @dev Resumes a proposal * To implement govblocks interface */ function resumeProposal(uint) public { } /** * @dev Checks If the proposal voting time is up and it's ready to close * i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise! * @param _proposalId Proposal id to which closing value is being checked */ function canCloseProposal(uint _proposalId) public view returns(uint) { uint dateUpdate; uint pStatus; uint _closingTime; uint _roleId; uint majority; pStatus = allProposalData[_proposalId].propStatus; dateUpdate = allProposalData[_proposalId].dateUpd; (, _roleId, majority, , , _closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category); if ( pStatus == uint(ProposalStatus.VotingStarted) ) { uint numberOfMembers = memberRole.numberOfMembers(_roleId); if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers || dateUpdate.add(_closingTime) <= now) { return 1; } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters || dateUpdate.add(_closingTime) <= now) return 1; } } else if (pStatus > uint(ProposalStatus.VotingStarted)) { return 2; } else { return 0; } } /** * @dev Gets Id of member role allowed to categorize the proposal * @return roleId allowed to categorize the proposal */ function allowedToCatgorize() public view returns(uint roleId) { return roleIdAllowedToCatgorize; } /** * @dev Gets vote tally data * @param _proposalId in concern * @param _solution of a proposal id * @return member vote value * @return advisory board vote value * @return amount of votes */ function voteTallyData(uint _proposalId, uint _solution) public view returns(uint, uint, uint) { return (proposalVoteTally[_proposalId].memberVoteValue[_solution], proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters); } /** * @dev Internal call to create proposal * @param _proposalTitle of proposal * @param _proposalSD is short description of proposal * @param _proposalDescHash IPFS hash value of propsal * @param _categoryId of proposal */ function _createProposal( string memory _proposalTitle, string memory _proposalSD, string memory _proposalDescHash, uint _categoryId ) internal { require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0); uint _proposalId = totalProposals; allProposalData[_proposalId].owner = msg.sender; allProposalData[_proposalId].dateUpd = now; allProposalSolutions[_proposalId].push(""); totalProposals++; emit Proposal( msg.sender, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); if (_categoryId > 0) _categorizeProposal(_proposalId, _categoryId, 0); } /** * @dev Internal call to categorize a proposal * @param _proposalId of proposal * @param _categoryId of proposal * @param _incentive is commonIncentive */ function _categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) internal { require( _categoryId > 0 && _categoryId < proposalCategory.totalCategories(), "Invalid category" ); allProposalData[_proposalId].category = _categoryId; allProposalData[_proposalId].commonIncentive = _incentive; allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution); emit ProposalCategorized(_proposalId, msg.sender, _categoryId); } /** * @dev Internal call to add solution to a proposal * @param _proposalId in concern * @param _action on that solution * @param _solutionHash string value */ function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash) internal { allProposalSolutions[_proposalId].push(_action); emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now); } /** * @dev Internal call to add solution and open proposal for voting */ function _proposalSubmission( uint _proposalId, string memory _solutionHash, bytes memory _action ) internal { uint _categoryId = allProposalData[_proposalId].category; if (proposalCategory.categoryActionHashes(_categoryId).length == 0) { require(keccak256(_action) == keccak256("")); proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } _addSolution( _proposalId, _action, _solutionHash ); _updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted)); (, , , , , uint closingTime, ) = proposalCategory.category(_categoryId); emit CloseProposalOnTime(_proposalId, closingTime.add(now)); } /** * @dev Internal call to submit vote * @param _proposalId of proposal in concern * @param _solution for that proposal */ function _submitVote(uint _proposalId, uint _solution) internal { uint delegationId = followerDelegation[msg.sender]; uint mrSequence; uint majority; uint closingTime; (, mrSequence, majority, , , closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category); require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed"); require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed"); require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) && _checkLastUpd(allDelegation[delegationId].lastUpd))); require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized"); uint totalVotes = allVotes.length; allVotesByMember[msg.sender].push(totalVotes); memberProposalVote[msg.sender][_proposalId] = totalVotes; allVotes.push(ProposalVote(msg.sender, _proposalId, now)); emit Vote(msg.sender, _proposalId, totalVotes, now, _solution); if (mrSequence == uint(MemberRoles.Role.Owner)) { if (_solution == 1) _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner); else _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } else { uint numberOfMembers = memberRole.numberOfMembers(mrSequence); _setVoteTally(_proposalId, _solution, mrSequence); if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) { emit VoteCast(_proposalId); } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters) emit VoteCast(_proposalId); } } } /** * @dev Internal call to set vote tally of a proposal * @param _proposalId of proposal in concern * @param _solution of proposal in concern * @param mrSequence number of members for a role */ function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal { uint categoryABReq; uint isSpecialResolution; (, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category); if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) || mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { proposalVoteTally[_proposalId].abVoteValue[_solution]++; } tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime); if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) { uint voteWeight; uint voters = 1; uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender); uint totalSupply = tokenInstance.totalSupply(); if (isSpecialResolution == 1) { voteWeight = tokenBalance.add(10**18); } else { voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18); } DelegateVote memory delegationData; for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) { delegationData = allDelegation[leaderDelegation[msg.sender][i]]; if (delegationData.leader == msg.sender && _checkLastUpd(delegationData.lastUpd)) { if (memberRole.checkRole(delegationData.follower, mrSequence)) { tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower); tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime); voters++; if (isSpecialResolution == 1) { voteWeight = voteWeight.add(tokenBalance.add(10**18)); } else { voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18)); } } } } proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight); proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters; } } /** * @dev Gets minimum of two numbers * @param a one of the two numbers * @param b one of the two numbers * @return minimum number out of the two */ function _minOf(uint a, uint b) internal pure returns(uint res) { res = a; if (res > b) res = b; } /** * @dev Check the time since last update has exceeded token holding time or not * @param _lastUpd is last update time * @return the bool which tells if the time since last update has exceeded token holding time or not */ function _checkLastUpd(uint _lastUpd) internal view returns(bool) { return (now - _lastUpd) > tokenHoldingTime; } /** * @dev Checks if the vote count against any solution passes the threshold value or not. */ function _checkForThreshold(uint _proposalId, uint _category) internal view returns(bool check) { uint categoryQuorumPerc; uint roleAuthorized; (, roleAuthorized, , categoryQuorumPerc, , , ) = proposalCategory.category(_category); check = ((proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1])) .mul(100)) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18) ) ) >= categoryQuorumPerc; } /** * @dev Called when vote majority is reached * @param _proposalId of proposal in concern * @param _status of proposal in concern * @param category of proposal in concern * @param max vote value of proposal in concern */ function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal { allProposalData[_proposalId].finalVerdict = max; _updateProposalStatus(_proposalId, _status); emit ProposalAccepted(_proposalId); if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) { if (role == MemberRoles.Role.AdvisoryBoard) { _triggerAction(_proposalId, category); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); proposalExecutionTime[_proposalId] = actionWaitingTime.add(now); } } } /** * @dev Internal function to trigger action of accepted proposal */ function _triggerAction(uint _proposalId, uint _categoryId) internal { proposalActionStatus[_proposalId] = uint(ActionStatus.Executed); bytes2 contractName; address actionAddress; bytes memory _functionHash; (, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId); if (contractName == "MS") { actionAddress = address(ms); } else if (contractName != "EX") { actionAddress = ms.getLatestAddress(contractName); } (bool actionStatus, ) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1])); if (actionStatus) { emit ActionSuccess(_proposalId); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); emit ActionFailed(_proposalId); } } /** * @dev Internal call to update proposal status * @param _proposalId of proposal in concern * @param _status of proposal to set */ function _updateProposalStatus(uint _proposalId, uint _status) internal { if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) { proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } allProposalData[_proposalId].dateUpd = now; allProposalData[_proposalId].propStatus = _status; } /** * @dev Internal call to undelegate a follower * @param _follower is address of follower to undelegate */ function _unDelegate(address _follower) internal { uint followerId = followerDelegation[_follower]; if (followerId > 0) { followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1); allDelegation[followerId].leader = address(0); allDelegation[followerId].lastUpd = now; lastRewardClaimed[_follower] = allVotesByMember[_follower].length; } } /** * @dev Internal call to close member voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeMemberVote(uint _proposalId, uint category) internal { uint isSpecialResolution; uint abMaj; (, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category); if (isSpecialResolution == 1) { uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10**18) )); if (acceptedVotePerc >= specialResolutionMajPerc) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } else { if (_checkForThreshold(_proposalId, category)) { uint majorityVote; (, , majorityVote, , , , ) = proposalCategory.category(category); if ( ((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)) .div(proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1]) )) >= majorityVote ) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } } else { if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } } if (proposalVoteTally[_proposalId].voters > 0) { tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive); } } /** * @dev Internal call to close advisory board voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal { uint _majorityVote; MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard; (, , _majorityVote, , , , ) = proposalCategory.category(category); if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } }
Gets Uint Parameters of a code code whose details we want return string value of the code return associated amount (time or perc or value) to the code/
function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "STLP") { val = stlp; val = stl; val = pm; val = minDays; val = tokensRetained; } }
7,286,895
./partial_match/1/0xC3Be6BffAeab7B297c03383B4254aa3Af2b9a5BA/sources/src/SablierV2Comptroller.sol
@inheritdoc ISablierV2Comptroller Effects: enable the ERC-20 asset for flash loaning. Log the change of the flash asset flag.
function toggleFlashAsset(IERC20 asset) external override onlyAdmin { bool oldFlag = isFlashAsset[asset]; isFlashAsset[asset] = !oldFlag; }
4,175,197
./full_match/3/0xB2d23ce635Ea9D4d741a86bca08B85141f80486a/sources/browser/CryptoWheat.sol
Safely transfers the ownership of a given token ID to another address If the target address is a contract, it must implement `onERC721Received`, which is called upon a safe transfer, and return the magic value `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, the transfer is reverted./ solium-disable-next-line arg-overflow
function safeTransferFrom(address from, address to, uint256 wheatId) whenNotPaused hasRole('accreditedTrader') public { safeTransferFrom(from, to, wheatId, ""); }
8,180,444
pragma solidity 0.7.0; 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)); } } } 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; } } 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); } 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)); } } 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; } } 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); } 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); } } 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; } } 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; } 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library 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)); } } 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; } } 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; } } interface PolicyManagerInterface { function register(address _node, uint16 _period) external; function updateFee(address _node, uint16 _period) external; function escrow() external view returns (address); function setDefaultFeeDelta(address _node, uint16 _period) external; } interface AdjudicatorInterface { function escrow() external view returns (address); } interface WorkLockInterface { function escrow() external view returns (address); } 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) } } } 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 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 _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 _hoursPerPeriod, uint256 _issuanceDecayCoefficient, uint256 _lockDurationCoefficient1, uint256 _lockDurationCoefficient2, uint16 _maximumRewardedPeriods, uint256 _firstPhaseTotalSupply, uint256 _firstPhaseMaxIssuance ) { uint256 localTotalSupply = _token.totalSupply(); require(localTotalSupply > 0 && _issuanceDecayCoefficient != 0 && _hoursPerPeriod != 0 && _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); 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); } /** * @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); } } 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; event Deposited(address indexed staker, uint256 value, uint16 periods); event Locked(address indexed staker, uint256 value, uint16 firstPeriod, uint16 periods); event Divided( address indexed staker, uint256 oldValue, uint16 lastPeriod, uint256 newValue, uint16 periods ); event Merged(address indexed staker, uint256 value1, uint256 value2, uint16 lastPeriod); event Prolonged(address indexed staker, uint256 value, uint16 lastPeriod, uint16 periods); event Withdrawn(address indexed staker, uint256 value); event CommitmentMade(address indexed staker, uint16 indexed period, uint256 value); event Minted(address indexed staker, uint16 indexed period, uint256 value); event Slashed(address indexed staker, uint256 penalty, address indexed investigator, uint256 reward); event ReStakeSet(address indexed staker, bool reStake); event ReStakeLocked(address indexed staker, uint16 lockUntilPeriod); event WorkerBonded(address indexed staker, address indexed worker, uint16 indexed startPeriod); event WorkMeasurementSet(address indexed staker, bool measureWork); event WindDownSet(address indexed staker, bool windDown); event SnapshotSet(address indexed staker, bool snapshotsEnabled); struct SubStakeInfo { uint16 firstPeriod; uint16 lastPeriod; uint16 periods; 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 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; uint16 public immutable minLockedPeriods; uint16 public immutable minWorkerPeriods; uint256 public immutable minAllowableLockedTokens; uint256 public immutable maxAllowableLockedTokens; bool public immutable isTestContract; mapping (address => StakerInfo) public stakerInfo; address[] public stakers; mapping (address => address) public stakerFromWorker; mapping (uint16 => uint256) public lockedPerPeriod; uint128[] public balanceHistory; PolicyManagerInterface public policyManager; AdjudicatorInterface public adjudicator; WorkLockInterface public workLock; /** * @notice Constructor sets address of token contract and coefficients for minting * @param _token Token contract * @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 * @param _isTestContract True if contract is only for tests */ constructor( NuCypherToken _token, uint32 _hoursPerPeriod, uint256 _issuanceDecayCoefficient, uint256 _lockDurationCoefficient1, uint256 _lockDurationCoefficient2, uint16 _maximumRewardedPeriods, uint256 _firstPhaseTotalSupply, uint256 _firstPhaseMaxIssuance, uint16 _minLockedPeriods, uint256 _minAllowableLockedTokens, uint256 _maxAllowableLockedTokens, uint16 _minWorkerPeriods, bool _isTestContract ) Issuer( _token, _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; isTestContract = _isTestContract; } /** * @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); _; } //------------------------Initialization------------------------ /** * @notice Set policy manager address */ function setPolicyManager(PolicyManagerInterface _policyManager) external onlyOwner { // Policy manager can be set only once require(address(policyManager) == address(0)); // This escrow must be the escrow for the new policy manager require(_policyManager.escrow() == address(this)); policyManager = _policyManager; } /** * @notice Set adjudicator address */ function setAdjudicator(AdjudicatorInterface _adjudicator) external onlyOwner { // Adjudicator can be set only once require(address(adjudicator) == address(0)); // This escrow must be the escrow for the new adjudicator require(_adjudicator.escrow() == address(this)); adjudicator = _adjudicator; } /** * @notice Set worklock address */ function setWorkLock(WorkLockInterface _workLock) external onlyOwner { // WorkLock can be set only once require(address(workLock) == address(0) || isTestContract); // This escrow must be the escrow for the new worklock require(_workLock.escrow() == address(this)); workLock = _workLock; } //------------------------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 ) { 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); } /** * @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.periods; 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 _periods Amount of periods that will be added to the current period */ function getLockedTokens(address _staker, uint16 _periods) external view returns (uint256 lockedValue) { StakerInfo storage info = stakerInfo[_staker]; uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod.add16(_periods); 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() + _periods) period * as well as stakers and their locked tokens * @param _periods 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 _periods, uint256 _startIndex, uint256 _maxStakers) external view returns (uint256 allLockedTokens, uint256[2][] memory activeStakers) { require(_periods > 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(_periods); 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 Checks if `reStake` parameter is available for changing * @param _staker Staker */ function isReStakeLocked(address _staker) public view returns (bool) { return getCurrentPeriod() < stakerInfo[_staker].lockReStakeUntilPeriod; } /** * @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 * Only if this parameter is not locked * @param _reStake Value for parameter */ function setReStake(bool _reStake) external { require(!isReStakeLocked(msg.sender)); 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 Lock `reStake` parameter. Only if this parameter is not locked * @param _lockReStakeUntilPeriod Can't change `reStake` value until this period */ function lockReStake(uint16 _lockReStakeUntilPeriod) external { require(!isReStakeLocked(msg.sender) && _lockReStakeUntilPeriod > getCurrentPeriod()); stakerInfo[msg.sender].lockReStakeUntilPeriod = _lockReStakeUntilPeriod; emit ReStakeLocked(msg.sender, _lockReStakeUntilPeriod); } /** * @notice Enable `reStake` and lock this parameter even if parameter is locked * @param _staker Staker address * @param _info Staker structure * @param _lockReStakeUntilPeriod Can't change `reStake` value until this period */ function forceLockReStake( address _staker, StakerInfo storage _info, uint16 _lockReStakeUntilPeriod ) internal { // reset bit when `reStake` is already disabled if (_info.flags.bitSet(RE_STAKE_DISABLED_INDEX) == true) { _info.flags = _info.flags.toggleBit(RE_STAKE_DISABLED_INDEX); emit ReStakeSet(_staker, true); } // lock `reStake` parameter if it's not locked or locked for too short duration if (_lockReStakeUntilPeriod > _info.lockReStakeUntilPeriod) { _info.lockReStakeUntilPeriod = _lockReStakeUntilPeriod; emit ReStakeLocked(_staker, _lockReStakeUntilPeriod); } } /** * @notice Deposit tokens and lock `reStake` parameter from WorkLock contract * @param _staker Staker address * @param _value Amount of tokens to deposit * @param _periods Amount of periods during which tokens will be locked * and number of period after which `reStake` can be changed */ function depositFromWorkLock( address _staker, uint256 _value, uint16 _periods ) external { require(msg.sender == address(workLock)); deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _periods); StakerInfo storage info = stakerInfo[_staker]; uint16 lockReStakeUntilPeriod = getCurrentPeriod().add16(_periods).add16(1); forceLockReStake(_staker, info, lockReStakeUntilPeriod); } /** * @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 onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(WIND_DOWN_INDEX) == _windDown) { return; } info.flags = info.flags.toggleBit(WIND_DOWN_INDEX); uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; emit WindDownSet(msg.sender, _windDown); // duration adjustment if next period is committed 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.periods = 1; continue; } // this sub-stake is no longer affected by winding down parameter if (subStake.lastPeriod != 0 || subStake.periods == 0) { continue; } subStake.periods = _windDown ? subStake.periods - 1 : subStake.periods + 1; if (subStake.periods == 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 Batch deposit. Allowed only initial deposit for each staker * @param _stakers Stakers * @param _numberOfSubStakes Number of sub-stakes which belong to staker in _values and _periods arrays * @param _values Amount of tokens to deposit for each staker * @param _periods Amount of periods during which tokens will be locked for each staker * @param _lockReStakeUntilPeriod Can't change `reStake` value until this period. Zero value will disable locking */ function batchDeposit( address[] calldata _stakers, uint256[] calldata _numberOfSubStakes, uint256[] calldata _values, uint16[] calldata _periods, uint16 _lockReStakeUntilPeriod ) // `onlyOwner` modifier is for prevent malicious using of `forceLockReStake` // remove `onlyOwner` if `forceLockReStake` will be removed external onlyOwner { uint256 subStakesLength = _values.length; require(_stakers.length != 0 && _stakers.length == _numberOfSubStakes.length && subStakesLength >= _stakers.length && _periods.length == subStakesLength); uint16 previousPeriod = getCurrentPeriod() - 1; uint16 nextPeriod = previousPeriod + 2; uint256 sumValue = 0; uint256 j = 0; for (uint256 i = 0; i < _stakers.length; i++) { address staker = _stakers[i]; uint256 numberOfSubStakes = _numberOfSubStakes[i]; uint256 endIndex = j + numberOfSubStakes; require(numberOfSubStakes > 0 && subStakesLength >= endIndex); StakerInfo storage info = stakerInfo[staker]; require(info.subStakes.length == 0); // A staker can't be a worker for another staker require(stakerFromWorker[staker] == address(0)); stakers.push(staker); policyManager.register(staker, previousPeriod); for (; j < endIndex; j++) { uint256 value = _values[j]; uint16 periods = _periods[j]; require(value >= minAllowableLockedTokens && periods >= minLockedPeriods); info.value = info.value.add(value); info.subStakes.push(SubStakeInfo(nextPeriod, 0, periods, uint128(value))); sumValue = sumValue.add(value); emit Deposited(staker, value, periods); emit Locked(staker, value, nextPeriod, periods); } require(info.value <= maxAllowableLockedTokens); info.history.addSnapshot(info.value); if (_lockReStakeUntilPeriod >= nextPeriod) { forceLockReStake(staker, info, _lockReStakeUntilPeriod); } } require(j == subStakesLength); uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); balanceHistory.addSnapshot(lastGlobalBalance + sumValue); token.safeTransferFrom(msg.sender, address(this), sumValue); } /** * @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 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); 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 _periods Amount of periods during which tokens will be locked */ function deposit(address _staker, uint256 _value, uint16 _periods) external { deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _periods); } /** * @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 _periods Amount of periods during which tokens will be locked */ function deposit(address _staker, address _payer, uint256 _index, uint256 _value, uint16 _periods) 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) { stakers.push(_staker); policyManager.register(_staker, getCurrentPeriod() - 1); } token.safeTransferFrom(_payer, address(this), _value); info.value += _value; lock(_staker, _index, _value, _periods); addSnapshot(info, int256(_value)); if (_index >= MAX_SUB_STAKES) { emit Deposited(_staker, _value, _periods); } 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 _periods Amount of periods during which tokens will be locked */ function lockAndCreate(uint256 _value, uint16 _periods) external onlyStaker { lock(msg.sender, MAX_SUB_STAKES, _value, _periods); } /** * @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 _periods Amount of periods during which tokens will be locked */ function lock(address _staker, uint256 _index, uint256 _value, uint16 _periods) internal { if (_index < MAX_SUB_STAKES) { require(_value > 0); } else { require(_value >= minAllowableLockedTokens && _periods >= 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, _periods); } } /** * @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 _periods Amount of periods during which tokens will be locked */ function lockAndCreate( StakerInfo storage _info, uint16 _nextPeriod, address _staker, uint256 _value, uint16 _periods ) internal { uint16 duration = _periods; // 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, _periods); } /** * @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 _periods Duration of the sub stake in periods * @param _lockedValue Amount of locked tokens */ function saveSubStake( StakerInfo storage _info, uint16 _firstPeriod, uint16 _lastPeriod, uint16 _periods, 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.periods = _periods; subStake.lockedValue = uint128(_lockedValue); return; } } require(_info.subStakes.length < MAX_SUB_STAKES); _info.subStakes.push(SubStakeInfo(_firstPeriod, _lastPeriod, _periods, uint128(_lockedValue))); } /** * @notice Divide sub stake into two parts * @param _index Index of the sub stake * @param _newValue New sub stake value * @param _periods Amount of periods for extending sub stake */ function divideStake(uint256 _index, uint256 _newValue, uint16 _periods) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; require(_newValue >= minAllowableLockedTokens && _periods > 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.periods.add16(_periods); saveSubStake(info, subStake.firstPeriod, 0, requestedPeriods, _newValue); emit Divided(msg.sender, oldValue, lastPeriod, _newValue, _periods); emit Locked(msg.sender, _newValue, subStake.firstPeriod, requestedPeriods); } /** * @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) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; // Incorrect parameters require(_periods > 0); SubStakeInfo storage subStake = info.subStakes[_index]; uint16 currentPeriod = getCurrentPeriod(); (uint16 startPeriod, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod); subStake.periods = subStake.periods.add16(_periods); // 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) + _periods >= minLockedPeriods); emit Locked(msg.sender, subStake.lockedValue, lastPeriod + 1, _periods); emit Prolonged(msg.sender, subStake.lockedValue, lastPeriod, _periods); } /** * @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.periods = 0; } else if (subStake1.firstPeriod > subStake2.firstPeriod) { subStake1.lockedValue += subStake2.lockedValue; subStake2.lastPeriod = subStake1.firstPeriod - 1; subStake2.periods = 0; } else { subStake2.lockedValue += subStake1.lockedValue; subStake1.lastPeriod = subStake2.firstPeriod - 1; subStake1.periods = 0; } } /** * @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); uint16 lastCommittedPeriod = getLastCommittedPeriod(staker); mint(staker); uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; // the period has already been committed if (info.nextCommittedPeriod == nextPeriod) { return; } 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.setDefaultFeeDelta(staker, nextPeriod); emit CommitmentMade(staker, nextPeriod, lockedTokens); } /** * @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.periods == 0) { continue; } subStake.periods--; if (subStake.periods == 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; } mint(msg.sender); } /** * @notice Mint tokens for previous periods if staker locked their tokens and made a commitment * @param _staker Staker */ function mint(address _staker) internal { 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; } uint16 startPeriod = getStartPeriod(info, currentPeriod); uint256 reward = 0; bool reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX); if (info.currentCommittedPeriod != 0) { reward = mint(_staker, info, info.currentCommittedPeriod, currentPeriod, startPeriod, reStake); info.currentCommittedPeriod = 0; if (reStake) { lockedPerPeriod[info.nextCommittedPeriod] += reward; } } if (info.nextCommittedPeriod <= previousPeriod) { reward += mint(_staker, info, info.nextCommittedPeriod, currentPeriod, startPeriod, reStake); 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 _staker Staker's address * @param _info Staker structure * @param _mintingPeriod Period for minting calculation * @param _currentPeriod Current period * @param _startPeriod Pre-calculated start period */ function mint( address _staker, 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); } } } policyManager.updateFee(_staker, _mintingPeriod); 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]; 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 periods, uint128 lockedValue) { SubStakeInfo storage info = stakerInfo[_staker].subStakes[_index]; firstPeriod = info.firstPeriod; lastPeriod = info.lastPeriod; periods = info.periods; 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(address(delegateGet(_testTarget, this.policyManager.selector)) == address(policyManager)); require(address(delegateGet(_testTarget, this.adjudicator.selector)) == address(adjudicator)); require(address(delegateGet(_testTarget, this.workLock.selector)) == address(workLock)); 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.lockReStakeUntilPeriod == info.lockReStakeUntilPeriod && 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.periods == subStakeInfo.periods && 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); } }
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)
function mint() external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; uint16 previousPeriod = getCurrentPeriod() - 1; if (info.nextCommittedPeriod <= previousPeriod && info.nextCommittedPeriod != 0) { info.lastCommittedPeriod = info.nextCommittedPeriod; } mint(msg.sender); }
7,397,474
pragma solidity 0.4.19; /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <[email protected]> contract MultiSigWallet { /* * Events */ event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); /* * Constants */ uint constant public MAX_OWNER_COUNT = 50; /* * Storage */ mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } /* * Modifiers */ modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0); _; } /// @dev Fallback function allows to deposit ether. function() payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function MultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i=0; i<_owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != 0); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (txn.destination.call.value(txn.value)(txn.data)) Execution(transactionId); else { ExecutionFailure(transactionId); txn.executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } }
Returns the confirmation status of a transaction. transactionId Transaction ID. return Confirmation status.
function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } }
13,812,551
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "./LoanController.sol"; import "./User.sol"; import "./Exponential.sol"; import "./TScoreController.sol"; import "hardhat/console.sol"; contract Loan { using SafeMath for uint; using Exponential for *; using TScoreController for *; /** @dev Loan related infos * */ address borrowerUser; address borrower; address loanController; bool public isNew = true; // used in TScore calculation // Requested amount for a loan uint public requestedAmount; // Amount to be returned by the borrower (with an interest) uint repaymentsCount; // Loan interest uint public interest; uint interestAmount; // Recommenders interest part of APY uint8 constant recommendersInterestRate = 60; // Increase value for social recommendation tScore after a successful loan uint8 constant successfulLoanScoreIncrease = 5; // Ban delay (in seconds), the user is banned if it's repayment is uint8 constant banDelay = 120; // Installment period uint8 constant installmentPeriod = 240; // The money is sent to the user only when the loan is started bool active = false; uint returnAmount; uint loanCreationDate; uint lastRepaymentDate; ExponentialNoError.Exp repaymentInstallment; uint repaidAmount; uint collateral; /* uint constant loanExpirationInterval = 86400; // 1 DAY */ uint constant loanExpirationInterval = 600; // 2 min uint constant minRecommendValue = 50; uint constant interestBasis = 5; // 5% APY uint public constant previousTScoreWeight = 30; // new TScore is based on 30% of a previous score and 70% on recommender's votes string tokenURI; /** @dev Investors and Recommenders infos * */ uint investorsCount; uint totalInvestedAmount; uint totalRecommendedAmount; mapping(address => bool) public lenders; mapping(address => bool) public recommenders; mapping(address => uint8) public recommendedScore; mapping(address => uint) investedAmounts; mapping(address => uint) recommendedAmounts; address[] recommenderAddr; // Store the lenders count, later needed for revoke vote. uint lendersCount = 0; uint recommendersCount = 0; /** Stages that every credit contract gets trough. * investment - During this state only investments are allowed. * collateral - During this state borrower must pay the remaining collateral. * repayment - During this stage only repayments are allowed. * interestReturns - This stage gives investors opportunity to request their returns. * expired - If the contract does not accumulate the necessary amount on the * balance over the time interval, it expires. * fraud - The borrower was marked as fraud. */ enum State { recommendation, investment, withdrawable, repayment, interestReturns, expired, revoked, fraud } State public state; /** @dev Events * */ event LoanInitialized(address indexed _address, uint indexed timestamp, uint indexed _repaymentInstallment); event LoanStateChanged(State indexed state, uint indexed timestamp); event LoanActiveStateChanged(bool indexed active, uint indexed timestamp); event LogBorrowerWithdrawal(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogBorrowerRepaymentInstallment(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogBorrowerRepaymentFinished(address indexed _address, uint indexed timestamp); event LogBorrowerChangeReturned(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogBorrowerIsFraud(address indexed _address, bool indexed fraudStatus, uint indexed timestamp); event Invested(address indexed _address, uint indexed _amount, uint indexed timestamp); event Recommended(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogLenderWithdrawal(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogRecommenderWithdrawal(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogLenderChangeReturned(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogLenderVoteForRevoking(address indexed _address, uint indexed timestamp); event LogLenderVoteForFraud(address indexed _address, uint indexed timestamp); event ExtraAmountRefunded(address indexed _address, uint indexed _amount, uint indexed timestamp); /** @dev Modifiers * */ // used for a withdraw function modifier isActive() { require(active == true); _; } // crowdfunding process cannot exceed an interval of expiration modifier notExpired() { require(block.timestamp - loanCreationDate < loanExpirationInterval); _; } // used for a withdraw function modifier onlyBorrower() { require(msg.sender == borrower); _; } modifier canAskForInterest() { require(state == State.interestReturns || state == State.fraud); require(investedAmounts[msg.sender] > 0 || recommendedAmounts[msg.sender] > 0); _; } modifier canInvest() { require(state == State.investment); require(block.timestamp - loanCreationDate < loanExpirationInterval); _; } modifier canDestruct() { require(msg.sender == address(this) || msg.sender == loanController); _; } modifier canRecommend() { // can recommend till the borrower's withdraw require(collateral > 0); require(state == State.recommendation); require(block.timestamp - loanCreationDate < loanExpirationInterval); _; } // TODO recheck conditions modifier canRepay() { require(state == State.repayment); _; } modifier canWithdraw() { require(address(this).balance >= requestedAmount*2); require(collateral == 0); require(state == State.withdrawable); _; } modifier isNotFraud() { require(state != State.fraud); _; } constructor ( address _borrowerUser, address _borrower, uint _requestedAmount, uint _repaymentsCount, uint _loanCreationDate, string memory _tokenURI, address _loanController ) public { borrowerUser = _borrowerUser; borrower = _borrower; requestedAmount = _requestedAmount; repaymentsCount = _repaymentsCount; interest = interestBasis*100/User(_borrowerUser).getTScore(); loanCreationDate = _loanCreationDate; tokenURI = _tokenURI; // Calculate the amount to return by the borrower /*returnAmount = ExponentialNoError.mul_ScalarTruncateAddUInt( ExponentialNoError.div_(ExponentialNoError.Exp({ mantissa: interest }), 100), requestedAmount, requestedAmount );*/ interestAmount = ExponentialNoError.mul_(ExponentialNoError.Exp({ mantissa: requestedAmount }), ExponentialNoError.div_(ExponentialNoError.Exp({ mantissa: interest*1e18 }), 100)).mantissa; returnAmount = interestAmount + requestedAmount; // Loan can only start when sufficient funds are invested lastRepaymentDate = 0; collateral = _requestedAmount; // initially the collateral is equal to the requested amount investorsCount = 0; /*uint repaymentInstallment = remainingPayments.div(_repaymentsCount);*/ (, repaymentInstallment) = Exponential.divExp(ExponentialNoError.Exp({mantissa: returnAmount }), ExponentialNoError.Exp({mantissa: _repaymentsCount*1e18})); repaidAmount = 0; active = true; isNew = true; loanController = _loanController; // 1 state of a loan state = State.recommendation; } function getBalance() public view returns (uint256) { return address(this).balance; } function getUserTScore() public view returns ( uint256, uint256, uint256, uint256 ) { User user = User(borrowerUser); return ( user.getActivityScore(), user.getProfileScore(), user.getSocialRecommendationScore(), user.getLoanRiskScore() ); } function getInfosForLender() public view returns (uint256, uint256, string memory, uint256, string memory, uint256, address) { return (interest, requestedAmount, tokenURI, loanCreationDate, getState(), investedAmounts[msg.sender], borrower); } function getInfosForRecommender() public view returns ( uint256, uint256, uint256, string memory, uint256, string memory, uint256, address, uint256 ) { return ( interest, requestedAmount, requestTScore(), tokenURI, collateral, getState(), recommendedAmounts[msg.sender], borrower, loanCreationDate); } function getInfosForBorrower() public view returns ( uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, string memory, uint256, address ) { return ( requestedAmount, interest, repaymentsCount, investorsCount, recommendersCount, requestTScore(), repaymentInstallment.mantissa, // totalInvestedAmount, returnAmount - repaidAmount, tokenURI, loanCreationDate, address(this) ); } /** @dev Trustworthiness score calculation function * Calculates trustworthiness score based on * borrower's attributes */ function requestTScore() public view returns (uint) { return TScoreController.getTScore(borrowerUser); } /** @dev Recommend function. * Provides functionality for person to recommend someone's project, * incentivized by the return of interest. */ function recommend(uint8 score, address recommenderAddress) public canRecommend payable { require(recommenderAddress != borrower, "You can not recommend your own project"); require(score > minRecommendValue && score <= 100); require(!recommenders[recommenderAddress], "You have already recommended"); uint extraMoney = 0; if (msg.value >= collateral) { extraMoney = msg.value.sub(collateral); assert(collateral == msg.value.sub(extraMoney)); // Assert that there is no overflow / underflow assert(extraMoney <= msg.value); if (extraMoney > 0) { // return extra money to the sender payable(recommenderAddress).transfer(extraMoney); emit ExtraAmountRefunded(recommenderAddress, extraMoney, block.timestamp); } collateral = 0; } else { // no overflow because msg.value is always greater than extraMoney collateral -= (msg.value - extraMoney); } uint recommendedAmount = msg.value - extraMoney; totalRecommendedAmount += recommendedAmount; recommenders[recommenderAddress] = true; recommendedAmounts[recommenderAddress] = recommendedAmount; recommendedScore[recommenderAddress] = score; recommenderAddr.push(recommenderAddress); recommendersCount++; // TODO Move logic here ExponentialNoError.Exp[] memory weights; uint8[] memory scores; (weights, scores) = TScoreController.getRecommendersWeightsAndValue(recommendersCount, recommenderAddr, recommenders, recommendedAmounts, totalRecommendedAmount, recommendedScore); TScoreController.updateSocialRecommendationScore(address(this), borrowerUser, 0, 0,weights, scores); isNew = false; emit Recommended(recommenderAddress, recommendedAmount, block.timestamp); // TODO threshold on collateral (50% of collateral recommended at least) if (collateral == 0) state = State.investment; } /** @dev Invest function. * Provides functionality for person to invest in someone's project, * incentivized by the return of interest. */ function lend(address investorAddress) public canInvest payable { require(investorAddress != borrower, "You can not invest in your own project"); uint extraMoney = 0; if (msg.value > requestedAmount) { extraMoney = address(this).balance.sub(requestedAmount); assert(requestedAmount == address(this).balance.sub(extraMoney)); // Assert that there is no overflow / underflow assert(extraMoney <= msg.value); if (extraMoney > 0) { // return extra money to the sender payable(investorAddress).transfer(extraMoney); emit ExtraAmountRefunded(investorAddress, extraMoney, block.timestamp); } //state = State.repayment; // state = State.collateral; // emit LoanStateChanged(state, block.timestamp); } totalInvestedAmount += msg.value.sub(extraMoney); investorsCount++; lenders[investorAddress] = true; investedAmounts[investorAddress] = msg.value.sub(extraMoney); emit Invested(investorAddress, msg.value.sub(extraMoney), block.timestamp); // TODO move to the if condition from above? if (collateral == 0 && totalInvestedAmount == requestedAmount) state = State.withdrawable; } /** @dev Repayment function. * Allows borrower to make repayment installments. */ function repay() public onlyBorrower canRepay payable { require(repaidAmount < returnAmount); require(msg.value >= repaymentInstallment.mantissa); // Update last repayment date lastRepaymentDate = block.timestamp; uint extraMoney = 0; // if (msg.value > repaymentInstallment.mantissa) { // // extraMoney = msg.value.sub(repaymentInstallment.mantissa); // // assert(repaymentInstallment.mantissa == msg.value.sub(extraMoney)); // // // Check the underflow // assert(extraMoney < msg.value); // // payable(msg.sender).transfer(extraMoney); // // emit ExtraAmountRefunded(msg.sender, extraMoney, block.timestamp); // } repaidAmount += (msg.value - extraMoney); emit LogBorrowerRepaymentInstallment(msg.sender, msg.value - extraMoney, block.timestamp); if (repaidAmount >= returnAmount) { emit LogBorrowerRepaymentFinished(msg.sender, block.timestamp); // once the loan is finished, investors can ask for interest state = State.interestReturns; emit LoanStateChanged(state, block.timestamp); // increase user's TScore after a successful loan project if (User(borrowerUser).getSocialRecommendationScore() - successfulLoanScoreIncrease <= 100) User(borrowerUser).setSocialRecommendationScore(User(borrowerUser).getSocialRecommendationScore() + successfulLoanScoreIncrease); else User(borrowerUser).setSocialRecommendationScore(100); } } /** @dev Withdraw function. * It can only be executed while contract is in active state. * It is only accessible to the borrower. * It is only accessible if the needed amount is gathered in the contract. * It can only be executed once. * It can be executed only after lending period * Transfers the gathered amount to the borrower. */ function withdraw() public onlyBorrower canWithdraw isNotFraud payable { // Set the state to repayment so we can avoid reentrancy. state = State.repayment; // Log state change. emit LoanStateChanged(state, block.timestamp); // Log borrower withdrawal. emit LogBorrowerWithdrawal(msg.sender, requestedAmount, block.timestamp); // Transfer the gathered amount to the loan borrower. payable(borrower).transfer(requestedAmount); } /** @dev Request interest function. * It can only be executed while contract is in active state. * It is only accessible to lenders. * It is only accessible if lender funded 1 or more wei. * It can only be executed once. * Transfers the lended amount + interest to the lender. */ function claimWithInterest() public isActive canAskForInterest { checkFraud(); // calculate the amount to be returned uint returnInterestAmount = 0; if (lenders[msg.sender]) { // Calculate the interest amount to return to the lender returnInterestAmount += ExponentialNoError.mul_ScalarTruncateAddUInt( // multiply the amount by the interest rate ExponentialNoError.div_(ExponentialNoError.Exp({ mantissa: interest*(100 - recommendersInterestRate)*1e18}), 10000), investedAmounts[msg.sender], investedAmounts[msg.sender] ); investedAmounts[msg.sender] = 0; } if (recommenders[msg.sender]) { // Calculate the interest amount to return to the recommender uint recommendedAmount = (state != State.fraud) ? recommendedAmounts[msg.sender] : ExponentialNoError.mul_ScalarTruncate( ExponentialNoError.div_( ExponentialNoError.Exp({ mantissa: (totalRecommendedAmount - repaidAmount)}), totalRecommendedAmount ), recommendedAmounts[msg.sender]); returnInterestAmount += ExponentialNoError.mul_ScalarTruncateAddUInt( // multiply the amount by the interest rate ExponentialNoError.div_(ExponentialNoError.Exp({ mantissa: interest*recommendersInterestRate*1e18}), 10000), recommendedAmount, recommendedAmount ); recommendedAmounts[msg.sender] = 0; } if (returnInterestAmount > address(this).balance) returnInterestAmount = address(this).balance; // Assert the contract has enough balance to pay the lender. assert(address(this).balance >= returnInterestAmount); // Transfer the return amount with interest to the lender. payable(msg.sender).transfer(returnInterestAmount); // Log the transfer to lender. emit LogLenderWithdrawal(msg.sender, returnInterestAmount, block.timestamp); // Check if the contract balance is drawned. if (address(this).balance == 0) { /* // Set the active state to false. active = false; // Log active state change. emit LoanActiveStateChanged(active, block.timestamp); // TODO destruct loan? // Set the contract stage to expired e.g. its lifespan is over. state = State.expired; // Log state change. emit LoanStateChanged(state, block.timestamp);*/ LoanController(loanController).finishLoan(borrower); this.destructLoan(payable(address(0))); } } function getState() public view returns (string memory) { if (State.recommendation == state) return "recommendation"; if (State.investment == state) return "investment"; if (State.withdrawable == state) return "withdrawable"; if (State.repayment == state) return "repayment"; if (State.interestReturns == state) return "interestReturns"; if (State.expired == state) return "expired"; if (State.revoked == state) return "revoked"; if (State.fraud == state) return "fraud"; return ""; } function destructLoan(address payable _to) public canDestruct { selfdestruct(_to); } function isExpiredAndNotFunded() public view returns (bool) { require(msg.sender == loanController, "Only Loan Controller can call this method"); // check if investment stage is finished and loan contract doesn't have enough funds to fill the request console.log("test", (block.timestamp - loanCreationDate) > loanExpirationInterval, state != State.withdrawable && state != State.repayment); return (((block.timestamp - loanCreationDate) > loanExpirationInterval) && state != State.withdrawable && state != State.repayment); } function checkFraud() internal { if (block.timestamp > (loanCreationDate + loanExpirationInterval + installmentPeriod*repaymentsCount) && state == State.repayment) { state = State.fraud; } } }
totalInvestedAmount,
function getInfosForBorrower() public view returns ( uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, string memory, uint256, address ) { return ( requestedAmount, interest, repaymentsCount, investorsCount, recommendersCount, requestTScore(), repaymentInstallment.mantissa, returnAmount - repaidAmount, tokenURI, loanCreationDate, address(this) ); }
14,072,165
./partial_match/42/0xf0313F35ECaD232E6876dAA95DF7edf25efcB35e/sources/FeePoolEternalStorage.sol
Import data from FeePool.lastFeeWithdrawal Only callable by the contract owner, and only for 6 weeks after deployment. accounts Array of addresses that have claimed feePeriodIDs Array feePeriodIDs with the accounts last claim/
function importFeeWithdrawalData(address[] accounts, uint[] feePeriodIDs) external onlyOwner onlyDuringSetup { require(accounts.length == feePeriodIDs.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { this.setUIntValue(keccak256(abi.encodePacked(LAST_FEE_WITHDRAWAL, accounts[i])), feePeriodIDs[i]); } }
3,394,357
./partial_match/1/0x5B17f168829968D9fb5F049b45b14b7601AFf85B/sources/ions/ERC721_Remote_Store.sol
Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. The call is not executed if the target address is not a contract. from address representing the previous owner of the given token ID to target address that will receive the tokens tokenId uint256 ID of the token to be transferred _data bytes optional data to send along with the call return ret bool whether the call correctly returned the expected magic value/ solhint-disable-next-line no-inline-assembly
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool ret) { ret = true; if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert("438"); assembly { revert(add(32, reason), mload(reason)) } } } } }
11,032,366
/** *Submitted for verification at Etherscan.io on 2021-06-25 */ /* .'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''.. .;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,. ';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,. ';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,. ...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''.. .,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. ..... .;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'. .';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;. .';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,. .,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,. .,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,.. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. .... ..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. ..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'. ...'.. .';;;;;;;;;;;;;;,,,'. ............... */ // https://github.com/trusttoken/smart-contracts // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency file: @openzeppelin/contracts/math/SafeMath.sol // pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Dependency file: @openzeppelin/contracts/utils/Address.sol // pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Dependency file: @openzeppelin/contracts/GSN/Context.sol // pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Dependency file: contracts/common/Initializable.sol // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol // Added public isInitialized() view of private initialized bool. // pragma solidity 0.6.10; /** * @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; } /** * @dev Return true if and only if the contract has been initialized * @return whether the contract has been initialized */ function isInitialized() public view returns (bool) { return initialized; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // Dependency file: contracts/common/UpgradeableERC20.sol // pragma solidity 0.6.10; // import {Address} from "@openzeppelin/contracts/utils/Address.sol"; // import {Context} from "@openzeppelin/contracts/GSN/Context.sol"; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; // import {Initializable} from "contracts/common/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Initializable, 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. */ function __ERC20_initialize(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 virtual view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override 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 virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual override 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 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 {} function updateNameAndSymbol(string memory __name, string memory __symbol) internal { _name = __name; _symbol = __symbol; } } // Dependency file: contracts/common/UpgradeableClaimable.sol // pragma solidity 0.6.10; // import {Context} from "@openzeppelin/contracts/GSN/Context.sol"; // import {Initializable} from "contracts/common/Initializable.sol"; /** * @title UpgradeableClaimable * @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. Since * this contract combines Claimable and UpgradableOwnable contracts, ownership * can be later change via 2 step method {transferOwnership} and {claimOwnership} * * 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 UpgradeableClaimable is Initializable, Context { address private _owner; address private _pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting a custom initial owner of choice. * @param __owner Initial owner of contract to be set. */ function initialize(address __owner) internal initializer { _owner = __owner; emit OwnershipTransferred(address(0), __owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the pending owner. */ function pendingOwner() public view returns (address) { return _pendingOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == _pendingOwner, "Ownable: caller is not the pending owner"); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(_owner, _pendingOwner); _owner = _pendingOwner; _pendingOwner = address(0); } } // Dependency file: contracts/truefi2/interface/ITrueStrategy.sol // pragma solidity 0.6.10; interface ITrueStrategy { /** * @dev put `amount` of tokens into the strategy * As a result of the deposit value of the strategy should increase by at least 98% of amount */ function deposit(uint256 amount) external; /** * @dev pull at least `minAmount` of tokens from strategy and transfer to the pool */ function withdraw(uint256 minAmount) external; /** * @dev withdraw everything from strategy * As a result of calling withdrawAll(),at least 98% of strategy's value should be transferred to the pool * Value must become 0 */ function withdrawAll() external; /// @dev value evaluated to Pool's tokens function value() external view returns (uint256); } // Dependency file: contracts/truefi2/interface/ILoanToken2.sol // pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {ERC20} from "contracts/common/UpgradeableERC20.sol"; // import {ITrueFiPool2} from "contracts/truefi2/interface/ITrueFiPool2.sol"; interface ILoanToken2 is IERC20 { enum Status {Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated} function borrower() external view returns (address); function amount() external view returns (uint256); function term() external view returns (uint256); function apy() external view returns (uint256); function start() external view returns (uint256); function lender() external view returns (address); function debt() external view returns (uint256); function pool() external view returns (ITrueFiPool2); function profit() external view returns (uint256); function status() external view returns (Status); function getParameters() external view returns ( uint256, uint256, uint256 ); function fund() external; function withdraw(address _beneficiary) external; function settle() external; function enterDefault() external; function liquidate() external; function redeem(uint256 _amount) external; function repay(address _sender, uint256 _amount) external; function repayInFull(address _sender) external; function reclaim() external; function allowTransfer(address account, bool _status) external; function repaid() external view returns (uint256); function isRepaid() external view returns (bool); function balance() external view returns (uint256); function value(uint256 _balance) external view returns (uint256); function token() external view returns (ERC20); function version() external pure returns (uint8); } //interface IContractWithPool { // function pool() external view returns (ITrueFiPool2); //} // //// Had to be split because of multiple inheritance problem //interface ILoanToken2 is ILoanToken, IContractWithPool { // //} // Dependency file: contracts/truefi2/interface/ITrueLender2.sol // pragma solidity 0.6.10; // import {ITrueFiPool2} from "contracts/truefi2/interface/ITrueFiPool2.sol"; // import {ILoanToken2} from "contracts/truefi2/interface/ILoanToken2.sol"; interface ITrueLender2 { // @dev calculate overall value of the pools function value(ITrueFiPool2 pool) external view returns (uint256); // @dev distribute a basket of tokens for exiting user function distribute( address recipient, uint256 numerator, uint256 denominator ) external; function transferAllLoanTokens(ILoanToken2 loan, address recipient) external; } // Dependency file: contracts/truefi2/interface/IERC20WithDecimals.sol // pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20WithDecimals is IERC20 { function decimals() external view returns (uint256); } // Dependency file: contracts/truefi2/interface/ITrueFiPoolOracle.sol // pragma solidity 0.6.10; // import {IERC20WithDecimals} from "contracts/truefi2/interface/IERC20WithDecimals.sol"; /** * @dev Oracle that converts any token to and from TRU * Used for liquidations and valuing of liquidated TRU in the pool */ interface ITrueFiPoolOracle { // token address function token() external view returns (IERC20WithDecimals); // amount of tokens 1 TRU is worth function truToToken(uint256 truAmount) external view returns (uint256); // amount of TRU 1 token is worth function tokenToTru(uint256 tokenAmount) external view returns (uint256); // USD price of token with 18 decimals function tokenToUsd(uint256 tokenAmount) external view returns (uint256); } // Dependency file: contracts/truefi2/interface/I1Inch3.sol // pragma solidity 0.6.10; pragma experimental ABIEncoderV2; interface I1Inch3 { struct SwapDescription { address srcToken; address dstToken; address srcReceiver; address dstReceiver; uint256 amount; uint256 minReturnAmount; uint256 flags; bytes permit; } function swap( address caller, SwapDescription calldata desc, bytes calldata data ) external returns ( uint256 returnAmount, uint256 gasLeft, uint256 chiSpent ); function unoswap( address srcToken, uint256 amount, uint256 minReturn, bytes32[] calldata /* pools */ ) external payable returns (uint256 returnAmount); } // Dependency file: contracts/truefi2/interface/ISAFU.sol // pragma solidity 0.6.10; interface ISAFU { function poolDeficit(address pool) external view returns (uint256); } // Dependency file: contracts/truefi2/interface/ITrueFiPool2.sol // pragma solidity 0.6.10; // import {ERC20, IERC20} from "contracts/common/UpgradeableERC20.sol"; // import {ITrueLender2, ILoanToken2} from "contracts/truefi2/interface/ITrueLender2.sol"; // import {ITrueFiPoolOracle} from "contracts/truefi2/interface/ITrueFiPoolOracle.sol"; // import {I1Inch3} from "contracts/truefi2/interface/I1Inch3.sol"; // import {ISAFU} from "contracts/truefi2/interface/ISAFU.sol"; interface ITrueFiPool2 is IERC20 { function initialize( ERC20 _token, ERC20 _stakingToken, ITrueLender2 _lender, I1Inch3 __1Inch, ISAFU safu, address __owner ) external; function token() external view returns (ERC20); function oracle() external view returns (ITrueFiPoolOracle); /** * @dev Join the pool by depositing tokens * @param amount amount of tokens to deposit */ function join(uint256 amount) external; /** * @dev borrow from pool * 1. Transfer TUSD to sender * 2. Only lending pool should be allowed to call this */ function borrow(uint256 amount) external; /** * @dev pay borrowed money back to pool * 1. Transfer TUSD from sender * 2. Only lending pool should be allowed to call this */ function repay(uint256 currencyAmount) external; /** * @dev SAFU buys LoanTokens from the pool */ function liquidate(ILoanToken2 loan) external; } // Dependency file: contracts/common/interface/IPauseableContract.sol // pragma solidity 0.6.10; /** * @dev interface to allow standard pause function */ interface IPauseableContract { function setPauseStatus(bool pauseStatus) external; } // Dependency file: contracts/truefi/Log.sol /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ // pragma solidity 0.6.10; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt(uint256 x) internal pure returns (int128) { require(x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2(int128 x) internal pure returns (int128) { require(x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = (msb - 64) << 64; uint256 ux = uint256(x) << uint256(127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256(b); } return int128(result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln(int128 x) internal pure returns (int128) { require(x > 0); return int128((uint256(log_2(x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128); } } // Dependency file: contracts/truefi2/libraries/OneInchExchange.sol // pragma solidity 0.6.10; // pragma experimental ABIEncoderV2; // import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; // import {I1Inch3} from "contracts/truefi2/interface/I1Inch3.sol"; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; interface IUniRouter { function token0() external view returns (address); function token1() external view returns (address); } library OneInchExchange { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 constant ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; uint256 constant REVERSE_MASK = 0x8000000000000000000000000000000000000000000000000000000000000000; event Swapped(I1Inch3.SwapDescription description, uint256 returnedAmount); /** * @dev Forward data to 1Inch contract * @param _1inchExchange address of 1Inch (currently 0x11111112542d85b3ef69ae05771c2dccff4faa26 for mainnet) * @param data Data that is forwarded into the 1inch exchange contract. Can be acquired from 1Inch API https://api.1inch.exchange/v3.0/1/swap * [See more](https://docs.1inch.exchange/api/quote-swap#swap) * * @return description - description of the swap */ function exchange(I1Inch3 _1inchExchange, bytes calldata data) internal returns (I1Inch3.SwapDescription memory description, uint256 returnedAmount) { if (data[0] == 0x7c) { // call `swap()` (, description, ) = abi.decode(data[4:], (address, I1Inch3.SwapDescription, bytes)); } else { // call `unoswap()` (address srcToken, uint256 amount, uint256 minReturn, bytes32[] memory pathData) = abi.decode( data[4:], (address, uint256, uint256, bytes32[]) ); description.srcToken = srcToken; description.amount = amount; description.minReturnAmount = minReturn; description.flags = 0; uint256 lastPath = uint256(pathData[pathData.length - 1]); IUniRouter uniRouter = IUniRouter(address(lastPath & ADDRESS_MASK)); bool isReverse = lastPath & REVERSE_MASK > 0; description.dstToken = isReverse ? uniRouter.token0() : uniRouter.token1(); description.dstReceiver = address(this); } IERC20(description.srcToken).safeApprove(address(_1inchExchange), description.amount); uint256 balanceBefore = IERC20(description.dstToken).balanceOf(description.dstReceiver); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(_1inchExchange).call(data); if (!success) { // Revert with original error message assembly { let ptr := mload(0x40) let size := returndatasize() returndatacopy(ptr, 0, size) revert(ptr, size) } } uint256 balanceAfter = IERC20(description.dstToken).balanceOf(description.dstReceiver); returnedAmount = balanceAfter.sub(balanceBefore); emit Swapped(description, returnedAmount); } } // Dependency file: contracts/truefi2/PoolExtensions.sol // pragma solidity 0.6.10; // import {ILoanToken2} from "contracts/truefi2/interface/ILoanToken2.sol"; // import {ITrueLender2} from "contracts/truefi2/interface/ITrueLender2.sol"; // import {ISAFU} from "contracts/truefi2/interface/ISAFU.sol"; /** * @dev Library that has shared functions between legacy TrueFi Pool and Pool2 */ library PoolExtensions { function _liquidate( ISAFU safu, ILoanToken2 loan, ITrueLender2 lender ) internal { require(msg.sender == address(safu), "TrueFiPool: Should be called by SAFU"); lender.transferAllLoanTokens(loan, address(safu)); } } // Root file: contracts/truefi2/TrueFiPool2.sol pragma solidity 0.6.10; // pragma experimental ABIEncoderV2; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; // import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // import {ERC20} from "contracts/common/UpgradeableERC20.sol"; // import {UpgradeableClaimable} from "contracts/common/UpgradeableClaimable.sol"; // import {ITrueStrategy} from "contracts/truefi2/interface/ITrueStrategy.sol"; // import {ITrueFiPool2, ITrueFiPoolOracle, I1Inch3} from "contracts/truefi2/interface/ITrueFiPool2.sol"; // import {ITrueLender2, ILoanToken2} from "contracts/truefi2/interface/ITrueLender2.sol"; // import {IPauseableContract} from "contracts/common/interface/IPauseableContract.sol"; // import {ISAFU} from "contracts/truefi2/interface/ISAFU.sol"; // import {ABDKMath64x64} from "contracts/truefi/Log.sol"; // import {OneInchExchange} from "contracts/truefi2/libraries/OneInchExchange.sol"; // import {PoolExtensions} from "contracts/truefi2/PoolExtensions.sol"; /** * @title TrueFiPool2 * @dev Lending pool which may use a strategy to store idle funds * Earn high interest rates on currency deposits through uncollateralized loans * * Funds deposited in this pool are not fully liquid. * Exiting the pool has 2 options: * - withdraw a basket of LoanTokens backing the pool * - take an exit penalty depending on pool liquidity * After exiting, an account will need to wait for LoanTokens to expire and burn them * It is recommended to perform a zap or swap tokens on Uniswap for increased liquidity * * Funds are managed through an external function to save gas on deposits */ contract TrueFiPool2 is ITrueFiPool2, IPauseableContract, ERC20, UpgradeableClaimable { using SafeMath for uint256; using SafeERC20 for ERC20; using SafeERC20 for IERC20; using OneInchExchange for I1Inch3; uint256 private constant BASIS_PRECISION = 10000; // max slippage on liquidation token swaps // Measured in basis points, e.g. 10000 = 100% uint16 public constant TOLERATED_SLIPPAGE = 100; // 1% // tolerance difference between // expected and actual transaction results // when dealing with strategies // Measured in basis points, e.g. 10000 = 100% uint16 public constant TOLERATED_STRATEGY_LOSS = 10; // 0.1% // ================ WARNING ================== // ===== THIS CONTRACT IS INITIALIZABLE ====== // === STORAGE VARIABLES ARE DECLARED BELOW == // REMOVAL OR REORDER OF VARIABLES WILL RESULT // ========= IN STORAGE CORRUPTION =========== uint8 public constant VERSION = 1; ERC20 public override token; ITrueStrategy public strategy; ITrueLender2 public lender; // fee for deposits // fee precision: 10000 = 100% uint256 public joiningFee; // track claimable fees uint256 public claimableFees; mapping(address => uint256) latestJoinBlock; IERC20 public liquidationToken; ITrueFiPoolOracle public override oracle; // allow pausing of deposits bool public pauseStatus; // cache values during sync for gas optimization bool private inSync; uint256 private strategyValueCache; uint256 private loansValueCache; // who gets all fees address public beneficiary; I1Inch3 public _1Inch; ISAFU public safu; // ======= STORAGE DECLARATION END =========== /** * @dev Helper function to concatenate two strings * @param a First part of string to concat * @param b Second part of string to concat * @return Concatenated string of `a` and `b` */ function concat(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } function initialize( ERC20 _token, ERC20 _liquidationToken, ITrueLender2 _lender, I1Inch3 __1Inch, ISAFU _safu, address __owner ) external override initializer { ERC20.__ERC20_initialize(concat("TrueFi ", _token.name()), concat("tf", _token.symbol())); UpgradeableClaimable.initialize(__owner); token = _token; liquidationToken = _liquidationToken; lender = _lender; safu = _safu; _1Inch = __1Inch; } /** * @dev Emitted when fee is changed * @param newFee New fee */ event JoiningFeeChanged(uint256 newFee); /** * @dev Emitted when beneficiary is changed * @param newBeneficiary New beneficiary */ event BeneficiaryChanged(address newBeneficiary); /** * @dev Emitted when oracle is changed * @param newOracle New oracle */ event OracleChanged(ITrueFiPoolOracle newOracle); /** * @dev Emitted when someone joins the pool * @param staker Account staking * @param deposited Amount deposited * @param minted Amount of pool tokens minted */ event Joined(address indexed staker, uint256 deposited, uint256 minted); /** * @dev Emitted when someone exits the pool * @param staker Account exiting * @param amount Amount unstaking */ event Exited(address indexed staker, uint256 amount); /** * @dev Emitted when funds are flushed into the strategy * @param currencyAmount Amount of tokens deposited */ event Flushed(uint256 currencyAmount); /** * @dev Emitted when funds are pulled from the strategy * @param minTokenAmount Minimal expected amount received tokens */ event Pulled(uint256 minTokenAmount); /** * @dev Emitted when funds are borrowed from pool * @param borrower Borrower address * @param amount Amount of funds borrowed from pool */ event Borrow(address borrower, uint256 amount); /** * @dev Emitted when borrower repays the pool * @param payer Address of borrower * @param amount Amount repaid */ event Repaid(address indexed payer, uint256 amount); /** * @dev Emitted when fees are collected * @param beneficiary Account to receive fees * @param amount Amount of fees collected */ event Collected(address indexed beneficiary, uint256 amount); /** * @dev Emitted when strategy is switched * @param newStrategy Strategy to switch to */ event StrategySwitched(ITrueStrategy newStrategy); /** * @dev Emitted when joining is paused or unpaused * @param pauseStatus New pausing status */ event PauseStatusChanged(bool pauseStatus); /** * @dev Emitted when SAFU address is changed * @param newSafu New SAFU address */ event SafuChanged(ISAFU newSafu); /** * @dev only lender can perform borrowing or repaying */ modifier onlyLender() { require(msg.sender == address(lender), "TrueFiPool: Caller is not the lender"); _; } /** * @dev pool can only be joined when it's unpaused */ modifier joiningNotPaused() { require(!pauseStatus, "TrueFiPool: Joining the pool is paused"); _; } /** * Sync values to avoid making expensive calls multiple times * Will set inSync to true, allowing getter functions to return cached values * Wipes cached values to save gas */ modifier sync() { // sync strategyValueCache = strategyValue(); loansValueCache = loansValue(); inSync = true; _; // wipe inSync = false; strategyValueCache = 0; loansValueCache = 0; } /** * @dev Allow pausing of deposits in case of emergency * @param status New deposit status */ function setPauseStatus(bool status) external override onlyOwner { pauseStatus = status; emit PauseStatusChanged(status); } /** * @dev Change SAFU address */ function setSafuAddress(ISAFU _safu) external onlyOwner { safu = _safu; emit SafuChanged(_safu); } /** * @dev Number of decimals for user-facing representations. * Delegates to the underlying pool token. */ function decimals() public override view returns (uint8) { return token.decimals(); } /** * @dev Virtual value of liquid assets in the pool * @return Virtual liquid value of pool assets */ function liquidValue() public view returns (uint256) { return currencyBalance().add(strategyValue()); } /** * @dev Value of funds deposited into the strategy denominated in underlying token * @return Virtual value of strategy */ function strategyValue() public view returns (uint256) { if (address(strategy) == address(0)) { return 0; } if (inSync) { return strategyValueCache; } return strategy.value(); } /** * @dev Calculate pool value in underlying token * "virtual price" of entire pool - LoanTokens, UnderlyingTokens, strategy value * @return pool value denominated in underlying token */ function poolValue() public view returns (uint256) { // this assumes defaulted loans are worth their full value return liquidValue().add(loansValue()).add(deficitValue()); } /** * @dev Return pool deficiency value, to be returned by safu * @return pool deficiency value */ function deficitValue() public view returns (uint256) { if (address(safu) == address(0)) { return 0; } return safu.poolDeficit(address(this)); } /** * @dev Get total balance of stake tokens * @return Balance of stake tokens denominated in this contract */ function liquidationTokenBalance() public view returns (uint256) { return liquidationToken.balanceOf(address(this)); } /** * @dev Price of TRU denominated in underlying tokens * @return Oracle price of TRU in underlying tokens */ function liquidationTokenValue() public view returns (uint256) { uint256 balance = liquidationTokenBalance(); if (balance == 0 || address(oracle) == address(0)) { return 0; } // Use conservative price estimation to avoid pool being overvalued return withToleratedSlippage(oracle.truToToken(balance)); } /** * @dev Virtual value of loan assets in the pool * Will return cached value if inSync * @return Value of loans in pool */ function loansValue() public view returns (uint256) { if (inSync) { return loansValueCache; } return lender.value(this); } /** * @dev ensure enough tokens are available * Check if current available amount of `token` is enough and * withdraw remainder from strategy * @param neededAmount amount required */ function ensureSufficientLiquidity(uint256 neededAmount) internal { uint256 currentlyAvailableAmount = currencyBalance(); if (currentlyAvailableAmount < neededAmount) { require(address(strategy) != address(0), "TrueFiPool: Pool has no strategy to withdraw from"); strategy.withdraw(neededAmount.sub(currentlyAvailableAmount)); require(currencyBalance() >= neededAmount, "TrueFiPool: Not enough funds taken from the strategy"); } } /** * @dev set pool join fee * @param fee new fee */ function setJoiningFee(uint256 fee) external onlyOwner { require(fee <= BASIS_PRECISION, "TrueFiPool: Fee cannot exceed transaction value"); joiningFee = fee; emit JoiningFeeChanged(fee); } /** * @dev set beneficiary * @param newBeneficiary new beneficiary */ function setBeneficiary(address newBeneficiary) external onlyOwner { require(newBeneficiary != address(0), "TrueFiPool: Beneficiary address cannot be set to 0"); beneficiary = newBeneficiary; emit BeneficiaryChanged(newBeneficiary); } /** * @dev Join the pool by depositing tokens * @param amount amount of token to deposit */ function join(uint256 amount) external override joiningNotPaused { uint256 fee = amount.mul(joiningFee).div(BASIS_PRECISION); uint256 mintedAmount = mint(amount.sub(fee)); claimableFees = claimableFees.add(fee); // TODO: tx.origin will be depricated in a future ethereum upgrade latestJoinBlock[tx.origin] = block.number; token.safeTransferFrom(msg.sender, address(this), amount); emit Joined(msg.sender, amount, mintedAmount); } /** * @dev Exit pool * This function will withdraw a basket of currencies backing the pool value * @param amount amount of pool tokens to redeem for underlying tokens */ function exit(uint256 amount) external { require(block.number != latestJoinBlock[tx.origin], "TrueFiPool: Cannot join and exit in same block"); require(amount <= balanceOf(msg.sender), "TrueFiPool: Insufficient funds"); uint256 _totalSupply = totalSupply(); // get share of tokens kept in the pool uint256 liquidAmountToTransfer = amount.mul(liquidValue()).div(_totalSupply); // burn tokens sent _burn(msg.sender, amount); // withdraw basket of loan tokens lender.distribute(msg.sender, amount, _totalSupply); // if tokens remaining, transfer if (liquidAmountToTransfer > 0) { ensureSufficientLiquidity(liquidAmountToTransfer); token.safeTransfer(msg.sender, liquidAmountToTransfer); } emit Exited(msg.sender, amount); } /** * @dev Exit pool only with liquid tokens * This function will only transfer underlying token but with a small penalty * Uses the sync() modifier to reduce gas costs of using strategy and lender * @param amount amount of pool liquidity tokens to redeem for underlying tokens */ function liquidExit(uint256 amount) external sync { require(block.number != latestJoinBlock[tx.origin], "TrueFiPool: Cannot join and exit in same block"); require(amount <= balanceOf(msg.sender), "TrueFiPool: Insufficient funds"); uint256 amountToWithdraw = poolValue().mul(amount).div(totalSupply()); amountToWithdraw = amountToWithdraw.mul(liquidExitPenalty(amountToWithdraw)).div(BASIS_PRECISION); require(amountToWithdraw <= liquidValue(), "TrueFiPool: Not enough liquidity in pool"); // burn tokens sent _burn(msg.sender, amount); ensureSufficientLiquidity(amountToWithdraw); token.safeTransfer(msg.sender, amountToWithdraw); emit Exited(msg.sender, amountToWithdraw); } /** * @dev Penalty (in % * 100) applied if liquid exit is performed with this amount * returns BASIS_PRECISION (10000) if no penalty */ function liquidExitPenalty(uint256 amount) public view returns (uint256) { uint256 lv = liquidValue(); uint256 pv = poolValue(); if (amount == pv) { return BASIS_PRECISION; } uint256 liquidRatioBefore = lv.mul(BASIS_PRECISION).div(pv); uint256 liquidRatioAfter = lv.sub(amount).mul(BASIS_PRECISION).div(pv.sub(amount)); return BASIS_PRECISION.sub(averageExitPenalty(liquidRatioAfter, liquidRatioBefore)); } /** * @dev Calculates integral of 5/(x+50)dx times 10000 */ function integrateAtPoint(uint256 x) public pure returns (uint256) { return uint256(ABDKMath64x64.ln(ABDKMath64x64.fromUInt(x.add(50)))).mul(50000).div(2**64); } /** * @dev Calculates average penalty on interval [from; to] * @return average exit penalty */ function averageExitPenalty(uint256 from, uint256 to) public pure returns (uint256) { require(from <= to, "TrueFiPool: To precedes from"); if (from == BASIS_PRECISION) { // When all liquid, don't penalize return 0; } if (from == to) { return uint256(50000).div(from.add(50)); } return integrateAtPoint(to).sub(integrateAtPoint(from)).div(to.sub(from)); } /** * @dev Deposit idle funds into strategy * @param amount Amount of funds to deposit into strategy */ function flush(uint256 amount) external { require(address(strategy) != address(0), "TrueFiPool: Pool has no strategy set up"); require(amount <= currencyBalance(), "TrueFiPool: Insufficient currency balance"); uint256 expectedMinStrategyValue = strategy.value().add(withToleratedStrategyLoss(amount)); token.safeApprove(address(strategy), amount); strategy.deposit(amount); require(strategy.value() >= expectedMinStrategyValue, "TrueFiPool: Strategy value expected to be higher"); emit Flushed(amount); } /** * @dev Remove liquidity from strategy * @param minTokenAmount minimum amount of tokens to withdraw */ function pull(uint256 minTokenAmount) external onlyOwner { require(address(strategy) != address(0), "TrueFiPool: Pool has no strategy set up"); uint256 expectedCurrencyBalance = currencyBalance().add(minTokenAmount); strategy.withdraw(minTokenAmount); require(currencyBalance() >= expectedCurrencyBalance, "TrueFiPool: Currency balance expected to be higher"); emit Pulled(minTokenAmount); } /** * @dev Remove liquidity from strategy if necessary and transfer to lender * @param amount amount for lender to withdraw */ function borrow(uint256 amount) external override onlyLender { require(amount <= liquidValue(), "TrueFiPool: Insufficient liquidity"); if (amount > 0) { ensureSufficientLiquidity(amount); } token.safeTransfer(msg.sender, amount); emit Borrow(msg.sender, amount); } /** * @dev repay debt by transferring tokens to the contract * @param currencyAmount amount to repay */ function repay(uint256 currencyAmount) external override onlyLender { token.safeTransferFrom(msg.sender, address(this), currencyAmount); emit Repaid(msg.sender, currencyAmount); } /** * @dev Claim fees from the pool */ function collectFees() external { require(beneficiary != address(0), "TrueFiPool: Beneficiary is not set"); uint256 amount = claimableFees; claimableFees = 0; if (amount > 0) { token.safeTransfer(beneficiary, amount); } emit Collected(beneficiary, amount); } /** * @dev Switches current strategy to a new strategy * @param newStrategy strategy to switch to */ function switchStrategy(ITrueStrategy newStrategy) external onlyOwner { require(strategy != newStrategy, "TrueFiPool: Cannot switch to the same strategy"); ITrueStrategy previousStrategy = strategy; strategy = newStrategy; if (address(previousStrategy) != address(0)) { uint256 expectedMinCurrencyBalance = currencyBalance().add(withToleratedStrategyLoss(previousStrategy.value())); previousStrategy.withdrawAll(); require(currencyBalance() >= expectedMinCurrencyBalance, "TrueFiPool: All funds should be withdrawn to pool"); require(previousStrategy.value() == 0, "TrueFiPool: Switched strategy should be depleted"); } emit StrategySwitched(newStrategy); } /** * @dev Function called by SAFU when liquidation happens. It will transfer all tokens of this loan the SAFU */ function liquidate(ILoanToken2 loan) external override { PoolExtensions._liquidate(safu, loan, lender); } /** * @dev Change oracle, can only be called by owner */ function setOracle(ITrueFiPoolOracle newOracle) external onlyOwner { oracle = newOracle; emit OracleChanged(newOracle); } function sellLiquidationToken(bytes calldata data) external { (I1Inch3.SwapDescription memory swap, uint256 balanceDiff) = _1Inch.exchange(data); uint256 expectedGain = oracle.truToToken(swap.amount); require(balanceDiff >= withToleratedSlippage(expectedGain), "TrueFiPool: Not optimal exchange"); require(swap.srcToken == address(liquidationToken), "TrueFiPool: Source token is not TRU"); require(swap.dstToken == address(token), "TrueFiPool: Invalid destination token"); require(swap.dstReceiver == address(this), "TrueFiPool: Receiver is not pool"); } /** * @dev Currency token balance * @return Currency token balance */ function currencyBalance() public view returns (uint256) { return token.balanceOf(address(this)).sub(claimableFees); } /** * @param depositedAmount Amount of currency deposited * @return amount minted from this transaction */ function mint(uint256 depositedAmount) internal returns (uint256) { if (depositedAmount == 0) { return depositedAmount; } uint256 mintedAmount = depositedAmount; // first staker mints same amount as deposited if (totalSupply() > 0) { mintedAmount = totalSupply().mul(depositedAmount).div(poolValue()); } // mint pool liquidity tokens _mint(msg.sender, mintedAmount); return mintedAmount; } /** * @dev Decrease provided amount percentwise by error * @param amount Amount to decrease * @return Calculated value */ function withToleratedSlippage(uint256 amount) internal pure returns (uint256) { return amount.mul(BASIS_PRECISION - TOLERATED_SLIPPAGE).div(BASIS_PRECISION); } /** * @dev Decrease provided amount percentwise by error * @param amount Amount to decrease * @return Calculated value */ function withToleratedStrategyLoss(uint256 amount) internal pure returns (uint256) { return amount.mul(BASIS_PRECISION - TOLERATED_STRATEGY_LOSS).div(BASIS_PRECISION); } }
Calculate pool value in underlying token "virtual price" of entire pool - LoanTokens, UnderlyingTokens, strategy value return pool value denominated in underlying token/ this assumes defaulted loans are worth their full value
function poolValue() public view returns (uint256) { return liquidValue().add(loansValue()).add(deficitValue()); }
10,810,061